Completed
Push — master ( 7482e2...2b64bc )
by Kirill
05:00
created

Service   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 195
Duplicated Lines 15.9 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 68.42%

Importance

Changes 12
Bugs 1 Features 4
Metric Value
wmc 19
c 12
b 1
f 4
lcom 1
cbo 11
dl 31
loc 195
ccs 65
cts 95
cp 0.6842
rs 10

6 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() 0 20 1
A getLastValue() 0 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
    public function getDayHistory(Variable $variable)
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
    public function getLastValue(Variable $variable)
191
    {
192
        /** @var EntityManager $em */
193
        $em = $this->getDoctrine()->getManager();
194
195
        $q = $em->createQueryBuilder();
196
        $res = $q->
197
        select('vh.value as av')->
198
        addSelect('vh.time as df')->
199
        from('AppBundle:VariableHistory', 'vh')->
200
        where('vh.var = :var_id')->
201
        setParameter('var_id', $variable->getId())->
202
        orderBy('df', 'desc')->
203
        setMaxResults(1)->
204
        getQuery();
205
206
        return $res->getSingleResult();
207
    }
208
}
209