Completed
Push — master ( c30967...3bd52a )
by Andrii
03:06
created

Query::options()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 3
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * ActiveRecord for API
4
 *
5
 * @link      https://github.com/hiqdev/yii2-hiart
6
 * @package   yii2-hiart
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\hiart;
12
13
use yii\db\QueryInterface;
14
15
/**
16
 * Query represents API query in a way that is independent from a concrete API.
17
 * Holds API query information:
18
 * - general query data
19
 *      - action: action to be performed with this query, e.g. search, insert, update, delete
20
 *      - options: other additional options, like
21
 *          - raw: do not decode response
22
 *          - batch: batch(bulk) request
23
 *          - timeout, ...
24
 * - insert/update query data
25
 *      - body: insert or update data
26
 * - select query data
27
 *      - select: fields to select
28
 *      - count: marks count query
29
 *      - from: entity being queried, e.g. user
30
 *      - join: data how to join with other entities
31
 * - other standard query options provided with QueryTrait:
32
 *      - where, limit, offset, orderBy, indexBy.
33
 */
34
class Query extends \yii\db\Query implements QueryInterface
35
{
36
    /**
37
     * @var string action that this query performs
38
     */
39
    public $action;
40
41
    /**
42
     * @var array query options e.g. raw, batch
43
     */
44
    public $options = [];
45
46
    public $count;
47
48
    public $body = [];
49
50
    public static function instantiate($action, $from, array $options = [])
51
    {
52
        $query = new static();
53
54
        return $query->action($action)->from($from)->options($options);
55
    }
56
57
    /**
58
     * @param null $db
59
     * @throws \Exception
60
     * @return Command
61
     */
62 2
    public function createCommand($db = null)
63
    {
64 2
        if ($db === null) {
65
            throw new \Exception('no db given to Query::createCommand');
66
        }
67
68 2
        $commandConfig = $db->getQueryBuilder()->build($this);
0 ignored issues
show
Bug introduced by
The method getQueryBuilder cannot be called on $db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
69
70 2
        return $db->createCommand($commandConfig);
0 ignored issues
show
Bug introduced by
The method createCommand cannot be called on $db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
71
    }
72
73
    public function one($db = null)
74
    {
75
        return $this->searchOne($db);
76
    }
77
78
    public function searchOne($db = null)
79
    {
80
        return $this->searchSingle($db)->getData();
81
    }
82
83
    public function searchSingle($db = null)
84
    {
85
        return $this->limit(1)->addOption('batch', false)->search($db);
86
    }
87
88
    public function all($db = null)
89
    {
90
        $rows = $this->searchAll($db);
91
92
        if (!empty($rows) && $this->indexBy !== null) {
93
            $result = [];
94
            foreach ($rows as $row) {
95 View Code Duplication
                if ($this->indexBy instanceof \Closure) {
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...
96
                    $key = call_user_func($this->indexBy, $row);
97
                } else {
98
                    $key = $row[$this->indexBy];
99
                }
100
                $result[$key] = $row;
101
            }
102
            $rows = $result;
103
        }
104
105
        return $rows;
106
    }
107
108 2
    public function searchAll($db = null)
109
    {
110 2
        return $this->searchBatch($db)->getData();
111
    }
112
113 2
    public function searchBatch($db = null)
114
    {
115 2
        return $this->addOption('batch', true)->search($db);
116
    }
117
118 2
    public function search($db = null)
119
    {
120 2
        return $this->createCommand($db)->search();
121
    }
122
123
    public function delete($db = null, $options = [])
124
    {
125
        return $this->createCommand($db)->deleteByQuery($options);
0 ignored issues
show
Documentation Bug introduced by
The method deleteByQuery does not exist on object<hiqdev\hiart\Command>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
126
    }
127
128
    public function count($q = '*', $db = null)
129
    {
130
        $this->count = $q;
131
132
        return (int) $this->searchAll($db);
133
    }
134
135
    public function exists($db = null)
136
    {
137
        return !empty(self::one($db));
138
    }
139
140
    public function action($action)
141
    {
142
        $this->action = $action;
143
144
        return $this;
145
    }
146
147 2
    public function addAction($action)
148
    {
149 2
        if (empty($this->action)) {
150 2
            $this->action = $action;
151
        }
152
153 2
        return $this;
154
    }
155
156 2
    public function addOption($name, $value)
157
    {
158 2
        if (!isset($this->options[$name])) {
159 2
            $this->options[$name] = $value;
160
        }
161
162 2
        return $this;
163
    }
164
165
    public function getOption($name)
166
    {
167
        return isset($this->options[$name]) ? $this->options[$name] : null;
168
    }
169
170
    public function options($options)
171
    {
172
        $this->options = $options;
173
174
        return $this;
175
    }
176
177
    public function addOptions($options)
178
    {
179
        if (!empty($options)) {
180
            $this->options = array_merge($this->options, $options);
181
        }
182
183
        return $this;
184
    }
185
186
    public function body($body)
187
    {
188
        $this->body = $body;
189
190
        return $this;
191
    }
192
193
    public function innerJoin($table, $on = '', $params = [])
194
    {
195
        $this->join[] = (array) $table;
196
197
        return $this;
198
    }
199
200 View Code Duplication
    public function fields($fields)
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...
201
    {
202
        if (is_array($fields) || $fields === null) {
203
            $this->fields = $fields;
0 ignored issues
show
Documentation introduced by
The property fields does not exist on object<hiqdev\hiart\Query>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
204
        } else {
205
            $this->fields = func_get_args();
0 ignored issues
show
Documentation introduced by
The property fields does not exist on object<hiqdev\hiart\Query>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
206
        }
207
208
        return $this;
209
    }
210
211 View Code Duplication
    public function source($source)
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...
212
    {
213
        if (is_array($source) || $source === null) {
214
            $this->source = $source;
0 ignored issues
show
Documentation introduced by
The property source does not exist on object<hiqdev\hiart\Query>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
215
        } else {
216
            $this->source = func_get_args();
0 ignored issues
show
Documentation introduced by
The property source does not exist on object<hiqdev\hiart\Query>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
217
        }
218
219
        return $this;
220
    }
221
}
222