Completed
Push — master ( 189bb6...0d32b3 )
by Matthew
03:08
created

AbstractEndpointRepository::read()   F

Complexity

Conditions 18
Paths 360

Size

Total Lines 87
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 14
Bugs 2 Features 10
Metric Value
c 14
b 2
f 10
dl 0
loc 87
rs 3.6715
cc 18
eloc 44
nc 360
nop 1

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\Repository;
4
5
use Aura\SqlQuery\AbstractQuery;
6
use Aura\SqlQuery\QueryFactory;
7
use Ps2alerts\Api\Contract\DatabaseAwareInterface;
8
use Ps2alerts\Api\Contract\DatabaseAwareTrait;
9
use Ps2alerts\Api\Contract\RedisAwareInterface;
10
use Ps2alerts\Api\Contract\RedisAwareTrait;
11
use Ps2alerts\Api\Contract\UuidAwareInterface;
12
use Ps2alerts\Api\Contract\UuidAwareTrait;
13
use Ps2alerts\Api\QueryObjects\QueryObject;
14
15
abstract class AbstractEndpointRepository implements
16
    DatabaseAwareInterface,
17
    RedisAwareInterface,
18
    UuidAwareInterface
19
{
20
    use DatabaseAwareTrait;
21
    use RedisAwareTrait;
22
    use UuidAwareTrait;
23
24
    /**
25
     * Determines the table that the DB is interfacing with
26
     *
27
     * @return string
28
     */
29
    abstract public function getTable();
30
31
    /**
32
     * Determines the primary key of the table
33
     *
34
     * @return string
35
     */
36
    abstract public function getPrimaryKey();
37
38
    /**
39
     * Determines the Result key of the table
40
     *
41
     * @return string
42
     */
43
    abstract public function getResultKey();
44
45
    /**
46
     * Builds a new query factory ready for use with the QueryObjects
47
     *
48
     * @return \Aura\SqlQuery\AbstractQuery
49
     */
50
    public function newQuery()
51
    {
52
        $factory = new QueryFactory('mysql');
53
54
        $query = $factory->newSelect(); // Suspect I'll only ever need this one
55
        $query->from($this->getTable());
56
57
        return $query;
58
    }
59
60
    /**
61
     * Sets up the resulting query based off properties present in the supplied object.
62
     *
63
     * @see \Ps2alerts\Api\QueryObjects\QueryObject
64
     *
65
     * @param  \Ps2alerts\Api\QueryObjects\QueryObject $queryObject
66
     * @return array
67
     */
68
    public function read(QueryObject $queryObject)
69
    {
70
        $query = $this->newQuery();
71
72
        // Setup select statements
73
        if (! empty($queryObject->getSelects())) {
74
            $query->cols($queryObject->getSelects());
75
        } else {
76
            $query->cols(['*']);
77
        }
78
79
        // Workarounds :-/
80
        if (! empty($queryObject->getFlags())) {
81
            if ($queryObject->getFlags() === 'outfitIDs') {
82
                // Prevent the VS, NC and TR "no outfit" workaround
83
                $queryObject->addWhere([
84
                    'col' => 'outfitID',
85
                    'op' => '>',
86
                    'value' => 0
87
                ]);
88
            }
89
        }
90
91
        // Setup where statements
92
        if (! empty($queryObject->getWheres())) {
93
            foreach ($queryObject->getWheres() as $where) {
94
                $col = $where['col'];
95
96
                if ($where['col'] === 'primary') {
97
                    $col = $this->getPrimaryKey();
98
                }
99
                if ($where['col'] === 'result') {
100
                    $col = $this->getResultKey();
101
                }
102
103
                // Generate a UUID so that any columns that are used multiple
104
                // times always have unique values. Tiny overhead for the benefit
105
                $uuid = $this->getUuidDriver()->uuid4()->toString();
106
                $bind = str_replace('-', '', $col.$uuid);
107
108
                $op = (isset($where['op']) ? $where['op'] : '=');
109
110
                $query->where("{$col} {$op} :$bind");
111
                $query->bindValue($bind, $where['value']);
112
            }
113
        }
114
115
        // Setup where statements
116
        if (! empty($queryObject->getWhereIns())) {
117
            foreach ($queryObject->getWhereIns() as $whereIn) {
118
                $col = $whereIn['col'];
119
120
                if ($whereIn['col'] === 'primary') {
121
                    $col = $this->getPrimaryKey();
122
                }
123
                if ($whereIn['col'] === 'result') {
124
                    $col = $this->getResultKey();
125
                }
126
127
                $query->where("{$col} IN ({$whereIn['value']})");
128
            }
129
        }
130
131
        // Set up order statement
132
        if (! empty($queryObject->getOrderBy())) {
133
            $orderBy = $queryObject->getOrderBy();
134
            if ($orderBy === 'primary') {
135
                $orderBy = $this->getPrimaryKey();
136
            }
137
            if ($orderBy === 'result') {
138
                $orderBy = $this->getResultKey();
139
            }
140
141
            $query->orderBy([
1 ignored issue
show
Bug introduced by
The method orderBy() does not exist on Aura\SqlQuery\AbstractQuery. Did you maybe mean addOrderBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
142
                "`{$orderBy}` {$queryObject->getOrderByDirection()}"
143
            ]);
144
        }
145
146
        if (! empty($queryObject->getLimit())) {
147
            // Only set a limit if it's required
148
            if ($queryObject->getLimit() !== 'unlimited') {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of $queryObject->getLimit() (integer) and 'unlimited' (string) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
149
                $query->limit($queryObject->getLimit());
150
            }
151
        }
152
153
        return $this->prepareAndExecuteQuery($query, $queryObject);
154
    }
155
156
    /**
157
     * Sets up the PDO Driver, then executes the query based on dimension.
158
     *
159
     * @param  \Aura\SqlQuery\AbstractQuery $query
160
     * @param  \Ps2alerts\Api\QueryObjects\QueryObject $queryObject Sent QueryObject to read dimension
161
     * @return array The final data
162
     */
163
    public function prepareAndExecuteQuery(AbstractQuery $query, QueryObject $queryObject)
164
    {
165
        $pdo = $this->getDatabaseDriver();
166
167
        //var_dump($query->getStatement());die;
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% 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...
168
169
        if ($queryObject->getDimension() === 'multi') {
170
            return $pdo->fetchAll($query->getStatement(), $query->getBindValues());
171
        }
172
173
174
        return $pdo->fetchOne($query->getStatement(), $query->getBindValues());
175
    }
176
}
177