Completed
Push — 5.1 ( caeb2e...f14ddd )
by Kristof
70:09 queued 59:10
created

MediaBundle/Command/RenameSoftDeletedCommand.php (1 issue)

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
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);
38
39
            $this->setName(null === $em ? 'kuma:media:rename-soft-deleted' : $em);
40
41
            return;
42
        }
43
44
        $this->em = $em;
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) {
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 = array();
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[] = array($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 = array();
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
}
116