Passed
Push — develop ( 762085...4c0d99 )
by Daniel
05:38
created

FormCacheClear   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 65
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 5 1
A __construct() 0 6 1
A execute() 0 10 2
A updateFormTimestamp() 0 12 3
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 1
    public function __construct(
24
        EntityManagerInterface $em,
25
        ?string $name = null
26
    ) {
27 1
        $this->em = $em;
28 1
        parent::__construct($name);
29 1
    }
30
31
    /**
32
     * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
33
     */
34 1
    protected function configure(): void
35
    {
36
        $this
37 1
            ->setName('app:form:cache:clear')
38 1
            ->setDescription('Purges the varnish cache for forms where files have been updated')
39
        ;
40 1
    }
41
42
    /**
43
     * @param InputInterface $input
44
     * @param OutputInterface $output
45
     * @return int|null|void
46
     * @throws \ReflectionException
47
     */
48 1
    protected function execute(InputInterface $input, OutputInterface $output)
49
    {
50 1
        $this->output = $output;
51
52 1
        $repo = $this->em->getRepository(Form::class);
53 1
        $forms = $repo->findAll();
54 1
        foreach ($forms as $form) {
55 1
            $this->updateFormTimestamp($form);
56
        }
57 1
        $this->em->flush();
58 1
    }
59
60
    /**
61
     * @param Form $form
62
     * @throws \ReflectionException
63
     */
64 1
    private function updateFormTimestamp(Form $form)
65
    {
66 1
        $formClass = $form->getFormType();
67 1
        $reflector = new \ReflectionClass($formClass);
68 1
        $dateTime = new \DateTime();
69 1
        $timestamp = filemtime($reflector->getFileName());
70
71 1
        $this->output->writeln(sprintf('<info>Checking timestamp for %s</info>', $formClass));
72 1
        if (!$form->getLastModified() || $timestamp !== $form->getLastModified()->getTimestamp()) {
73 1
            $dateTime->setTimestamp($timestamp);
74 1
            $form->setLastModified($dateTime);
75 1
            $this->output->writeln('<comment>Updated timestamp</comment>');
76
        }
77 1
    }
78
}
79