From 7fc65ea529fc854595c3da71e9dca732dbd43ef5 Mon Sep 17 00:00:00 2001 From: ADmad Date: Tue, 27 Oct 2020 12:21:44 +0530 Subject: [PATCH] Skip processing in beforeSave() if value is not instance of UploadedFileInterface Refs #535 --- src/Model/Behavior/UploadBehavior.php | 9 +++++--- .../Model/Behavior/UploadBehaviorTest.php | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/Model/Behavior/UploadBehavior.php b/src/Model/Behavior/UploadBehavior.php index 2296215c..a98318b6 100644 --- a/src/Model/Behavior/UploadBehavior.php +++ b/src/Model/Behavior/UploadBehavior.php @@ -95,11 +95,15 @@ public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObj public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options) { foreach ($this->getConfig(null, []) as $field => $settings) { - if (in_array($field, $this->protectedFieldNames)) { + if ( + in_array($field, $this->protectedFieldNames, true) + || !$entity->isDirty($field) + ) { continue; } - if (empty($entity->get($field)) || !$entity->isDirty($field)) { + $data = $entity->get($field); + if (!$data instanceof UploadedFileInterface) { continue; } @@ -111,7 +115,6 @@ public function beforeSave(EventInterface $event, EntityInterface $entity, Array continue; } - $data = $entity->get($field); $path = $this->getPathProcessor($entity, $data, $field, $settings); $basepath = $path->basepath(); $filename = $path->filename(); diff --git a/tests/TestCase/Model/Behavior/UploadBehaviorTest.php b/tests/TestCase/Model/Behavior/UploadBehaviorTest.php index 0c9f94e6..d4565429 100644 --- a/tests/TestCase/Model/Behavior/UploadBehaviorTest.php +++ b/tests/TestCase/Model/Behavior/UploadBehaviorTest.php @@ -383,6 +383,27 @@ public function testBeforeSaveWithProtectedFieldName() $this->assertNull($behavior->beforeSave(new Event('fake.event'), $this->entity, new ArrayObject())); } + public function testBeforeSaveWithFieldValueAsString() + { + $methods = array_diff($this->behaviorMethods, ['beforeSave', 'config', 'setConfig', 'getConfig']); + /** @var \Josegonzalez\Upload\Model\Behavior\UploadBehavior $behavior */ + $behavior = $this->getMockBuilder(UploadBehavior::class) + ->onlyMethods($methods) + ->setConstructorArgs([$this->table, $this->settings]) + ->getMock(); + + $this->entity->expects($this->any()) + ->method('get') + ->with('field') + ->will($this->returnValue('file.jpg')); + $this->entity->expects($this->any()) + ->method('isDirty') + ->with('field') + ->will($this->returnValue(true)); + + $this->assertNull($behavior->beforeSave(new Event('fake.event'), $this->entity, new ArrayObject())); + } + public function testAfterDeleteOk() { $methods = array_diff($this->behaviorMethods, ['afterDelete', 'config', 'setConfig', 'getConfig']);