Passed
Pull Request — master (#19)
by
unknown
08:00
created

Field::valueColumn()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 5
Bugs 1 Features 3
Metric Value
c 5
b 1
f 3
dl 0
loc 14
ccs 0
cts 9
cp 0
rs 8.8571
cc 6
eloc 11
nc 6
nop 1
crap 42
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 date value */
30
    const TYPE_DATE = 3;
31
    /** Additional field storing options value */
32
    const TYPE_OPTIONS = 4;
33
    /** Additional field storing other entity identifier */
34
    const TYPE_ENTITYID = 6;
35
    /** Additional field storing numeric value */
36
    const TYPE_NUMERIC = 7;
37
    /** Additional field storing long text value */
38
    const TYPE_LONGTEXT = 8;
39
	    /** Additional field storing gallery value */
40
    const TYPE_GALLERY = 9;
41
    /** Additional field storing datetime value */
42
    const TYPE_DATETIME = 10;
43
    /** Additional field storing boolean value */
44
    const TYPE_BOOL = 11;
45
    /** Additional field navigation identifier value */
46
    const TYPE_NAVIGATION = 12;
47
    /** Additional field external picture identifier value */
48
    const TYPE_EXTERNALPICTURE = 13;
49
	
50
    /** @var array Collection of field type to php variable type relations */
51
    protected static $phpTYPE = array(
52
        self::TYPE_TEXT => 'string',
53
        self::TYPE_RESOURCE => 'string',
54
        self::TYPE_OPTIONS => 'string',
55
        self::TYPE_LONGTEXT => 'string',
56
        self::TYPE_BOOL => 'bool',
57
        self::TYPE_ENTITYID => 'int',
58
        self::TYPE_NUMERIC => 'int',
59
        self::TYPE_DATETIME => 'int',
60
        self::TYPE_DATE => 'int',
61
        self::TYPE_GALLERY => 'int',
62
        self::TYPE_NAVIGATION => 'int',
63
		self::TYPE_EXTERNALPICTURE => 'string'
64
    );
65
66
    /**
67
     * Get additional field type in form of Field constant name
68
     * by database additional field type identifier.
69
     *
70
     * @param integer $fieldType Additional field type identifier
71
     * @return string Additional field type constant
72
     * @throws AdditionalFieldTypeNotFound
73
     */
74
    public static function phpType($fieldType)
75
    {
76
        $pointer = & static::$phpTYPE[$fieldType];
77
        if (isset($pointer)) {
78
            return $pointer;
79
        } else {
80
            throw new AdditionalFieldTypeNotFound($fieldType);
81
        }
82
    }
83
84
    /** @return string Get additional field value field name depending on its type */
85
    public static function valueColumn($type)
86
    {
87
        switch ($type) {
88
            case self::TYPE_DATETIME:
89
            case self::TYPE_DATE:
90
            case self::TYPE_NUMERIC:
91
                return MaterialField::F_NUMERIC;
92
            case self::TYPE_ENTITYID:
93
            case self::TYPE_NAVIGATION:
94
                return MaterialField::F_KEY;
95
            default:
96
                return MaterialField::F_VALUE;
97
        }
98
    }
99
100
    /** @var string Additional field value type */
101
    public $Type;
102
103
    /** @var string Additional field name */
104
    public $Name;
105
106
    /** @var string Default field value */
107
    public $Value;
108
109
    /** @var bool Flag is localized */
110
    public $local;
111
112
    /** @var bool Internal existence flag */
113
    public $Active;
114
115
    /**
116
     * Get current entity instances collection by their identifiers.
117
     * Method can accept different query executors.
118
     *
119
     * @param QueryInterface $query Database query
120
     * @param string|array $fieldIDs Field identifier or their colleciton
121
     * @param self[]|array|null $return Variable where request result would be returned
122
     * @param string $executor Method name for query execution
123
     * @return bool|self[] True if material entities has been found and $return is passed
124
     *                      or self[] if only two parameters is passed.
125
     */
126 View Code Duplication
    public static function byIDs(QueryInterface $query, $fieldIDs, &$return = array(), $executor = 'exec')
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...
127
    {
128
        $return = $query->entity(get_called_class())
129
            ->where('FieldID', $fieldIDs)
130
            ->where('Active', 1)
131
            ->orderBy('priority')
132
            ->$executor();
133
134
        // If only one argument is passed - return null, otherwise bool
135
        return func_num_args() > 2 ? sizeof($return) : $return;
136
    }
137
138
    /**
139
     * Get current entity identifiers collection by navigation identifier.
140
     *
141
     * @param QueryInterface $query Database query
142
     * @param string $navigationID Navigation identifier
143
     * @param array $return Variable where request result would be returned
144
     * @param array $materialIDs Collection of material identifiers for filtering query
145
     * @return bool|array True if field entities has been found and $return is passed
146
     *                      or collection of identifiers if only two parameters is passed.
147
     */
148
    public static function idsByNavigationID(
149
        QueryInterface $query,
150
        $navigationID,
151
        &$return = array(),
152
        $materialIDs = null
153
    ) {
154
        // Prepare query
155
        $query->entity(CMS::FIELD_NAVIGATION_RELATION_ENTITY)
156
            ->where('StructureID', $navigationID)
157
            ->where('Active', 1);
158
159
        // Add material identifier filter if passed
160
        if (isset($materialIDs)) {
161
            $query->where('MaterialID', $materialIDs);
162
        }
163
164
        // Perform database query and get only material identifiers collection
165
        $return = $query->fields('FieldID');
166
167
        // If only one argument is passed - return null, otherwise bool
168
        return func_num_args() > 2 ? sizeof($return) : $return;
169
    }
170
171
    /**
172
     * Get current entity instances collection by navigation identifier.
173
     *
174
     * @param QueryInterface $query Database query
175
     * @param string $navigationID Navigation identifier
176
     * @param self[]|array|null $return Variable where request result would be returned
177
     * @return bool|self[] True if field entities has been found and $return is passed
178
     *                      or self[] if only two parameters is passed.
179
     */
180
    public static function byNavigationID(QueryInterface $query, $navigationID, &$return = array())
181
    {
182
        /** @var array $fieldIDs Collection of entity identifiers filtered by additional field */
183
        $fieldIDs = null;
184
        if (static::idsByNavigationID($query, $navigationID, $fieldIDs)) {
185
            static::byIDs($query, $fieldIDs, $return);
186
        }
187
188
        // If only one argument is passed - return null, otherwise bool
189
        return func_num_args() > 2 ? sizeof($return) : $return;
190
    }
191
192
    /**
193
     * Find additional field database record by Name.
194
     * This is generic method that should be used in nested classes to find its
195
     * records by some its primary key value.
196
     *
197
     * @param QueryInterface $query Query object instance
198
     * @param string $name Additional field name
199
     * @param self $return Variable to return found database record
200
     * @return bool|null|self  Field instance or null if 3rd parameter not passed
201
     */
202
    public static function byName(QueryInterface $query, $name, self & $return = null)
203
    {
204
        // Get field record by name column
205
        $return = static::oneByColumn($query, 'Name', $name);
0 ignored issues
show
Deprecated Code introduced by
The method samsonframework\orm\Record::oneByColumn() has been deprecated with message: Record should not be queryable, query class ancestor must be used

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
206
207
        // If only one argument is passed - return null, otherwise bool
208
        return func_num_args() > 1 ? $return == null : $return;
209
    }
210
211
    /**
212
     * Find additional field database record by Name or ID.
213
     * This is generic method that should be used in nested classes to find its
214
     * records by some its primary key value.
215
     *
216
     * @param QueryInterface $query Query object instance
217
     * @param string $nameOrID Additional field name or identifier
218
     * @param self $return Variable to return found database record
219
     * @return bool|null|self  Field instance or null if 3rd parameter not passed
220
     */
221
    public static function byNameOrID(QueryInterface $query, $nameOrID, self & $return = null)
222
    {
223
        // Create id or URL condition
224
        $idOrUrl = new Condition('OR');
225
        $idOrUrl->add('FieldID', $nameOrID)->add('Name', $nameOrID);
226
227
        // Perform query
228
        $return = $query->entity(get_called_class())->whereCondition($idOrUrl)->first();
229
230
        // If only one argument is passed - return null, otherwise bool
231
        return func_num_args() > 1 ? $return == null : $return;
232
    }
233
234
    /**
235
     * If this field has defined key=>value set.
236
     *
237
     * @return array|mixed Grouped collection of field key => value possible values or value for key passed.
238
     */
239
    public function options($key = null)
240
    {
241
        $types = array();
242
        // Convert possible field values to array
243
        foreach (explode(',', $this->Value) as $typeValue) {
244
            // Split view and value
245
            $typeValue = explode(':', $typeValue);
246
247
            // Store to key => value collection
248
            $types[$typeValue[0]] = $typeValue[1];
249
        }
250
251
        return isset($key) ? $types[$key] : $types;
252
    }
253
254
    /** @return string Get additional field value field name depending on its type */
255
    public function valueFieldName()
256
    {
257
        return self::valueColumn($this->Type);
258
    }
259
260
    /** @return bool True if field is localized */
261
    public function localized()
262
    {
263
        return $this->local == 1;
264
    }
265
}
266