ChartController   B
last analyzed

Complexity

Total Complexity 50

Size/Duplication

Total Lines 289
Duplicated Lines 39.1 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 7
Bugs 3 Features 0
Metric Value
c 7
b 3
f 0
dl 113
loc 289
rs 8.6206
wmc 50
lcom 1
cbo 5

13 Methods

Rating   Name   Duplication   Size   Complexity  
A getDaysOrNull() 0 19 4
A __construct() 0 11 1
B weightAction() 31 31 1
B caloriesAction() 31 31 1
B energymixAction() 31 31 1
A getDefaultFrom() 10 10 2
A getDefaultTo() 10 10 2
B getMinWeight() 0 11 5
B getMaxWeight() 0 11 5
B getMinCalorie() 0 11 5
B getMaxCalorie() 0 11 5
B getMinEnergyMix() 0 17 9
B getMaxEnergyMix() 0 17 9

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ChartController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ChartController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Dominikzogg\EnergyCalculator\Controller;
4
5
use Doctrine\Common\Persistence\ManagerRegistry;
6
use Dominikzogg\EnergyCalculator\Entity\Day;
7
use Dominikzogg\EnergyCalculator\Form\DateRangeType;
8
use Dominikzogg\EnergyCalculator\Repository\DayRepository;
9
use Saxulum\RouteController\Annotation\DI;
10
use Saxulum\RouteController\Annotation\Route;
11
use Symfony\Component\Form\FormFactory;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\HttpFoundation\Response;
14
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
15
16
/**
17
 * @Route("/{_locale}/chart", asserts={"_locale"="([a-z]{2}|[a-z]{2}_[A-Z]{2})"})
18
 * @DI(serviceIds={
19
 *      "doctrine",
20
 *      "form.factory",
21
 *      "security.token_storage",
22
 *      "twig"
23
 * })
24
 */
25
class ChartController extends AbstractController
26
{
27
    public function __construct(
28
        ManagerRegistry $doctrine,
29
        FormFactory $formFactory,
30
        TokenStorageInterface $tokenStorage,
31
        \Twig_Environment $twig
32
    ) {
33
        $this->doctrine = $doctrine;
34
        $this->formFactory = $formFactory;
35
        $this->tokenStorage = $tokenStorage;
36
        $this->twig = $twig;
37
    }
38
39
    /**
40
     * @Route("/weight", bind="chart_weight", method="GET")
41
     * @param  Request  $request
42
     * @return Response
43
     */
44 View Code Duplication
    public function weightAction(Request $request)
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...
45
    {
46
        $dateRangeType = new DateRangeType();
47
48
        $dateRangeForm = $this->createForm($dateRangeType, array(
0 ignored issues
show
Documentation introduced by
$dateRangeType is of type object<Dominikzogg\Energ...tor\Form\DateRangeType>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
49
            'from' => $this->getDefaultFrom('-1 week'),
50
            'to' => $this->getDefaultTo(),
51
        ));
52
53
        $dateRangeForm->handleRequest($request);
54
        $dateRangeFormData = $dateRangeForm->getData();
55
56
        $from = $dateRangeFormData['from'];
57
        $to = $dateRangeFormData['to'];
58
59
        /** @var DayRepository $repo */
60
        $repo = $this->getRepositoryForClass(Day::class);
61
62
        $days = $repo->getInRange($from, $to, $this->getUser());
63
        $allDays = $this->getDaysOrNull($days, $from, $to);
64
65
        $minWeight = $this->getMinWeight($days);
66
        $maxWeight = $this->getMaxWeight($days);
67
68
        return $this->render('@DominikzoggEnergyCalculator/Chart/weight.html.twig', array(
69
            'daterangeform' => $dateRangeForm->createView(),
70
            'alldays' => $allDays,
71
            'minweight' => $minWeight,
72
            'maxweight' => $maxWeight,
73
        ));
74
    }
75
76
    /**
77
     * @Route("/calorie", bind="chart_calorie", method="GET")
78
     * @param  Request  $request
79
     * @return Response
80
     */
81 View Code Duplication
    public function caloriesAction(Request $request)
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...
82
    {
83
        $dateRangeType = new DateRangeType();
84
85
        $dateRangeForm = $this->createForm($dateRangeType, array(
0 ignored issues
show
Documentation introduced by
$dateRangeType is of type object<Dominikzogg\Energ...tor\Form\DateRangeType>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
86
            'from' => $this->getDefaultFrom('-1 week'),
87
            'to' => $this->getDefaultTo(),
88
        ));
89
90
        $dateRangeForm->handleRequest($request);
91
        $dateRangeFormData = $dateRangeForm->getData();
92
93
        $from = $dateRangeFormData['from'];
94
        $to = $dateRangeFormData['to'];
95
96
        /** @var DayRepository $repo */
97
        $repo = $this->getRepositoryForClass(Day::class);
98
99
        $days = $repo->getInRange($from, $to, $this->getUser());
100
        $allDays = $this->getDaysOrNull($days, $from, $to);
101
102
        $minCalorie = $this->getMinCalorie($days);
103
        $maxCalorie = $this->getMaxCalorie($days);
104
105
        return $this->render('@DominikzoggEnergyCalculator/Chart/calorie.html.twig', array(
106
            'daterangeform' => $dateRangeForm->createView(),
107
            'alldays' => $allDays,
108
            'mincalorie' => $minCalorie,
109
            'maxcalorie' => $maxCalorie,
110
        ));
111
    }
112
113
    /**
114
     * @Route("/energymix", bind="chart_energymix", method="GET")
115
     * @param  Request  $request
116
     * @return Response
117
     */
118 View Code Duplication
    public function energymixAction(Request $request)
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...
119
    {
120
        $dateRangeType = new DateRangeType();
121
122
        $dateRangeForm = $this->createForm($dateRangeType, array(
0 ignored issues
show
Documentation introduced by
$dateRangeType is of type object<Dominikzogg\Energ...tor\Form\DateRangeType>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
123
            'from' => $this->getDefaultFrom('-1 week'),
124
            'to' => $this->getDefaultTo(),
125
        ));
126
127
        $dateRangeForm->handleRequest($request);
128
        $dateRangeFormData = $dateRangeForm->getData();
129
130
        $from = $dateRangeFormData['from'];
131
        $to = $dateRangeFormData['to'];
132
133
        /** @var DayRepository $repo */
134
        $repo = $this->getRepositoryForClass(Day::class);
135
136
        $days = $repo->getInRange($from, $to, $this->getUser());
137
        $allDays = $this->getDaysOrNull($days, $from, $to);
138
139
        $minEnergyMix = $this->getMinEnergyMix($days);
140
        $maxEnergyMix = $this->getMaxEnergyMix($days);
141
142
        return $this->render('@DominikzoggEnergyCalculator/Chart/energymix.html.twig', array(
143
            'daterangeform' => $dateRangeForm->createView(),
144
            'alldays' => $allDays,
145
            'minenergymix' => $minEnergyMix,
146
            'maxenergymix' => $maxEnergyMix,
147
        ));
148
    }
149
150
    /**
151
     * @param  string|null $modifier
152
     * @return \DateTime
153
     */
154 View Code Duplication
    protected function getDefaultFrom($modifier = null)
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...
155
    {
156
        $from = new \DateTime();
157
        if (null !== $modifier) {
158
            $from->modify($modifier);
159
        }
160
        $from->setTime(0, 0, 0);
161
162
        return $from;
163
    }
164
165
    /**
166
     * @param  string|null $modifier
167
     * @return \DateTime
168
     */
169 View Code Duplication
    protected function getDefaultTo($modifier = null)
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...
170
    {
171
        $to = new \DateTime();
172
        if (null !== $modifier) {
173
            $to->modify($modifier);
174
        }
175
        $to->setTime(23, 59, 59);
176
177
        return $to;
178
    }
179
180
    /**
181
     * @param  Day[]     $days
182
     * @param  \DateTime $from
183
     * @param  \DateTime $to
184
     * @return Day[]
185
     */
186
    protected function getDaysOrNull(array $days, \DateTime $from, \DateTime $to)
187
    {
188
        $from = clone $from;
189
190
        $daysPerDate = array();
191
        foreach ($days as $day) {
192
            $daysPerDate[$day->getDate()->format('d.m.Y')] = $day;
193
        }
194
195
        $return = array();
196
197
        while ($from->format('Ymd') <= $to->format('Ymd')) {
198
            $fromAsString = $from->format('d.m.Y');
199
            $return[$fromAsString] = isset($daysPerDate[$fromAsString]) ? $daysPerDate[$fromAsString] : null;
200
            $from->modify('+1day');
201
        }
202
203
        return $return;
204
    }
205
206
    /**
207
     * @param  Day[] $days
208
     * @return float
209
     */
210
    protected function getMinWeight(array $days)
211
    {
212
        $minWeight = null;
213
        foreach ($days as $day) {
214
            if (null === $minWeight || $day->getWeight() < $minWeight) {
215
                $minWeight = $day->getWeight();
216
            }
217
        }
218
219
        return null !== $minWeight ? $minWeight : 0;
220
    }
221
222
    /**
223
     * @param  Day[] $days
224
     * @return float
225
     */
226
    protected function getMaxWeight(array $days)
227
    {
228
        $maxWeight = null;
229
        foreach ($days as $day) {
230
            if (null === $maxWeight || $day->getWeight() > $maxWeight) {
231
                $maxWeight = $day->getWeight();
232
            }
233
        }
234
235
        return null !== $maxWeight ? $maxWeight : 500;
236
    }
237
238
    /**
239
     * @param  Day[] $days
240
     * @return float
241
     */
242
    protected function getMinCalorie(array $days)
243
    {
244
        $minCalorie = null;
245
        foreach ($days as $day) {
246
            if (null === $minCalorie || $day->getCalorie() < $minCalorie) {
247
                $minCalorie = $day->getCalorie();
248
            }
249
        }
250
251
        return null !== $minCalorie ? $minCalorie : 0;
252
    }
253
254
    /**
255
     * @param  Day[] $days
256
     * @return float
257
     */
258
    protected function getMaxCalorie(array $days)
259
    {
260
        $maxCalorie = null;
261
        foreach ($days as $day) {
262
            if (null === $maxCalorie || $day->getCalorie() > $maxCalorie) {
263
                $maxCalorie = $day->getCalorie();
264
            }
265
        }
266
267
        return null !== $maxCalorie ? $maxCalorie : 10000;
268
    }
269
270
    /**
271
     * @param  Day[] $days
272
     * @return float
273
     */
274
    protected function getMinEnergyMix(array $days)
275
    {
276
        $minEnergyMix = null;
277
        foreach ($days as $day) {
278
            if (null === $minEnergyMix || $day->getProtein() < $minEnergyMix) {
279
                $minEnergyMix = $day->getProtein();
280
            }
281
            if (null === $minEnergyMix || $day->getCarbohydrate() < $minEnergyMix) {
282
                $minEnergyMix = $day->getCarbohydrate();
283
            }
284
            if (null === $minEnergyMix || $day->getFat() < $minEnergyMix) {
285
                $minEnergyMix = $day->getFat();
286
            }
287
        }
288
289
        return null !== $minEnergyMix ? $minEnergyMix : 0;
290
    }
291
292
    /**
293
     * @param  Day[] $days
294
     * @return float
295
     */
296
    protected function getMaxEnergyMix(array $days)
297
    {
298
        $maxEnergyMix = null;
299
        foreach ($days as $day) {
300
            if (null === $maxEnergyMix || $day->getProtein() > $maxEnergyMix) {
301
                $maxEnergyMix = $day->getProtein();
302
            }
303
            if (null === $maxEnergyMix || $day->getCarbohydrate() > $maxEnergyMix) {
304
                $maxEnergyMix = $day->getCarbohydrate();
305
            }
306
            if (null === $maxEnergyMix || $day->getFat() > $maxEnergyMix) {
307
                $maxEnergyMix = $day->getFat();
308
            }
309
        }
310
311
        return null !== $maxEnergyMix ? $maxEnergyMix : 1000;
312
    }
313
}
314