umbrellio /
php-table-sync
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Umbrellio\TableSync\Integration\Laravel; |
||
| 6 | |||
| 7 | use Umbrellio\TableSync\Integration\Laravel\Contracts\SyncableModel; |
||
| 8 | use Umbrellio\TableSync\Messages\PublishMessage; |
||
| 9 | use Umbrellio\TableSync\Publisher; |
||
| 10 | |||
| 11 | class Syncer |
||
| 12 | { |
||
| 13 | private const EVENT_CREATED = 'created'; |
||
| 14 | private const EVENT_UPDATED = 'updated'; |
||
| 15 | private const EVENT_DELETED = 'deleted'; |
||
| 16 | |||
| 17 | private $publisher; |
||
| 18 | |||
| 19 | 12 | public function __construct(Publisher $publisher) |
|
| 20 | { |
||
| 21 | 12 | $this->publisher = $publisher; |
|
| 22 | } |
||
| 23 | |||
| 24 | 12 | public function syncCreated(SyncableModel $model): void |
|
| 25 | { |
||
| 26 | 12 | $this->syncTable($model, self::EVENT_CREATED); |
|
| 27 | } |
||
| 28 | |||
| 29 | 5 | public function syncUpdated(SyncableModel $model): void |
|
| 30 | { |
||
| 31 | 5 | $this->syncTable($model, self::EVENT_UPDATED); |
|
| 32 | } |
||
| 33 | |||
| 34 | 3 | public function syncDeleted(SyncableModel $model): void |
|
| 35 | { |
||
| 36 | 3 | $this->syncTable($model, self::EVENT_DELETED); |
|
| 37 | } |
||
| 38 | |||
| 39 | 12 | private function syncTable(SyncableModel $model, string $event): void |
|
| 40 | { |
||
| 41 | 12 | $attributes = $this->getSyncableAttributes($model); |
|
| 42 | |||
| 43 | 12 | if (!$this->needsPublishAttributes($model, $attributes)) { |
|
| 44 | 1 | return; |
|
| 45 | } |
||
| 46 | |||
| 47 | 12 | $this->publisher->publish(new PublishMessage( |
|
| 48 | 12 | $model->classForSync(), |
|
| 49 | 12 | $event, |
|
| 50 | 12 | $model->routingKey(), |
|
| 51 | 12 | $attributes |
|
| 52 | 12 | )); |
|
| 53 | } |
||
| 54 | |||
| 55 | 12 | private function getSyncableAttributes(SyncableModel $model): array |
|
| 56 | { |
||
| 57 | 12 | if (!$model->exists()) { |
|
| 58 | 3 | return $this->pkAttributes($model); |
|
| 59 | } |
||
| 60 | |||
| 61 | 12 | return array_merge($this->pkAttributes($model), $model->getTableSyncableAttributes()); |
|
| 62 | } |
||
| 63 | |||
| 64 | 12 | private function needsPublishAttributes(SyncableModel $model, array $attributes): bool |
|
|
0 ignored issues
–
show
|
|||
| 65 | { |
||
| 66 | 12 | return !$model->exists() || $model->fresh(); |
|
| 67 | } |
||
| 68 | |||
| 69 | 12 | private function pkAttributes(SyncableModel $model): array |
|
| 70 | { |
||
| 71 | 12 | return [ |
|
| 72 | 12 | $model->getKeyName() => $model->getKey(), |
|
| 73 | 12 | ]; |
|
| 74 | } |
||
| 75 | } |
||
| 76 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.