DonorRepositoryProxy.php
78 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Donors\Repositories; |
| 4 | |
| 5 | use Give\Donors\Models\Donor; |
| 6 | use Give\Framework\Exceptions\Primitives\InvalidArgumentException; |
| 7 | use Give_DB_Donors; |
| 8 | |
| 9 | /** |
| 10 | * This proxy determines which donors repository to call donors->method() from. |
| 11 | * In the case of naming conflicts, we will manually check SHARED_METHOD against their arguments. |
| 12 | * |
| 13 | * @since 2.19.6 |
| 14 | * |
| 15 | * @mixin DonorRepository |
| 16 | * @mixin Give_DB_Donors |
| 17 | * |
| 18 | * @throws InvalidArgumentException |
| 19 | */ |
| 20 | #[\AllowDynamicProperties] |
| 21 | class DonorRepositoryProxy |
| 22 | { |
| 23 | const SHARED_METHODS = ['insert', 'update', 'delete']; |
| 24 | |
| 25 | /** |
| 26 | * @var Give_DB_Donors |
| 27 | */ |
| 28 | private $legacyDonorRepository; |
| 29 | /** |
| 30 | * @var DonorRepository |
| 31 | */ |
| 32 | private $donorRepository; |
| 33 | |
| 34 | /** |
| 35 | * The Give_DB_Donors class extends Give_DB which has & assigns public properties that we need to |
| 36 | * dynamically assign to this proxy class or else they won't be accessible. |
| 37 | * |
| 38 | * @since 2.19.6 |
| 39 | */ |
| 40 | public function __construct(Give_DB_Donors $legacyDonorRepository, DonorRepository $donorRepository) |
| 41 | { |
| 42 | $this->legacyDonorRepository = $legacyDonorRepository; |
| 43 | $this->donorRepository = $donorRepository; |
| 44 | |
| 45 | $properties = get_object_vars($legacyDonorRepository); |
| 46 | |
| 47 | foreach ($properties as $key => $value) { |
| 48 | $this->$key = $value; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * @since 2.19.6 |
| 54 | * |
| 55 | * @param string $method |
| 56 | * @param array $parameters |
| 57 | * @return mixed |
| 58 | */ |
| 59 | public function __call($method, $parameters) |
| 60 | { |
| 61 | if (in_array($method, self::SHARED_METHODS, true)) { |
| 62 | return $parameters[0] instanceof Donor ? $this->donorRepository->{$method}( |
| 63 | ...$parameters |
| 64 | ) : $this->legacyDonorRepository->{$method}(...$parameters); |
| 65 | } |
| 66 | |
| 67 | if (method_exists($this->donorRepository, $method)) { |
| 68 | return $this->donorRepository->{$method}(...$parameters); |
| 69 | } |
| 70 | |
| 71 | if (method_exists($this->legacyDonorRepository, $method)) { |
| 72 | return $this->legacyDonorRepository->{$method}(...$parameters); |
| 73 | } |
| 74 | |
| 75 | throw new InvalidArgumentException("$method does not exist."); |
| 76 | } |
| 77 | } |
| 78 |