Completed
Push — staging ( d055c8...be366c )
by Matthew
02:58
created

AlertCountsEndpointController::getCountData()   C

Complexity

Conditions 12
Paths 47

Size

Total Lines 80
Code Lines 42

Duplication

Lines 28
Ratio 35 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 28
loc 80
rs 5.0693
cc 12
eloc 42
nc 47
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Ps2alerts\Api\Controller\Endpoint\Alerts;
4
5
use League\Fractal\Manager;
6
use Ps2alerts\Api\Controller\Endpoint\AbstractEndpointController;
7
use Ps2alerts\Api\Contract\ConfigAwareInterface;
8
use Ps2alerts\Api\Contract\ConfigAwareTrait;
9
use Ps2alerts\Api\Repository\AlertRepository;
10
use Ps2alerts\Api\Transformer\AlertTotalTransformer;
11
use Ps2alerts\Api\Transformer\AlertTransformer;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\HttpFoundation\Response;
14
15
class AlertCountsEndpointController extends AbstractEndpointController implements
16
    ConfigAwareInterface
17
{
18
    use ConfigAwareTrait;
19
20
    /**
21
     * Construct
22
     *
23
     * @param Ps2alerts\Api\Repository\AlertRepository   $repository
24
     * @param Ps2alerts\Api\Transformer\AlertTransformer $transformer
25
     * @param League\Fractal\Manager                     $fractal
26
     */
27
    public function __construct(
28
        AlertRepository  $repository,
29
        AlertTransformer $transformer,
30
        Manager          $fractal
31
    ) {
32
        $this->repository  = $repository;
33
        $this->transformer = $transformer;
34
        $this->fractal     = $fractal;
35
    }
36
37
    /**
38
     * Returns the victories of each faction and the totals
39
     *
40
     * @param  Symfony\Component\HttpFoundation\Request  $request
41
     * @param  Symfony\Component\HttpFoundation\Response $response
42
     *
43
     * @return array
44
     */
45
    public function getVictories(Request $request, Response $response)
46
    {
47
        return $this->getCountData($request, $response, 'victories');
48
    }
49
50
    /**
51
     * Returns the dominations of each faction and the totals
52
     *
53
     * @param  \Symfony\Component\HttpFoundation\Request  $request
54
     * @param  \Symfony\Component\HttpFoundation\Response $response
55
     *
56
     * @return array
57
     */
58
    public function getDominations(Request $request, Response $response)
59
    {
60
        return $this->getCountData($request, $response, 'dominations');
61
    }
62
63
    /**
64
     * Gets the required count data and returns
65
     *
66
     * @param  \Symfony\Component\HttpFoundation\Request  $request
67
     * @param  \Symfony\Component\HttpFoundation\Response $response
68
     * @param  string                                     $mode     The type of data we're getting (victory / domination)
69
     *
70
     * @return \Symfony\Component\HttpFoundation\Response
71
     */
72
    public function getCountData(Request $request, Response $response, $mode)
73
    {
74
        $serversQuery = $request->get('servers');
75
        $zonesQuery   = $request->get('zones');
76
        $servers      = $this->getConfigItem('servers');
77
        $zones        = $this->getConfigItem('zones');
78
79 View Code Duplication
        if (! empty($serversQuery)) {
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...
80
            $check = explode(',', $serversQuery);
81
82
            // Run a check on the IDs provided to make sure they're valid and no naughty things are being passed
83
            foreach($check as $id) {
84
                if (! in_array($id, $servers)) {
85
                    return $this->errorWrongArgs($response, 'Invalid Server Arguments passed');
86
                }
87
            }
88
89
            $servers = $serversQuery;
90
        } else {
91
            $servers = implode(',', $servers);
92
        }
93
94 View Code Duplication
        if (! empty($zonesQuery)) {
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...
95
            $check = explode(',', $zonesQuery);
96
97
            // Run a check on the IDs provided to make sure they're valid and no naughty things are being passed
98
            foreach($check as $id) {
99
                if (! in_array($id, $zones)) {
100
                    return $this->errorWrongArgs($response, 'Invalid Zone Arguments passed');
101
                }
102
            }
103
104
            $zones = $zonesQuery;
105
        } else {
106
            $zones = implode(',', $zones);
107
        }
108
109
        /* The marvelous query that is fired:
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
110
        SUM(CASE WHEN `ResultWinner`='VS' AND `ResultServer` IN (1,10,13,17,25,1000,2000) AND `ResultAlertCont` IN (2,4,6,8) THEN 1 ELSE 0 END) vs,
111
        */
112
113
        $serversExploded = explode(',', $servers);
114
115
        foreach ($serversExploded as $server) {
116
            $query = $this->repository->newQuery();
117
118
            $sql = '';
119
120
            foreach ($this->getConfigItem('factions') as $faction) {
0 ignored issues
show
Bug introduced by
The expression $this->getConfigItem('factions') of type string is not traversable.
Loading history...
121
                $factionAbv = strtoupper($faction);
122
                $sql .= "SUM(CASE WHEN `ResultWinner`='{$factionAbv}' ";
123
                $sql .= "AND `ResultServer` IN ({$server}) ";
124
                $sql .= "AND `ResultAlertCont` IN ({$zones}) ";
125
126
                if ($mode === 'dominations') {
127
                    $sql .= "AND `ResultDomination` = 1 ";
128
                }
129
130
                $sql .= "THEN 1 ELSE 0 END) {$faction}";
131
132
                if ($factionAbv !== 'DRAW') {
133
                    $sql .= ", ";
134
                }
135
            }
136
137
            $query->cols([$sql]);
138
            $data = $this->repository->readRaw($query->getStatement(), true);
139
            $data['total'] = array_sum($data);
140
141
            if ($mode === 'domination') {
142
                $data['draw'] = null; // For dominations, set it by default first
143
            }
144
145
            // Build each section of the final response using the transformer
146
            $counts['data'][$server] = $this->createItem($data, new AlertTotalTransformer);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$counts was never initialized. Although not strictly required by PHP, it is generally a good practice to add $counts = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
147
        }
148
149
        // Return the now formatted array to the response
150
        return $this->respondWithArray($response, $counts);
0 ignored issues
show
Bug introduced by
The variable $counts does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
151
    }
152
}
153