FriendsOfCake / cakephp-upload

CakePHP: Handle file uploading sans ridiculous automagic
https://cakephp-upload.readthedocs.io/
MIT License
551 stars 255 forks source link

Improve nameCallback by adding $table, $entry and $field #477

Closed MAFLO321 closed 6 years ago

MAFLO321 commented 6 years ago

This adds $table, $entry and $field to the signature of the nameCallback function.

'nameCallback' => function ($table, $entity, $data, $field, $settings) { ... }

That gives the ability to change the filename more dynamically.

For example

It is now possible to update the name of a file only if it is a new entity:

'nameCallback' => function ($table, $entity, $data, $field, $settings) {
    // Rename destination filename
    $ext = pathinfo($data['name'], PATHINFO_EXTENSION);
    if (!empty($ext)) {
        $ext = '.' . $ext;
    }
    if ($entity->isNew()) {
        $data['name'] = uniqid() . $ext;
    } else {
        $filename = pathinfo($entity->getOriginal($field), PATHINFO_FILENAME);
        $data['name'] = $filename . $ext;
    }
    return $data['name'];
},
davidyell commented 6 years ago

Why can't these be set in the controller table and passed into the function?

$thingy = 'foo';

//$this->loadComponent('Upload', [
$this->addBehaviour('Upload', [
   'nameCallback' => function ($data, $settings) use ($thingy) {
josegonzalez commented 6 years ago

Its not a component.

davidyell commented 6 years ago

Wouldn't the same apply to a behaviour though?

MAFLO321 commented 6 years ago

@saeideng I have added backwards compatibility as you said. @josegonzalez Should i squash commits or let them as separate commits?

josegonzalez commented 6 years ago

Fancy.

raul338 commented 6 years ago

Can this PR be tagged in a new release? It can be used to use a virtual property as part of the filename, (currently it only is possible in the path)

josegonzalez commented 6 years ago

Yes it can, whenever someone has time to do that.