Completed
Push — master ( 47c858...15c002 )
by Vitaly
04:57
created

Field::byNavigationID()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4286
cc 3
eloc 5
nc 4
nop 3
1
<?php
2
namespace samsoncms\api;
3
4
use samsoncms\api\exception\AdditionalFieldTypeNotFound;
5
use samsonframework\orm\Condition;
6
use samsonframework\orm\QueryInterface;
7
8
/**
9
 * SamsonCMS additional field table entity class
10
 * @package samson\cms
11
 */
12
class Field extends \samson\activerecord\field
13
{
14
    /** Store entity name */
15
    const ENTITY = __CLASS__;
16
17
    /** Entity field names constants for using in code */
18
    const F_PRIMARY = 'FieldID';
19
    const F_IDENTIFIER = 'Name';
20
    const F_DELETION = 'Active';
21
    const F_DEFAULT = 'Value';
22
    const F_LOCALIZED = 'local';
23
24
    /** Additional field storing text value */
25
    const TYPE_TEXT = 0;
26
    /** Additional field storing resource link */
27
    const TYPE_RESOURCE = 1;
28
    /** Additional field storing options value */
29
    const TYPE_OPTIONS = 4;
30
    /** Additional field storing other entity identifier */
31
    const TYPE_ENTITYID = 6;
32
    /** Additional field storing numeric value */
33
    const TYPE_NUMERIC = 7;
34
    /** Additional field storing long text value */
35
    const TYPE_LONGTEXT = 8;
36
    /** Additional field storing datetime value */
37
    const TYPE_DATETIME = 10;
38
    /** Additional field storing boolean value */
39
    const TYPE_BOOL = 11;
40
41
    /** @var array Collection of field type to php variable type relations */
42
    protected static $phpTYPE = array(
43
        self::TYPE_TEXT => 'string',
44
        self::TYPE_RESOURCE => 'string',
45
        self::TYPE_OPTIONS => 'string',
46
        self::TYPE_LONGTEXT => 'string',
47
        self::TYPE_BOOL => 'int',
48
        self::TYPE_ENTITYID => 'int',
49
        self::TYPE_NUMERIC => 'int',
50
        self::TYPE_DATETIME => 'bool'
51
    );
52
53
    /**
54
     * Get additional field type in form of Field constant name
55
     * by database additional field type identifier.
56
     *
57
     * @param integer $fieldType Additional field type identifier
58
     * @return string Additional field type constant
59
     * @throws AdditionalFieldTypeNotFound
60
     */
61
    public static function phpType($fieldType)
62
    {
63
        $pointer = & static::$phpTYPE[$fieldType];
64
        if (isset($pointer)) {
65
            return $pointer;
66
        } else {
67
            throw new AdditionalFieldTypeNotFound();
68
        }
69
    }
70
71
    /** @var string Additional field value type */
72
    public $Type;
73
74
    /** @var string Additional field name */
75
    public $Name;
76
77
    /** @var string Default field value */
78
    public $Value;
79
80
    /** @var bool Flag is localized */
81
    public $local;
82
83
    /** @var bool Internal existence flag */
84
    public $Active;
85
86
    /**
87
     * Get current entity instances collection by their identifiers.
88
     * Method can accept different query executors.
89
     *
90
     * @param QueryInterface $query Database query
91
     * @param string|array $fieldIDs Field identifier or their colleciton
92
     * @param self[]|array|null $return Variable where request result would be returned
93
     * @param string $executor Method name for query execution
94
     * @return bool|self[] True if material entities has been found and $return is passed
95
     *                      or self[] if only two parameters is passed.
96
     */
97
    public static function byIDs(QueryInterface $query, $fieldIDs, &$return = array(), $executor = 'exec')
98
    {
99
        $return = $query->entity(get_called_class())
100
            ->where('FieldID', $fieldIDs)
0 ignored issues
show
Bug introduced by
It seems like $fieldIDs defined by parameter $fieldIDs on line 97 can also be of type array; however, samsonframework\orm\QueryInterface::where() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
101
            ->where('Active', 1)
102
            ->orderBy('priority')
103
            ->$executor();
104
105
        // If only one argument is passed - return null, otherwise bool
106
        return func_num_args() > 2 ? sizeof($return) : $return;
107
    }
108
109
    /**
110
     * Get current entity identifiers collection by navigation identifier.
111
     *
112
     * @param QueryInterface $query Database query
113
     * @param string $navigationID Navigation identifier
114
     * @param array $return Variable where request result would be returned
115
     * @param array $materialIDs Collection of material identifiers for filtering query
116
     * @return bool|array True if field entities has been found and $return is passed
117
     *                      or collection of identifiers if only two parameters is passed.
118
     */
119
    public static function idsByNavigationID(
120
        QueryInterface $query,
121
        $navigationID,
122
        &$return = array(),
123
        $materialIDs = null
124
    ) {
125
        // Prepare query
126
        $query->entity(CMS::FIELD_NAVIGATION_RELATION_ENTITY)
127
            ->where('StructureID', $navigationID)
128
            ->where('Active', 1);
129
130
        // Add material identifier filter if passed
131
        if (isset($materialIDs)) {
132
            $query->where('MaterialID', $materialIDs);
0 ignored issues
show
Documentation introduced by
$materialIDs is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
133
        }
134
135
        // Perform database query and get only material identifiers collection
136
        $return = $query->fields('FieldID');
137
138
        // If only one argument is passed - return null, otherwise bool
139
        return func_num_args() > 2 ? sizeof($return) : $return;
140
    }
141
142
    /**
143
     * Get current entity instances collection by navigation identifier.
144
     *
145
     * @param QueryInterface $query Database query
146
     * @param string $navigationID Navigation identifier
147
     * @param self[]|array|null $return Variable where request result would be returned
148
     * @return bool|self[] True if field entities has been found and $return is passed
149
     *                      or self[] if only two parameters is passed.
150
     */
151
    public static function byNavigationID(QueryInterface $query, $navigationID, &$return = array())
152
    {
153
        /** @var array $fieldIDs Collection of entity identifiers filtered by additional field */
154
        $fieldIDs = null;
155
        if (static::idsByNavigationID($query, $navigationID, $fieldIDs)) {
156
            static::byIDs($query, $fieldIDs, $return);
157
        }
158
159
        // If only one argument is passed - return null, otherwise bool
160
        return func_num_args() > 2 ? sizeof($return) : $return;
161
    }
162
163
    /**
164
     * Find additional field database record by Name.
165
     * This is generic method that should be used in nested classes to find its
166
     * records by some its primary key value.
167
     *
168
     * @param QueryInterface $query Query object instance
169
     * @param string $name Additional field name
170
     * @param self $return Variable to return found database record
171
     * @return bool|null|self  Field instance or null if 3rd parameter not passed
172
     */
173
    public static function byName(QueryInterface $query, $name, self & $return = null)
174
    {
175
        // Get field record by name column
176
        $return = static::oneByColumn($query, 'Name', $name);
177
178
        // If only one argument is passed - return null, otherwise bool
179
        return func_num_args() > 1 ? $return == null : $return;
180
    }
181
182
    /**
183
     * Find additional field database record by Name or ID.
184
     * This is generic method that should be used in nested classes to find its
185
     * records by some its primary key value.
186
     *
187
     * @param QueryInterface $query Query object instance
188
     * @param string $nameOrID Additional field name or identifier
189
     * @param self $return Variable to return found database record
190
     * @return bool|null|self  Field instance or null if 3rd parameter not passed
191
     */
192
    public static function byNameOrID(QueryInterface $query, $nameOrID, self & $return = null)
193
    {
194
        // Create id or URL condition
195
        $idOrUrl = new Condition('OR');
196
        $idOrUrl->add('FieldID', $nameOrID)->add('Name', $nameOrID);
197
198
        // Perform query
199
        $return = $query->entity(get_called_class())->whereCondition($idOrUrl)->first();
200
201
        // If only one argument is passed - return null, otherwise bool
202
        return func_num_args() > 1 ? $return == null : $return;
203
    }
204
205
    /**
206
     * If this field has defined key=>value set.
207
     *
208
     * @return array|mixed Grouped collection of field key => value possible values or value for key passed.
209
     */
210
    public function options($key = null)
211
    {
212
        $types = array();
213
        // Convert possible field values to array
214
        foreach (explode(',', $this->Value) as $typeValue) {
215
            // Split view and value
216
            $typeValue = explode(':', $typeValue);
217
218
            // Store to key => value collection
219
            $types[$typeValue[0]] = $typeValue[1];
220
        }
221
222
        return isset($key) ? $types[$key] : $types;
223
    }
224
225
    /** @return string Get additional field value field name depending on its type */
226
    public function valueFieldName()
227
    {
228
        switch ($this->Type) {
229
            case self::TYPE_NUMERIC:
230
                return 'numeric_value';
231
            case self::TYPE_ENTITYID:
232
                return 'key_value';
233
            default:
234
                return 'Value';
235
        }
236
    }
237
238
    /** @return bool True if field is localized */
239
    public function localized()
240
    {
241
        return $this->local == 1;
242
    }
243
}
244