Completed
Push — master ( 111c7d...cc6796 )
by Vitaly
02:51
created

Field::valueColumn()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 8

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 8
nc 3
nop 1
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_TYPE = 'Type';
21
    const F_DELETION = 'Active';
22
    const F_DEFAULT = 'Value';
23
    const F_LOCALIZED = 'local';
24
25
    /** Additional field storing text value */
26
    const TYPE_TEXT = 0;
27
    /** Additional field storing resource link */
28
    const TYPE_RESOURCE = 1;
29
    /** Additional field storing options value */
30
    const TYPE_OPTIONS = 4;
31
    /** Additional field storing other entity identifier */
32
    const TYPE_ENTITYID = 6;
33
    /** Additional field storing numeric value */
34
    const TYPE_NUMERIC = 7;
35
    /** Additional field storing long text value */
36
    const TYPE_LONGTEXT = 8;
37
    /** Additional field storing datetime value */
38
    const TYPE_DATETIME = 10;
39
    /** Additional field storing boolean value */
40
    const TYPE_BOOL = 11;
41
42
    /** @var array Collection of field type to php variable type relations */
43
    protected static $phpTYPE = array(
44
        self::TYPE_TEXT => 'string',
45
        self::TYPE_RESOURCE => 'string',
46
        self::TYPE_OPTIONS => 'string',
47
        self::TYPE_LONGTEXT => 'string',
48
        self::TYPE_BOOL => 'int',
49
        self::TYPE_ENTITYID => 'int',
50
        self::TYPE_NUMERIC => 'int',
51
        self::TYPE_DATETIME => 'bool'
52
    );
53
54
    /**
55
     * Get additional field type in form of Field constant name
56
     * by database additional field type identifier.
57
     *
58
     * @param integer $fieldType Additional field type identifier
59
     * @return string Additional field type constant
60
     * @throws AdditionalFieldTypeNotFound
61
     */
62
    public static function phpType($fieldType)
63
    {
64
        $pointer = & static::$phpTYPE[$fieldType];
65
        if (isset($pointer)) {
66
            return $pointer;
67
        } else {
68
            throw new AdditionalFieldTypeNotFound();
69
        }
70
    }
71
72
    /** @return string Get additional field value field name depending on its type */
73
    public static function valueColumn($type)
74
    {
75
        switch ($type) {
76
            case self::TYPE_NUMERIC:
77
                return 'numeric_value';
78
            case self::TYPE_ENTITYID:
79
                return 'key_value';
80
            default:
81
                return 'Value';
82
        }
83
    }
84
85
    /** @var string Additional field value type */
86
    public $Type;
87
88
    /** @var string Additional field name */
89
    public $Name;
90
91
    /** @var string Default field value */
92
    public $Value;
93
94
    /** @var bool Flag is localized */
95
    public $local;
96
97
    /** @var bool Internal existence flag */
98
    public $Active;
99
100
    /**
101
     * Get current entity instances collection by their identifiers.
102
     * Method can accept different query executors.
103
     *
104
     * @param QueryInterface $query Database query
105
     * @param string|array $fieldIDs Field identifier or their colleciton
106
     * @param self[]|array|null $return Variable where request result would be returned
107
     * @param string $executor Method name for query execution
108
     * @return bool|self[] True if material entities has been found and $return is passed
109
     *                      or self[] if only two parameters is passed.
110
     */
111
    public static function byIDs(QueryInterface $query, $fieldIDs, &$return = array(), $executor = 'exec')
112
    {
113
        $return = $query->entity(get_called_class())
114
            ->where('FieldID', $fieldIDs)
0 ignored issues
show
Bug introduced by
It seems like $fieldIDs defined by parameter $fieldIDs on line 111 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...
115
            ->where('Active', 1)
116
            ->orderBy('priority')
117
            ->$executor();
118
119
        // If only one argument is passed - return null, otherwise bool
120
        return func_num_args() > 2 ? sizeof($return) : $return;
121
    }
122
123
    /**
124
     * Get current entity identifiers collection by navigation identifier.
125
     *
126
     * @param QueryInterface $query Database query
127
     * @param string $navigationID Navigation identifier
128
     * @param array $return Variable where request result would be returned
129
     * @param array $materialIDs Collection of material identifiers for filtering query
130
     * @return bool|array True if field entities has been found and $return is passed
131
     *                      or collection of identifiers if only two parameters is passed.
132
     */
133
    public static function idsByNavigationID(
134
        QueryInterface $query,
135
        $navigationID,
136
        &$return = array(),
137
        $materialIDs = null
138
    ) {
139
        // Prepare query
140
        $query->entity(CMS::FIELD_NAVIGATION_RELATION_ENTITY)
141
            ->where('StructureID', $navigationID)
142
            ->where('Active', 1);
143
144
        // Add material identifier filter if passed
145
        if (isset($materialIDs)) {
146
            $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...
147
        }
148
149
        // Perform database query and get only material identifiers collection
150
        $return = $query->fields('FieldID');
151
152
        // If only one argument is passed - return null, otherwise bool
153
        return func_num_args() > 2 ? sizeof($return) : $return;
154
    }
155
156
    /**
157
     * Get current entity instances collection by navigation identifier.
158
     *
159
     * @param QueryInterface $query Database query
160
     * @param string $navigationID Navigation identifier
161
     * @param self[]|array|null $return Variable where request result would be returned
162
     * @return bool|self[] True if field entities has been found and $return is passed
163
     *                      or self[] if only two parameters is passed.
164
     */
165
    public static function byNavigationID(QueryInterface $query, $navigationID, &$return = array())
166
    {
167
        /** @var array $fieldIDs Collection of entity identifiers filtered by additional field */
168
        $fieldIDs = null;
169
        if (static::idsByNavigationID($query, $navigationID, $fieldIDs)) {
170
            static::byIDs($query, $fieldIDs, $return);
171
        }
172
173
        // If only one argument is passed - return null, otherwise bool
174
        return func_num_args() > 2 ? sizeof($return) : $return;
175
    }
176
177
    /**
178
     * Find additional field database record by Name.
179
     * This is generic method that should be used in nested classes to find its
180
     * records by some its primary key value.
181
     *
182
     * @param QueryInterface $query Query object instance
183
     * @param string $name Additional field name
184
     * @param self $return Variable to return found database record
185
     * @return bool|null|self  Field instance or null if 3rd parameter not passed
186
     */
187
    public static function byName(QueryInterface $query, $name, self & $return = null)
188
    {
189
        // Get field record by name column
190
        $return = static::oneByColumn($query, 'Name', $name);
191
192
        // If only one argument is passed - return null, otherwise bool
193
        return func_num_args() > 1 ? $return == null : $return;
194
    }
195
196
    /**
197
     * Find additional field database record by Name or ID.
198
     * This is generic method that should be used in nested classes to find its
199
     * records by some its primary key value.
200
     *
201
     * @param QueryInterface $query Query object instance
202
     * @param string $nameOrID Additional field name or identifier
203
     * @param self $return Variable to return found database record
204
     * @return bool|null|self  Field instance or null if 3rd parameter not passed
205
     */
206
    public static function byNameOrID(QueryInterface $query, $nameOrID, self & $return = null)
207
    {
208
        // Create id or URL condition
209
        $idOrUrl = new Condition('OR');
210
        $idOrUrl->add('FieldID', $nameOrID)->add('Name', $nameOrID);
211
212
        // Perform query
213
        $return = $query->entity(get_called_class())->whereCondition($idOrUrl)->first();
214
215
        // If only one argument is passed - return null, otherwise bool
216
        return func_num_args() > 1 ? $return == null : $return;
217
    }
218
219
    /**
220
     * If this field has defined key=>value set.
221
     *
222
     * @return array|mixed Grouped collection of field key => value possible values or value for key passed.
223
     */
224
    public function options($key = null)
225
    {
226
        $types = array();
227
        // Convert possible field values to array
228
        foreach (explode(',', $this->Value) as $typeValue) {
229
            // Split view and value
230
            $typeValue = explode(':', $typeValue);
231
232
            // Store to key => value collection
233
            $types[$typeValue[0]] = $typeValue[1];
234
        }
235
236
        return isset($key) ? $types[$key] : $types;
237
    }
238
239
    /** @return string Get additional field value field name depending on its type */
240
    public function valueFieldName()
241
    {
242
        return self::valueColumn($this->Type);
243
    }
244
245
    /** @return bool True if field is localized */
246
    public function localized()
247
    {
248
        return $this->local == 1;
249
    }
250
}
251