DonorNotesRepository.php
1 year ago
DonorRepository.php
8 months ago
DonorRepositoryProxy.php
1 year ago
DonorRepositoryProxy.php
89 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 | * @var DonorNotesRepository |
| 36 | */ |
| 37 | public $notes; |
| 38 | |
| 39 | /** |
| 40 | * The Give_DB_Donors class extends Give_DB which has & assigns public properties that we need to |
| 41 | * dynamically assign to this proxy class or else they won't be accessible. |
| 42 | * |
| 43 | * @since 4.4.0 Add "notes" property |
| 44 | * @since 2.19.6 |
| 45 | */ |
| 46 | public function __construct( |
| 47 | Give_DB_Donors $legacyDonorRepository, |
| 48 | DonorRepository $donorRepository, |
| 49 | DonorNotesRepository $donorNotesRepository |
| 50 | ) |
| 51 | { |
| 52 | $this->legacyDonorRepository = $legacyDonorRepository; |
| 53 | $this->donorRepository = $donorRepository; |
| 54 | $this->notes = $donorNotesRepository; |
| 55 | |
| 56 | $properties = get_object_vars($legacyDonorRepository); |
| 57 | |
| 58 | foreach ($properties as $key => $value) { |
| 59 | $this->$key = $value; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * @since 2.19.6 |
| 65 | * |
| 66 | * @param string $method |
| 67 | * @param array $parameters |
| 68 | * @return mixed |
| 69 | */ |
| 70 | public function __call($method, $parameters) |
| 71 | { |
| 72 | if (in_array($method, self::SHARED_METHODS, true)) { |
| 73 | return $parameters[0] instanceof Donor ? $this->donorRepository->{$method}( |
| 74 | ...$parameters |
| 75 | ) : $this->legacyDonorRepository->{$method}(...$parameters); |
| 76 | } |
| 77 | |
| 78 | if (method_exists($this->donorRepository, $method)) { |
| 79 | return $this->donorRepository->{$method}(...$parameters); |
| 80 | } |
| 81 | |
| 82 | if (method_exists($this->legacyDonorRepository, $method)) { |
| 83 | return $this->legacyDonorRepository->{$method}(...$parameters); |
| 84 | } |
| 85 | |
| 86 | throw new InvalidArgumentException("$method does not exist."); |
| 87 | } |
| 88 | } |
| 89 |