Completed
Push — master ( 883d2e...18bc1e )
by Oscar
02:27
created

Select::leftJoin()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 12

Duplication

Lines 6
Ratio 26.09 %

Importance

Changes 7
Bugs 1 Features 0
Metric Value
c 7
b 1
f 0
dl 6
loc 23
rs 8.7972
cc 4
eloc 12
nc 4
nop 3
1
<?php
2
3
namespace SimpleCrud\Queries\Mysql;
4
5
use SimpleCrud\SimpleCrudException;
6
use SimpleCrud\Queries\Query;
7
use SimpleCrud\Scheme\Scheme;
8
use SimpleCrud\RowCollection;
9
use SimpleCrud\Table;
10
use PDO;
11
12
/**
13
 * Manages a database select query.
14
 */
15
class Select extends Query
16
{
17
    const MODE_ONE = 1;
18
    const MODE_ALL = 2;
19
20
    use ExtendedSelectionTrait;
21
22
    protected $leftJoin = [];
23
    protected $orderBy = [];
24
    protected $statement;
25
    protected $mode = 2;
26
27
    /**
28
     * Change the mode to returns just the first row.
29
     * 
30
     * @return self
31
     */
32
    public function one()
33
    {
34
        $this->mode = self::MODE_ONE;
35
36
        return $this->limit(1);
37
    }
38
39
    /**
40
     * Change the mode to returns all rows.
41
     * 
42
     * @return self
43
     */
44
    public function all()
45
    {
46
        $this->mode = self::MODE_ALL;
47
48
        return $this;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     *
54
     * @return Row|RowCollection|null
55
     */
56
    public function run()
57
    {
58
        $statement = $this->__invoke();
59
60
        if ($this->mode === self::MODE_ONE) {
61
            return ($row = $statement->fetch()) === false ? null : $this->createRow($row);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return ($row = $statemen...$this->createRow($row); (array) is incompatible with the return type of the parent method SimpleCrud\Queries\Query::run of type SimpleCrud\Queries\PDOStatement.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
62
        }
63
64
        $result = $this->table->createCollection();
65
66
        while (($row = $statement->fetch())) {
67
            $result[] = $this->createRow($row);
68
        }
69
70
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $result; (SimpleCrud\RowCollection) is incompatible with the return type of the parent method SimpleCrud\Queries\Query::run of type SimpleCrud\Queries\PDOStatement.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
71
    }
72
73
    /**
74
     * Create a row and insert the joined rows if exist.
75
     *
76
     * @param array $data
77
     * 
78
     * @return Row
79
     */
80
    public function createRow(array $data)
81
    {
82
        $row = $this->table->createFromDatabase($data);
83
84
        if (empty($this->leftJoin)) {
85
            return $row;
86
        }
87
88
        foreach ($this->leftJoin as $join) {
89
            $table = $this->table->getDatabase()->{$join['table']};
90
            $values = [];
91
92
            foreach (array_keys($table->fields) as $name) {
93
                $field = sprintf('%s.%s', $join['table'], $name);
94
                $values[$name] = $data[$field];
95
            }
96
97
            $row->{$join['table']} = empty($values['id']) ? null : $table->createFromDatabase($values);
98
        }
99
100
        return $row;
101
    }
102
103
    /**
104
     * Adds an ORDER BY clause.
105
     *
106
     * @param string      $orderBy
107
     * @param string|null $direction
108
     *
109
     * @return self
110
     */
111
    public function orderBy($orderBy, $direction = null)
112
    {
113
        if (!empty($direction)) {
114
            $orderBy .= ' '.$direction;
115
        }
116
117
        $this->orderBy[] = $orderBy;
118
119
        return $this;
120
    }
121
122
    /**
123
     * Adds a LEFT JOIN clause.
124
     *
125
     * @param string     $table
126
     * @param string     $on
127
     * @param array|null $marks
128
     *
129
     * @return self
130
     */
131
    public function leftJoin($table, $on = null, $marks = null)
132
    {
133
        $scheme = $this->table->getScheme();
134
135 View Code Duplication
        if (!isset($scheme['relations'][$table])) {
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...
136
            throw new SimpleCrudException(sprintf("The tables '%s' and '%s' are not related", $this->table->name, $table));
137
        }
138
139 View Code Duplication
        if ($scheme['relations'][$table][0] !== Scheme::HAS_ONE) {
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...
140
            throw new SimpleCrudException(sprintf("Invalid LEFT JOIN between the tables '%s' and '%s'", $this->table->name, $table));
141
        }
142
143
        $this->leftJoin[] = [
144
            'table' => $table,
145
            'on' => $on,
146
        ];
147
148
        if ($marks) {
149
            $this->marks += $marks;
150
        }
151
152
        return $this;
153
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158 View Code Duplication
    public function __invoke()
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...
159
    {
160
        $statement = $this->table->getDatabase()->execute((string) $this, $this->marks);
161
        $statement->setFetchMode(PDO::FETCH_ASSOC);
162
163
        return $statement;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $statement; (PDOStatement) is incompatible with the return type declared by the abstract method SimpleCrud\Queries\Query::__invoke of type SimpleCrud\Queries\PDOStatement.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
164
    }
165
166
    /**
167
     * {@inheritdoc}
168
     */
169
    public function __toString()
170
    {
171
        $query = 'SELECT';
172
        $query .= ' '.static::buildFields($this->table->name, array_keys($this->table->fields));
173
174
        foreach ($this->leftJoin as $join) {
175
            $query .= ', '.static::buildFields($join['table'], array_keys($this->table->getDatabase()->{$join['table']}->fields), true);
176
        }
177
178
        $query .= $this->fieldsToString();
179
        $query .= sprintf(' FROM `%s`', $this->table->name);
180
        $query .= $this->fromToString();
181
182
        foreach ($this->leftJoin as $join) {
183
            $relation = $this->table->getScheme()['relations'][$join['table']];
184
185
            $query .= sprintf(
186
                ' LEFT JOIN `%s` ON (`%s`.`id` = `%s`.`%s`%s)',
187
                $join['table'],
188
                $join['table'],
189
                $this->table->name,
190
                $relation[1],
191
                empty($join['on']) ? '' : sprintf(' AND (%s)', $join['on'])
192
            );
193
        }
194
195
        $query .= $this->whereToString();
196
197
        if (!empty($this->orderBy)) {
198
            $query .= ' ORDER BY '.implode(', ', $this->orderBy);
199
        }
200
201
        $query .= $this->limitToString();
202
203
        return $query;
204
    }
205
206
    /**
207
     * Generates the fields/tables part of a SELECT query.
208
     *
209
     * @param string $table
210
     * @param array  $fields
211
     * @param bool   $rename
212
     *
213
     * @return string
214
     */
215
    protected static function buildFields($table, array $fields, $rename = false)
216
    {
217
        $query = [];
218
219
        foreach ($fields as $field) {
220
            if ($rename) {
221
                $query[] = "`{$table}`.`{$field}` as `{$table}.{$field}`";
222
            } else {
223
                $query[] = "`{$table}`.`{$field}`";
224
            }
225
        }
226
227
        return implode(', ', $query);
228
    }
229
}
230