Test Failed
Branch develop (ac2838)
by Daniel
09:09
created

FormCacheClear::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Command;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Silverback\ApiComponentBundle\Entity\Component\Form\Form;
7
use Symfony\Component\Console\Command\Command;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Output\OutputInterface;
10
11
class FormCacheClear extends Command
12
{
13
    /**
14
     * @var EntityManagerInterface
15
     */
16
    private $em;
17
18
    /**
19
     * @var OutputInterface
20
     */
21
    private $output;
22
23
    public function __construct(
24
        EntityManagerInterface $em,
25
        ?string $name = null
26
    ) {
27
        $this->em = $em;
28
        parent::__construct($name);
29
    }
30
31
    /**
32
     * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
33
     */
34
    protected function configure(): void
35
    {
36
        $this
37
            ->setName('app:form:cache:clear')
38
            ->setDescription('Purges the varnish cache for forms where files have been updated')
39
        ;
40
    }
41
42
    /**
43
     * @param InputInterface $input
44
     * @param OutputInterface $output
45
     * @return int|null|void
46
     * @throws \ReflectionException
47
     */
48
    protected function execute(InputInterface $input, OutputInterface $output)
49
    {
50
        $this->output = $output;
51
52
        $repo = $this->em->getRepository(Form::class);
53
        $forms = $repo->findAll();
54
        foreach ($forms as $form) {
55
            $this->updateFormTimestamp($form);
56
        }
57
        $this->em->flush();
58
    }
59
60
    /**
61
     * @param Form $form
62
     * @throws \ReflectionException
63
     */
64
    private function updateFormTimestamp(Form $form)
65
    {
66
        $formClass = $form->getFormType();
67
        $reflector = new \ReflectionClass($formClass);
68
        $dateTime = new \DateTime();
69
        $timestamp = filemtime($reflector->getFileName());
70
71
        $this->output->writeln(sprintf('<info>Checking timestamp for %s</info>', $formClass));
72
        if (!$form->getLastModified() || $timestamp !== $form->getLastModified()->getTimestamp()) {
73
            $dateTime->setTimestamp($timestamp);
74
            $form->setLastModified($dateTime);
75
            $this->output->writeln('<comment>Updated timestamp</comment>');
76
        } else {
77
            $this->output->writeln('<info>No changes</info>');
78
        }
79
    }
80
}
81