Completed
Pull Request — 5.6 (#2830)
by Jeroen
14:14
created

MediaBundle/Command/RenameSoftDeletedCommand.php (5 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\MediaBundle\Command;
4
5
use Doctrine\ORM\EntityManager;
6
use Doctrine\ORM\EntityManagerInterface;
7
use Kunstmaan\MediaBundle\Entity\Media;
8
use Kunstmaan\MediaBundle\Helper\File\FileHandler;
9
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Output\OutputInterface;
13
14
/**
15
 * @final since 5.1
16
 * NEXT_MAJOR extend from `Command` and remove `$this->getContainer` usages
17
 */
18
class RenameSoftDeletedCommand extends ContainerAwareCommand
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...d\ContainerAwareCommand has been deprecated with message: since Symfony 4.2, use {@see Command} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
19
{
20
    /** @var EntityManager */
21
    protected $em;
22
23
    /**
24
     * @var MediaManager
25
     */
26
    private $mediaManager;
27
28
    /**
29
     * @param EntityManagerInterface|null $em
30
     * @param MediaManager|null           $mediaManager
31
     */
32 View Code Duplication
    public function __construct(/* EntityManagerInterface */ $em = null, /* MediaManager */ $mediaManager = null)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
33
    {
34
        parent::__construct();
35
36
        if (!$em instanceof EntityManagerInterface) {
37
            @trigger_error(sprintf('Passing a command name as the first argument of "%s" is deprecated since version symfony 3.4 and will be removed in symfony 4.0. If the command was registered by convention, make it a service instead. ', __METHOD__), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
38
39
            $this->setName(null === $em ? 'kuma:media:rename-soft-deleted' : $em);
40
41
            return;
42
        }
43
44
        $this->em = $em;
0 ignored issues
show
Documentation Bug introduced by
$em is of type object<Doctrine\ORM\EntityManagerInterface>, but the property $em was declared to be of type object<Doctrine\ORM\EntityManager>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
45
        $this->mediaManager = $mediaManager;
46
    }
47
48
    protected function configure()
49
    {
50
        parent::configure();
51
52
        $this
53
            ->setName('kuma:media:rename-soft-deleted')
54
            ->setDescription('Rename physical files for soft-deleted media.')
55
            ->setHelp(
56
                'The <info>kuma:media:rename-soft-deleted</info> command can be used to rename soft-deleted media which is still publically available under the original filename.'
57
            )
58
            ->addOption(
59
                'original',
60
                'o',
61
                InputOption::VALUE_NONE,
62
                'If set renames soft-deleted media to its original filename'
63
            );
64
    }
65
66
    public function execute(InputInterface $input, OutputInterface $output)
67
    {
68 View Code Duplication
        if (null === $this->em) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
69
            $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
70
            $this->mediaManager = $this->getContainer()->get('kunstmaan_media.media_manager');
71
        }
72
73
        $output->writeln('Renaming soft-deleted media...');
74
75
        $original = $input->getOption('original');
76
        $medias = $this->em->getRepository('KunstmaanMediaBundle:Media')->findAll();
77
        $updates = 0;
78
        $fileRenameQueue = [];
79
80
        try {
81
            $this->em->beginTransaction();
82
            /** @var Media $media */
83
            foreach ($medias as $media) {
84
                $handler = $this->mediaManager->getHandler($media);
85
                if ($media->isDeleted() && $media->getLocation() === 'local' && $handler instanceof FileHandler) {
86
                    $oldFileUrl = $media->getUrl();
87
                    $newFileName = ($original ? $media->getOriginalFilename() : uniqid() . '.' . pathinfo($oldFileUrl, PATHINFO_EXTENSION));
88
                    $newFileUrl = \dirname($oldFileUrl) . '/' . $newFileName;
89
                    $fileRenameQueue[] = [$oldFileUrl, $newFileUrl, $handler];
90
                    $media->setUrl($newFileUrl);
91
                    $this->em->persist($media);
92
                    ++$updates;
93
                }
94
            }
95
            $this->em->flush();
96
            $this->em->commit();
97
        } catch (\Exception $e) {
98
            $this->em->rollback();
99
            $output->writeln('An error occured while updating soft-deleted media : <error>' . $e->getMessage() . '</error>');
100
            $updates = 0;
101
            $fileRenameQueue = [];
102
        }
103
104
        foreach ($fileRenameQueue as $row) {
105
            list($oldFileUrl, $newFileUrl, $handler) = $row;
106
            $handler->fileSystem->rename(
107
                preg_replace('~^' . preg_quote($handler->mediaPath, '~') . '~', '/', $oldFileUrl),
108
                preg_replace('~^' . preg_quote($handler->mediaPath, '~') . '~', '/', $newFileUrl)
109
            );
110
            $output->writeln('Renamed <info>' . $oldFileUrl . '</info> to <info>' . basename($newFileUrl) . '</info>');
111
        }
112
113
        $output->writeln('<info>' . $updates . ' soft-deleted media files have been renamed.</info>');
114
115
        return 0;
116
    }
117
}
118