Skip to content

Commit

Permalink
Merge pull request #548 from FriendsOfCake/beforesave
Browse files Browse the repository at this point in the history
Skip processing in beforeSave() if value is not instance of UploadedFileInterface
  • Loading branch information
ADmad committed Oct 27, 2020
2 parents 2b0e781 + 7fc65ea commit ec02c87
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/Model/Behavior/UploadBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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();
Expand Down
21 changes: 21 additions & 0 deletions tests/TestCase/Model/Behavior/UploadBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand Down

0 comments on commit ec02c87

Please sign in to comment.