|
| 1 | +<?php |
| 2 | +namespace App\Model\Table; |
| 3 | + |
| 4 | +use Cake\Event\Event; |
| 5 | +use Cake\Datasource\EntityInterface; |
| 6 | +use Cake\Filesystem\File; |
| 7 | +use Cake\ORM\Entity; |
| 8 | +use Cake\ORM\Table; |
| 9 | +use Burzum\FileStorage\Model\Table\ImageStorageTable; |
| 10 | + |
| 11 | +class AppImagesTable extends ImageStorageTable { |
| 12 | + |
| 13 | + /** |
| 14 | + * afterSave callback |
| 15 | + * |
| 16 | + * Does not call the parent to avoid that the regular file storage event listener saves the image already |
| 17 | + * |
| 18 | + * @param Event $event event |
| 19 | + * @param EntityInterface $entity entity |
| 20 | + * @param array $options options |
| 21 | + * @return bool |
| 22 | + */ |
| 23 | + public function afterSave(Event $event, EntityInterface $entity, $options) |
| 24 | + { |
| 25 | + if ($entity->isNew()) { |
| 26 | + if (empty($entity->tmp_name)) { |
| 27 | + return true; |
| 28 | + } |
| 29 | + $file = [ |
| 30 | + 'tmp_name' => $entity->tmp_name, |
| 31 | + ]; |
| 32 | + $entity->file = $file; |
| 33 | + $entity->filename = $entity['name']; |
| 34 | + $entity->filesize = $entity['size']; |
| 35 | + $file = new File($entity['name']); |
| 36 | + $entity->extension = $file->ext(); |
| 37 | + $imageEvent = new Event('ImageStorage.afterSave', $this, [ |
| 38 | + 'storage' => $this->storageAdapter($entity['adapter']), |
| 39 | + 'record' => $entity |
| 40 | + ]); |
| 41 | + $this->eventManager()->dispatch($imageEvent); |
| 42 | + $this->_cleanupImages($entity); |
| 43 | + } |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Cleanup all the old images uploaded, keeping only the latest one after edit |
| 49 | + * |
| 50 | + * @param EntityInterface $entity entity |
| 51 | + * @return void |
| 52 | + */ |
| 53 | + protected function _cleanupImages($entity) |
| 54 | + { |
| 55 | + $oldImages = $this->find() |
| 56 | + ->where([ |
| 57 | + 'id !=' => $entity['id'], |
| 58 | + 'foreign_key' => $entity['foreign_key'], |
| 59 | + 'model' => $entity['model'], |
| 60 | + ]); |
| 61 | + $oldImages->each(function ($oldImage) { |
| 62 | + if (empty($oldImage['filename'])) { |
| 63 | + $this->deleteAll([ |
| 64 | + 'id' => $oldImage['id'], |
| 65 | + ]); |
| 66 | + } else { |
| 67 | + $this->delete($oldImage); |
| 68 | + } |
| 69 | + }); |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments