Skip to content

Commit ec02c87

Browse files
authored
Merge pull request #548 from FriendsOfCake/beforesave
Skip processing in beforeSave() if value is not instance of UploadedFileInterface
2 parents 2b0e781 + 7fc65ea commit ec02c87

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/Model/Behavior/UploadBehavior.php

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,15 @@ public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObj
9595
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)
9696
{
9797
foreach ($this->getConfig(null, []) as $field => $settings) {
98-
if (in_array($field, $this->protectedFieldNames)) {
98+
if (
99+
in_array($field, $this->protectedFieldNames, true)
100+
|| !$entity->isDirty($field)
101+
) {
99102
continue;
100103
}
101104

102-
if (empty($entity->get($field)) || !$entity->isDirty($field)) {
105+
$data = $entity->get($field);
106+
if (!$data instanceof UploadedFileInterface) {
103107
continue;
104108
}
105109

@@ -111,7 +115,6 @@ public function beforeSave(EventInterface $event, EntityInterface $entity, Array
111115
continue;
112116
}
113117

114-
$data = $entity->get($field);
115118
$path = $this->getPathProcessor($entity, $data, $field, $settings);
116119
$basepath = $path->basepath();
117120
$filename = $path->filename();

tests/TestCase/Model/Behavior/UploadBehaviorTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,27 @@ public function testBeforeSaveWithProtectedFieldName()
383383
$this->assertNull($behavior->beforeSave(new Event('fake.event'), $this->entity, new ArrayObject()));
384384
}
385385

386+
public function testBeforeSaveWithFieldValueAsString()
387+
{
388+
$methods = array_diff($this->behaviorMethods, ['beforeSave', 'config', 'setConfig', 'getConfig']);
389+
/** @var \Josegonzalez\Upload\Model\Behavior\UploadBehavior $behavior */
390+
$behavior = $this->getMockBuilder(UploadBehavior::class)
391+
->onlyMethods($methods)
392+
->setConstructorArgs([$this->table, $this->settings])
393+
->getMock();
394+
395+
$this->entity->expects($this->any())
396+
->method('get')
397+
->with('field')
398+
->will($this->returnValue('file.jpg'));
399+
$this->entity->expects($this->any())
400+
->method('isDirty')
401+
->with('field')
402+
->will($this->returnValue(true));
403+
404+
$this->assertNull($behavior->beforeSave(new Event('fake.event'), $this->entity, new ArrayObject()));
405+
}
406+
386407
public function testAfterDeleteOk()
387408
{
388409
$methods = array_diff($this->behaviorMethods, ['afterDelete', 'config', 'setConfig', 'getConfig']);

0 commit comments

Comments
 (0)