Service   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 221
Duplicated Lines 40.72 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 60.19%

Importance

Changes 13
Bugs 1 Features 4
Metric Value
wmc 20
c 13
b 1
f 4
lcom 1
cbo 11
dl 90
loc 221
ccs 65
cts 108
cp 0.6019
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 1
A getDoctrine() 0 4 1
A get() 0 11 2
D set() 31 105 13
A getDayHistory() 20 20 1
A getExtremes() 21 21 1
A getLastValue() 18 18 1

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 AppBundle\Variable;
4
5
use AppBundle\Entity\Trigger;
6
use AppBundle\Entity\Variable;
7
use AppBundle\Entity\VariableHistory;
8
use AppBundle\Variable\Parser\ParserInterface;
9
use Doctrine\Bundle\DoctrineBundle\Registry;
10
use Doctrine\ORM\EntityManager;
11
use Monolog\Logger;
12
use Symfony\Component\Config\Definition\Exception\Exception;
13
14
class Service
15
{
16
17
    private $doctrine;
18
    private $needSync = false;
19
    private $syncHost;
20
    private $actionService;
21
    private $logger;
22
23 5
    public function __construct(
24
        Registry $doctrine,
25
        \AppBundle\Action\Service $actionService,
26
        $needSync,
27
        $syncHost,
28
        Logger $logger
29
    ) {
30
    
31 5
        $this->doctrine = $doctrine;
32 5
        $this->needSync = $needSync;
33 5
        $this->syncHost = $syncHost;
34 5
        $this->actionService = $actionService;
35 5
        $this->logger = $logger;
36 5
    }
37
38 5
    private function getDoctrine()
39
    {
40 5
        return $this->doctrine;
41
    }
42
43 5
    public function get($varName)
44
    {
45 5
        $vars = $this->getDoctrine()->getRepository('AppBundle:Variable');
46
47
        /** @var Variable $var */
48 5
        $var = $vars->findOneBy(['name'=>$varName]);
49 5
        if (!$var) {
50 1
            throw new Exception('Variable '.$varName.' not found');
51
        }
52 4
        return $var;
53
    }
54
55 3
    public function set($varName, $value)
56
    {
57 3
        $vars = $this->getDoctrine()->getRepository('AppBundle:Variable');
58
59
        /** @var Variable $var */
60 3
        $var = $vars->findOneBy(['name'=>$varName]);
61 3
        if (!$var) {
62
            throw new Exception('Variable '.$varName.' not found');
63
        }
64
65 3
        $parser = 'AppBundle\Variable\Parser\\'.ucfirst($var->getParser());
66
67 3
        if (!class_exists($parser)) {
68
            throw new Exception('Unknown parser: '.$parser);
69
        }
70
71
        /** @var ParserInterface $parser */
72 3
        $parser = new $parser();
73
74 3
        $value = $parser->parse($value);
75
76 3
        if (!$value) {
77 2
            return false;
78
        }
79
80 3
        if ($this->needSync) {
81
            if ($var->needSync) {
82
                @file_get_contents($this->syncHost.'set/'.$varName.'?value='.$value);
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...
83
            }
84
        }
85
86 3
        $this->logger->addInfo('Set '.$var->getName().' to '.$value);
87
88 3
        $var->setValue($value);
89 3
        $var->setLaststatus(200);
90 3
        $var->setLastupdate(new \DateTime());
91
92 3
        $this->getDoctrine()->getManagerForClass('AppBundle:Variable')->persist($var);
93
94 3
        if ($var->needHistory) {
95 3
            $state = new VariableHistory();
96 3
            $state->setVar($var);
97 3
            $state->setTime(new \DateTime());
98 3
            $state->setValue($value);
99
100 3
            $this->getDoctrine()->getManagerForClass('AppBundle:VariableHistory')->persist($state);
101 3
            $this->getDoctrine()->getManagerForClass('AppBundle:VariableHistory')->flush();
102
        }
103
104 3
        $this->getDoctrine()->getManagerForClass('AppBundle:Variable')->flush();
105
106
        // Check triggers
107
108
        $triggers = $this->
109 3
                        getDoctrine()->
110 3
                        getManager()->
111 3
                        getRepository('AppBundle:Trigger')->
112 3
                        findBy(
113
                            [
114 3
                                'variable'=>$var,
115
                                'isEnabled'=>true
116
                            ]
117
                        );
118
119
        /** @var Trigger $trigger */
120 3
        foreach ($triggers as $trigger) {
121 1
            if ($trigger->getState() == false) {
122 1 View Code Duplication
                if ($trigger->checkState()) {
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...
123 1
                    $trigger->setState(true);
124
125
126 1
                    if ($trigger->onActivate) {
127 1
                        $tParams = json_decode($trigger->activateParams, true);
128 1
                        $tParams['variable'] = $var->getValue();
129 1
                        $this->actionService->executeReal(
130 1
                            $trigger->onActivate,
131 1
                            'trigger:activate',
132
                            $tParams
133
                        );
134
                    }
135
                }
136 View Code Duplication
            } else {
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...
137 1
                if (!$trigger->checkState()) {
138 1
                    $trigger->setState(false);
139
140
                    // Deactivation hooks
141 1
                    if ($trigger->onDeactivate) {
142 1
                        $tParams = json_decode($trigger->deactivateParams, true);
143 1
                        $tParams['variable'] = $var->getValue();
144
145 1
                        $this->actionService->executeReal(
146 1
                            $trigger->onDeactivate,
147 1
                            'trigger:deactivate',
148
                            $tParams
149
                        );
150
                    }
151
                }
152
            }
153
154 1
            $this->getDoctrine()->getManagerForClass('AppBundle:Trigger')->persist($trigger);
155 1
            $this->getDoctrine()->getManager()->flush();
156
        }
157
158 3
        return $value;
159
    }
160
161
    /**
162
     * @param Variable $variable
163
     * @return array
164
     */
165 View Code Duplication
    public function getDayHistory(Variable $variable)
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...
166
    {
167
        /** @var EntityManager $em */
168
        $em = $this->getDoctrine()->getManager();
169
170
        $q = $em->createQueryBuilder();
171
        $res = $q->
172
            select('AVG(vh.value) as av')->
173
            addSelect('DATE_FORMAT(vh.time,\'%Y-%m-%d %H:00\') as df')->
174
            from('AppBundle:VariableHistory', 'vh')->
175
            where('vh.time >= :date')->
176
            setParameter('date', new \DateTime('-48 hour'))->
177
            andWhere('vh.var = :var_id')->
178
            setParameter('var_id', $variable->getId())->
179
            groupBy('df')->
180
            orderBy('df', 'asc')->
181
            getQuery();
182
183
        return $res->getArrayResult();
184
    }
185
186
    /**
187
     * @param Variable $variable
188
     * @return array
189
     */
190 View Code Duplication
    public function getExtremes(Variable $variable)
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...
191
    {
192
        /**
193
 * @var EntityManager $em
194
*/
195
        $em = $this->getDoctrine()->getManager();
196
197
        $q = $em->createQueryBuilder();
198
        $res = $q->
199
        select('AVG(vh.value) as average')
200
            ->addSelect('MIN(vh.value) as minimum')
201
            ->addSelect('MAX(vh.value) as maximum')
202
            ->from('AppBundle:VariableHistory', 'vh')
203
            ->where('vh.time >= :date')
204
            ->setParameter('date', new \DateTime('-24 hour'))
205
            ->andWhere('vh.var = :var_id')
206
            ->setParameter('var_id', $variable->getId())
207
            ->getQuery();
208
209
        return $res->getArrayResult()[0];
210
    }
211
212
    /**
213
     * @param Variable $variable
214
     * @return array
215
     */
216 View Code Duplication
    public function getLastValue(Variable $variable)
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...
217
    {
218
        /** @var EntityManager $em */
219
        $em = $this->getDoctrine()->getManager();
220
221
        $q = $em->createQueryBuilder();
222
        $res = $q->
223
        select('vh.value as av')->
224
        addSelect('vh.time as df')->
225
        from('AppBundle:VariableHistory', 'vh')->
226
        where('vh.var = :var_id')->
227
        setParameter('var_id', $variable->getId())->
228
        orderBy('df', 'desc')->
229
        setMaxResults(1)->
230
        getQuery();
231
232
        return $res->getSingleResult();
233
    }
234
}
235