Completed
Push — master ( 1de9b7...830752 )
by Kristof
38:46 queued 24:09
created

GoogleAnalyticsOverviewsGenerateCommand   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 165
Duplicated Lines 32.12 %

Coupling/Cohesion

Components 2
Dependencies 7

Importance

Changes 0
Metric Value
wmc 20
lcom 2
cbo 7
dl 53
loc 165
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 3
A configure() 20 20 1
B execute() 0 32 6
A generateOverviewsOfSegment() 13 13 2
A generateOverviewsOfConfig() 0 23 4
A generateAllOverviews() 20 20 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Kunstmaan\DashboardBundle\Command;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Kunstmaan\DashboardBundle\Repository\AnalyticsSegmentRepository;
7
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\InputOption;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
/**
13
 * @final since 5.1
14
 * NEXT_MAJOR extend from `Command` and remove `$this->getContainer` usages
15
 */
16
class GoogleAnalyticsOverviewsGenerateCommand 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...
17
{
18
    /** @var EntityManagerInterface $em */
19
    private $em;
20
21
    /**
22
     * @param EntityManagerInterface|null $em
23
     */
24
    public function __construct(/* EntityManagerInterface */ $em = null)
25
    {
26
        parent::__construct();
27
28
        if (!$em instanceof EntityManagerInterface) {
29
            @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...
30
31
            $this->setName(null === $em ? 'kuma:dashboard:widget:googleanalytics:overviews:generate' : $em);
32
33
            return;
34
        }
35
36
        $this->em = $em;
37
    }
38
39 View Code Duplication
    protected function configure()
0 ignored issues
show
Duplication introduced by
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...
40
    {
41
        $this
42
            ->setName('kuma:dashboard:widget:googleanalytics:overviews:generate')
43
            ->setDescription('Generate overviews')
44
            ->addOption(
45
                'config',
46
                null,
47
                InputOption::VALUE_OPTIONAL,
48
                'Specify to only update one config',
49
                false
50
            )
51
            ->addOption(
52
                'segment',
53
                null,
54
                InputOption::VALUE_OPTIONAL,
55
                'Specify to only update one segment',
56
                false
57
            );
58
    }
59
60
    /**
61
     * @param InputInterface  $input
62
     * @param OutputInterface $output
63
     *
64
     * @return int|null|void
65
     */
66
    protected function execute(InputInterface $input, OutputInterface $output)
67
    {
68
        if (null === $this->em) {
69
            $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
70
        }
71
72
        // get params
73
        $configId = false;
74
        $segmentId = false;
75
76
        try {
77
            $configId = $input->getOption('config');
78
            $segmentId = $input->getOption('segment');
79
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
80
        }
81
82
        try {
83
            if ($segmentId) {
84
                $this->generateOverviewsOfSegment($segmentId);
85
            } else {
86
                if ($configId) {
87
                    $this->generateOverviewsOfConfig($configId);
88
                } else {
89
                    $this->generateAllOverviews();
90
                }
91
            }
92
93
            $output->writeln('<fg=green>Overviews succesfully generated</fg=green>');
94
        } catch (\InvalidArgumentException $e) {
95
            $output->writeln('<fg=red>' . $e->getMessage() . '</fg=red>');
96
        }
97
    }
98
99
    /**
100
     * Get all overviews of a segment
101
     *
102
     * @param int $segmentId
103
     *
104
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
105
     *
106
     * @throws \InvalidArgumentException
107
     */
108 View Code Duplication
    private function generateOverviewsOfSegment($segmentId)
0 ignored issues
show
Duplication introduced by
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...
109
    {
110
        /** @var AnalyticsSegmentRepository $segmentRepository */
111
        $segmentRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsSegment');
112
        $segment = $segmentRepository->find($segmentId);
113
114
        if (!$segment) {
115
            throw new \InvalidArgumentException('Unknown segment ID');
116
        }
117
118
        // init the segment
119
        $segmentRepository->initSegment($segment);
120
    }
121
122
    /**
123
     * Get all overviews of a config
124
     *
125
     * @param int $configId
126
     *
127
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
128
     *
129
     * @throws \InvalidArgumentException
130
     */
131
    private function generateOverviewsOfConfig($configId)
132
    {
133
        $configRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig');
134
        $segmentRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsSegment');
135
        $overviewRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsOverview');
136
        // get specified config
137
        $config = $configRepository->find($configId);
138
139
        if (!$config) {
140
            throw new \InvalidArgumentException('Unknown config ID');
141
        }
142
143
        // create default overviews for this config if none exist yet
144
        if (!count($config->getOverviews())) {
145
            $overviewRepository->addOverviews($config);
146
        }
147
148
        // init all the segments for this config
149
        $segments = $config->getSegments();
150
        foreach ($segments as $segment) {
151
            $segmentRepository->initSegment($segment);
152
        }
153
    }
154
155
    /**
156
     * get all overviews
157
     *
158
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
159
     */
160 View Code Duplication
    private function generateAllOverviews()
0 ignored issues
show
Duplication introduced by
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...
161
    {
162
        $configRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig');
163
        $overviewRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsOverview');
164
        $segmentRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsSegment');
165
        $configs = $configRepository->findAll();
166
167
        foreach ($configs as $config) {
168
            // add overviews if none exist yet
169
            if (!count($configRepository->findDefaultOverviews($config))) {
170
                $overviewRepository->addOverviews($config);
171
            }
172
173
            // init all the segments for this config
174
            $segments = $config->getSegments();
175
            foreach ($segments as $segment) {
176
                $segmentRepository->initSegment($segment);
177
            }
178
        }
179
    }
180
}
181