agence-adeliom / easy-media-bundle

A Symfony Media manager bundle for EasyAdmin
MIT License
27 stars 17 forks source link

Manager - createFolder > setParent should be called before getPath is used #26

Open j0r1s opened 1 year ago

j0r1s commented 1 year ago

I think I found a quite impactful logic error in method createFolder from EasyMediaManager.

Folder::getPath is used before setParent has been called, therefore, if the folder should be nested, the path returned (and then created by the filesystem) is wrong (relative to root instead of parent folder).

Here is the code of the function, I've added comments to explain my point :

public function createFolder(?string $name, ?string $path = null): ?Folder
    {
        if ('.' === $path) {
            $path = '';
        }

        $class = $this->getHelper()->getFolderClassName();
        /** @var Folder $entity */
        $entity = new $class();

        if ($name) {
            $entity->setName($name);
        }

        $folder = $this->folderByPath($path);
        if (false === $folder && !empty($path)) {
            $folder = $this->createFolder(basename($path), dirname($path));
        }

        if (!empty($this->getHelper()->getFolderRepository()->findBy(['parent' => $folder, 'name' => $name]))) {
            throw new FolderAlreadyExist($this->translator->trans('error.already_exists', [], 'EasyMediaBundle'));
        }

        // in the next two lines, getPath only returns slug of $entity since it has no parent yet
        if (!$this->filesystem->directoryExists($entity->getPath())) {
            $this->filesystem->createDirectory($entity->getPath(), []);
        }

        $entity->setParent($folder ?: null); // This should be called before
        $this->save($entity);

        return $entity;
    }

This error leads to multiple issue with "File/folder already exists", I would be happy to open a PR if needed.

Probably related to #25

SebastienLcmt commented 1 year ago

Thanks @j0r1s 🥇