Completed
Push — 6.0 ( eb641c...92cb73 )
by Ruud
148:12 queued 131:31
created

RenameSoftDeletedCommand::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 2
nop 2
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
    public function __construct(/* EntityManagerInterface */ $em = null, /* MediaManager */ $mediaManager = null)
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
Duplication introduced by
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 = array();
79
        try {
80
            $this->em->beginTransaction();
81
            /** @var Media $media */
82
            foreach ($medias as $media) {
83
                $handler = $this->mediaManager->getHandler($media);
84
                if ($media->isDeleted() && $media->getLocation() === 'local' && $handler instanceof FileHandler) {
85
                    $oldFileUrl = $media->getUrl();
86
                    $newFileName = ($original ? $media->getOriginalFilename() : uniqid() . '.' . pathinfo($oldFileUrl, PATHINFO_EXTENSION));
87
                    $newFileUrl = dirname($oldFileUrl) . '/' . $newFileName;
88
                    $fileRenameQueue[] = array($oldFileUrl, $newFileUrl, $handler);
89
                    $media->setUrl($newFileUrl);
90
                    $this->em->persist($media);
91
                    $updates++;
92
                }
93
            }
94
            $this->em->flush();
95
            $this->em->commit();
96
        } catch (\Exception $e) {
97
            $this->em->rollback();
98
            $output->writeln('An error occured while updating soft-deleted media : <error>' . $e->getMessage() . '</error>');
99
            $updates = 0;
100
            $fileRenameQueue = array();
101
        }
102
103
        foreach ($fileRenameQueue as $row) {
104
            list ($oldFileUrl, $newFileUrl, $handler) = $row;
105
            $handler->fileSystem->rename(
106
                preg_replace('~^' . preg_quote($handler->mediaPath, '~') . '~', '/', $oldFileUrl),
107
                preg_replace('~^' . preg_quote($handler->mediaPath, '~') . '~', '/', $newFileUrl)
108
            );
109
            $output->writeln('Renamed <info>' . $oldFileUrl . '</info> to <info>' . basename($newFileUrl) . '</info>');
110
        }
111
112
        $output->writeln('<info>' . $updates . ' soft-deleted media files have been renamed.</info>');
113
    }
114
}
115