Completed
Pull Request — master (#22)
by Matthew
06:23 queued 04:03
created

AbstractEndpointController::getFiltersFromQueryString()   D

Complexity

Conditions 10
Paths 19

Size

Total Lines 45
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 22
nc 19
nop 2
dl 0
loc 45
rs 4.8196
c 0
b 0
f 0

How to fix   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;
4
5
use Aura\SqlQuery\AbstractQuery;
6
use League\Container\ContainerAwareInterface;
7
use League\Container\ContainerAwareTrait;
8
use Ps2alerts\Api\Contract\ConfigAwareInterface;
9
use Ps2alerts\Api\Contract\ConfigAwareTrait;
10
use Ps2alerts\Api\Contract\DatabaseAwareInterface;
11
use Ps2alerts\Api\Contract\DatabaseAwareTrait;
12
use Ps2alerts\Api\Contract\UtilityAwareInterface;
13
use Ps2alerts\Api\Contract\UtilityAwareTrait;
14
use Ps2alerts\Api\Exception\InvalidArgumentException;
15
use Ps2alerts\Api\Utility\ResponseHandler;
16
use League\Fractal\TransformerAbstract;
17
18
abstract class AbstractEndpointController extends ResponseHandler implements
19
    ConfigAwareInterface,
20
    ContainerAwareInterface,
21
    DatabaseAwareInterface,
22
    UtilityAwareInterface
23
{
24
    use ConfigAwareTrait;
25
    use ContainerAwareTrait;
26
    use DatabaseAwareTrait;
27
    use UtilityAwareTrait;
28
29
    /**
30
     * Contains the repository used for interfacing with the database
31
     *
32
     * @var \Ps2alerts\Api\Repository\AbstractEndpointRepository
33
     */
34
    protected $repository;
35
36
    /**
37
     * Holds the transformer we're going to use
38
     *
39
     * @var TransformerAbstract
40
     */
41
    protected $transformer;
42
43
    /**
44
     * Gets the Server or Zone filters and runs a check to make sure the request validates. Also formats the list
45
     * correctly for inclusion in query strings.
46
     *
47
     * @param  string $queryString
48
     * @param  string $type
49
     *
50
     * @throws InvalidArgumentException
51
     *
52
     * @return string
53
     */
54
    public function validateQueryStringArguments($queryString, string $type)
55
    {
56
        $filters = $this->getConfigItem($type);
57
        $numericals = ['servers', 'zones'];
58
        $strings = ['factions', 'brackets', 'dates'];
59
60
        if (!empty($queryString)) {
61
            $values = explode(',', $queryString);
62
63
            // Run a check on the IDs provided to make sure they're valid and no naughty things are being passed
64
            foreach ($values as $val) {
65
                // If the query string should contain only numbers
66
                if (in_array($type, $numericals)) {
67
                    if (!is_numeric($val)) {
68
                        throw new InvalidArgumentException("Non numerical ID detected. Only numerical IDs are accepted with this request.");
69
                    }
70
                }
71
                if (in_array($type, $strings)) {
72
                    if (is_numeric($val)) {
73
                        throw new InvalidArgumentException("Numerical input detected. Only string inputs are accepted with this request.");
74
                    }
75
                }
76
77
                if ($type !== 'dates' && !in_array($val, $filters)) {
78
                    throw new InvalidArgumentException("Unrecognized {$type}. Please check the DATA you sent.");
79
                }
80
81
                if ($type === 'dates') {
82
                    if (!$this->getDateValidationUtility()->validate($val, 'Y-m-d')) {
83
                        throw new InvalidArgumentException('Unrecognized date format. Dates must be in Y-m-d format.');
84
                    }
85
                }
86
            }
87
88
            // Additional check for ordering of dates
89
            if ($type === 'dates') {
90
                if ($values[0] > $values[1]) {
91
                    throw new InvalidArgumentException('First date provided MUST come BEFORE second date.');
92
                }
93
            }
94
95
            // Allow brackets to have UNK as otherwise it's filtering out the queries
96
            if ($type === 'brackets') {
97
                $values[] = 'UNK';
98
            }
99
100
            // Format into strings comma separated for SQL
101
            if (in_array($type, $strings)) {
102
                $queryString = "'" . implode("','", $values) . "'";
103
            }
104
105
            return $queryString;
106
        }
107
108
        if ($type === 'dates') {
109
            return $queryString;
110
        }
111
112
        // Allow brackets to have UNK as otherwise it's filtering out the queries
113
        if ($type === 'brackets') {
114
            $values[] = 'UNK';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$values was never initialized. Although not strictly required by PHP, it is generally a good practice to add $values = 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...
115
        }
116
117
        // If no query string was provided
118
        $return = implode(',', $filters);
119
120
        if (in_array($type, $strings)) {
121
            $return = "'" . implode("','", $filters) . "'";
122
        }
123
124
        return $return;
125
    }
126
127
    /**
128
     * Checks formatting of dates input and then adds them to query
129
     *
130
     * @param mixed         $dates
131
     * @param AbstractQuery $query
132
     * @param boolean       $raw   Determines if query is being used in raw mode
133
     *
134
     * @return void
135
     */
136
    public function addDateRangeWhereClause($dates, AbstractQuery $query, $raw = false)
137
    {
138 View Code Duplication
        if (! is_array($dates)) {
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...
139
            $dates = str_replace('\'', '', $dates); // Remove escaping quotes
140
            $dates = explode(',', $dates);
141
        }
142
143
        // If somehow we don't have a full date range, add today's date
144
        if (empty($dates[1])) {
145
            $dates[1] = date('Y-m-d');
146
        }
147
148
        if ($raw === false) {
149
            $query->where('ResultDateTime >= ?', $dates[0]);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Aura\SqlQuery\AbstractQuery as the method where() does only exist in the following sub-classes of Aura\SqlQuery\AbstractQuery: Aura\SqlQuery\Common\Delete, Aura\SqlQuery\Common\Select, Aura\SqlQuery\Common\Update, Aura\SqlQuery\Mysql\Delete, Aura\SqlQuery\Mysql\Select, Aura\SqlQuery\Mysql\Update, Aura\SqlQuery\Pgsql\Delete, Aura\SqlQuery\Pgsql\Select, Aura\SqlQuery\Pgsql\Update, Aura\SqlQuery\Sqlite\Delete, Aura\SqlQuery\Sqlite\Select, Aura\SqlQuery\Sqlite\Update, Aura\SqlQuery\Sqlsrv\Delete, Aura\SqlQuery\Sqlsrv\Select, Aura\SqlQuery\Sqlsrv\Update. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
150
            $query->where('ResultDateTime <= ?', $dates[1]);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Aura\SqlQuery\AbstractQuery as the method where() does only exist in the following sub-classes of Aura\SqlQuery\AbstractQuery: Aura\SqlQuery\Common\Delete, Aura\SqlQuery\Common\Select, Aura\SqlQuery\Common\Update, Aura\SqlQuery\Mysql\Delete, Aura\SqlQuery\Mysql\Select, Aura\SqlQuery\Mysql\Update, Aura\SqlQuery\Pgsql\Delete, Aura\SqlQuery\Pgsql\Select, Aura\SqlQuery\Pgsql\Update, Aura\SqlQuery\Sqlite\Delete, Aura\SqlQuery\Sqlite\Select, Aura\SqlQuery\Sqlite\Update, Aura\SqlQuery\Sqlsrv\Delete, Aura\SqlQuery\Sqlsrv\Select, Aura\SqlQuery\Sqlsrv\Update. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
151
        } else {
152
            $query->where("ResultDateTime >= '{$dates[0]}' AND ResultDateTime <= '{$dates[1]}'");
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Aura\SqlQuery\AbstractQuery as the method where() does only exist in the following sub-classes of Aura\SqlQuery\AbstractQuery: Aura\SqlQuery\Common\Delete, Aura\SqlQuery\Common\Select, Aura\SqlQuery\Common\Update, Aura\SqlQuery\Mysql\Delete, Aura\SqlQuery\Mysql\Select, Aura\SqlQuery\Mysql\Update, Aura\SqlQuery\Pgsql\Delete, Aura\SqlQuery\Pgsql\Select, Aura\SqlQuery\Pgsql\Update, Aura\SqlQuery\Sqlite\Delete, Aura\SqlQuery\Sqlite\Select, Aura\SqlQuery\Sqlite\Update, Aura\SqlQuery\Sqlsrv\Delete, Aura\SqlQuery\Sqlsrv\Select, Aura\SqlQuery\Sqlsrv\Update. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
153
        }
154
    }
155
156
    public function convertStringToArrayForAuraBinds(string $string)
157
    {
158
        $string = str_replace('\'', '', $string); // Remove escaping quotes
159
        return explode(',', $string);
160
    }
161
}
162