Test Failed
Branch master (5aadec)
by Agel_Nash
04:00
created

MODxAPI::decodeField()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 8
nc 4
nop 2
1
<?php
2
include_once(MODX_BASE_PATH . 'assets/lib/APIHelpers.class.php');
1 ignored issue
show
Bug introduced by
The constant MODX_BASE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
3
include_once(MODX_BASE_PATH . 'assets/snippets/DocLister/lib/jsonHelper.class.php');
4
include_once(MODX_BASE_PATH . 'assets/snippets/DocLister/lib/DLCollection.class.php');
5
6
7
/**
8
 * Class MODxAPIhelpers
9
 */
10
class MODxAPIhelpers
11
{
12
    /**
13
     * @param $email
14
     * @param bool $dns
15
     * @return false|string
16
     */
17
    public function emailValidate($email, $dns = true)
18
    {
19
        return \APIhelpers::emailValidate($email, $dns);
20
    }
21
22
    /**
23
     * @param $len
24
     * @param string $data
25
     * @return string
26
     */
27
    public function genPass($len, $data = '')
28
    {
29
        return \APIhelpers::genPass($len, $data);
30
    }
31
32
    /**
33
     * @param string $out
34
     * @return string
35
     */
36
    public function getUserIP($out = '127.0.0.1')
37
    {
38
        return \APIhelpers::getUserIP($out);
39
    }
40
41
    /**
42
     * @param $data
43
     * @return array|mixed|string
44
     */
45
    public function sanitarTag($data)
46
    {
47
        return \APIhelpers::sanitarTag($data);
48
    }
49
50
    /**
51
     * @param $value
52
     * @param int $minLen
53
     * @param array $alph
54
     * @param array $mixArray
55
     * @return bool
56
     */
57
    public function checkString($value, $minLen = 1, $alph = array(), $mixArray = array())
58
    {
59
        return \APIhelpers::checkString($value, $minLen, $alph, $mixArray);
60
    }
61
}
62
63
/**
64
 * Class MODxAPI
65
 */
66
abstract class MODxAPI extends MODxAPIhelpers
67
{
68
    /**
69
     * Объект DocumentParser - основной класс MODX
70
     * @var \DocumentParser
1 ignored issue
show
Bug introduced by
The type DocumentParser was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
71
     * @access protected
72
     */
73
    protected $modx = null;
74
75
    /**
76
     * @var array
77
     */
78
    protected $log = array();
79
80
    /**
81
     * @var array
82
     */
83
    protected $field = array();
84
85
    /**
86
     * @var array
87
     */
88
    protected $default_field = array();
89
90
    /**
91
     * @var null|integer|string
92
     */
93
    protected $id = null;
94
95
    /**
96
     * @var array
97
     */
98
    protected $set = array();
99
100
    /**
101
     * @var bool
102
     */
103
    protected $newDoc = false;
104
105
    /**
106
     * @var string
107
     */
108
    protected $pkName = 'id';
109
110
    /**
111
     * @var string
112
     */
113
    protected $ignoreError = '';
114
115
    /**
116
     * @var bool
117
     */
118
    protected $_debug = false;
119
120
    /**
121
     * @var array
122
     */
123
    protected $_query = array();
124
125
    /**
126
     * @var array
127
     */
128
    protected $jsonFields = array();
129
130
    /**
131
     * @var array
132
     */
133
    protected $store = array();
134
135
    /**
136
     * @var DLCollection
137
     */
138
    protected $_decodedFields;
139
140
    /**
141
     * @var array
142
     */
143
    private $_table = array();
144
145
    /**
146
     * MODxAPI constructor.
147
     * @param DocumentParser $modx
148
     * @param bool $debug
149
     * @throws Exception
150
     */
151
    public function __construct(DocumentParser $modx, $debug = false)
152
    {
153
        $this->modx = $modx;
154
        if (function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc()) {
155
            throw new Exception('Magic Quotes is a deprecated and mostly useless setting that should be disabled. Please ask your server administrator to disable it in php.ini or in your webserver config.');
156
        }
157
158
        $this->setDebug($debug);
159
        $this->_decodedFields = new DLCollection($this->modx);
160
    }
161
162
    /**
163
     * @param boolean $flag
164
     * @return $this
165
     */
166
    public function setDebug($flag)
167
    {
168
        $this->_debug = (bool)$flag;
169
170
        return $this;
171
    }
172
173
    /**
174
     * @return bool
175
     */
176
    public function getDebug()
177
    {
178
        return $this->_debug;
179
    }
180
181
    /**
182
     * @return array
183
     */
184
    public function getDefaultFields()
185
    {
186
        return $this->default_field;
187
    }
188
189
    /**
190
     * @param $value
191
     * @return int|mixed|string
192
     */
193
    protected function getTime($value)
194
    {
195
        $value = trim($value);
196
        if (!empty($value)) {
197
            if (!is_numeric($value)) {
198
                $value = (int)strtotime($value);
199
            }
200
            if (!empty($value)) {
201
                $value += $this->modxConfig('server_offset_time');
202
            }
203
        }
204
205
        return $value;
206
    }
207
208
    /**
209
     * @param string $name
210
     * @param null $default
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $default is correct as it would always require null to be passed?
Loading history...
211
     * @return mixed
212
     */
213
    final public function modxConfig($name, $default = null)
214
    {
215
        return APIHelpers::getkey($this->modx->config, $name, $default);
216
    }
217
218
    /**
219
     * @param $q
220
     * @return $this
221
     */
222
    public function addQuery($q)
223
    {
224
        if (is_scalar($q) && !empty($q)) {
225
            $this->_query[] = $q;
226
        }
227
228
        return $this;
229
    }
230
231
    /**
232
     * @return array
233
     */
234
    public function getQueryList()
235
    {
236
        return $this->_query;
237
    }
238
239
    /**
240
     * @param $SQL
241
     * @return mixed
242
     */
243
    final public function query($SQL)
244
    {
245
        if ($this->getDebug()) {
246
            $this->addQuery($SQL);
247
        }
248
249
        return empty($SQL) ? null : $this->modx->db->query($SQL);
250
    }
251
252
    /**
253
     * @param $value
254
     * @return string|void
255
     */
256
    final public function escape($value)
257
    {
258
        if (!is_scalar($value)) {
259
            $value = '';
260
        } else {
261
            $value = $this->modx->db->escape($value);
262
        }
263
264
        return $value;
265
    }
266
267
    /**
268
     * @param string $name
269
     * @param array $data
270
     * @param bool $flag
271
     * @return $this
272
     */
273
    final public function invokeEvent($name, $data = array(), $flag = false)
274
    {
275
        if ((bool)$flag === true) {
276
            $this->modx->invokeEvent($name, $data);
277
        }
278
279
        return $this;
280
    }
281
282
    /**
283
     * @param string $name
284
     * @param array $data
285
     * @param boolean $flag
286
     * @return array|bool
287
     */
288
    final public function getInvokeEventResult($name, $data = array(), $flag = null)
289
    {
290
        $flag = (isset($flag) && $flag != '') ? (bool)$flag : false;
291
292
        return $flag ? $this->modx->invokeEvent($name, $data) : false;
293
    }
294
295
    /**
296
     * @return $this
297
     */
298
    final public function clearLog()
299
    {
300
        $this->log = array();
301
302
        return $this;
303
    }
304
305
    /**
306
     * @return array
307
     */
308
    final public function getLog()
309
    {
310
        return $this->log;
311
    }
312
313
    /**
314
     * @param bool $flush
315
     * @return $this
316
     */
317
    final public function list_log($flush = false)
318
    {
319
        echo '<pre>' . print_r(APIHelpers::sanitarTag($this->log), true) . '</pre>';
320
        if ($flush) {
321
            $this->clearLog();
322
        }
323
324
        return $this;
325
    }
326
327
    /**
328
     * @param bool $full
329
     * @return string
330
     */
331
    final public function getCachePath($full = true)
332
    {
333
        $path = $this->modx->getCachePath();
334
        if ($full) {
335
            $path = MODX_BASE_PATH . substr($path, strlen(MODX_BASE_URL));
2 ignored issues
show
Bug introduced by
The constant MODX_BASE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant MODX_BASE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
336
        }
337
338
        return $path;
339
    }
340
341
    /**
342
     * @param boolean $fire_events
343
     * @param bool $custom
344
     */
345
    final public function clearCache($fire_events = false, $custom = false)
346
    {
347
        $IDs = array();
348
        if ($custom === false) {
349
            $this->modx->clearCache();
350
            include_once(MODX_MANAGER_PATH . 'processors/cache_sync.class.processor.php');
1 ignored issue
show
Bug introduced by
The constant MODX_MANAGER_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
351
            $sync = new synccache();
0 ignored issues
show
Bug introduced by
The type synccache was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
352
            $path = $this->getCachePath(true);
353
            $sync->setCachepath($path);
354
            $sync->setReport(false);
355
            $sync->emptyCache();
356
        } else {
357
            if (is_scalar($custom)) {
0 ignored issues
show
introduced by
The condition is_scalar($custom) can never be false.
Loading history...
358
                $custom = array($custom);
359
            }
360
            switch ($this->modx->config['cache_type']) {
361
                case 2:
362
                    $cacheFile = "_*.pageCache.php";
363
                    break;
364
                default:
365
                    $cacheFile = ".pageCache.php";
366
            }
367
            if (is_array($custom)) {
0 ignored issues
show
introduced by
The condition is_array($custom) can never be false.
Loading history...
368
                foreach ($custom as $id) {
369
                    $tmp = glob(MODX_BASE_PATH . "assets/cache/docid_" . $id . $cacheFile);
1 ignored issue
show
Bug introduced by
Are you sure $id of type true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

369
                    $tmp = glob(MODX_BASE_PATH . "assets/cache/docid_" . /** @scrutinizer ignore-type */ $id . $cacheFile);
Loading history...
Bug introduced by
The constant MODX_BASE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
370
                    foreach ($tmp as $file) {
371
                        if (is_readable($file)) {
372
                            unlink($file);
373
                        }
374
                        $IDs[] = $id;
375
                    }
376
                }
377
            }
378
            clearstatcache();
379
        }
380
        $this->invokeEvent('OnSiteRefresh', array('IDs' => $IDs), $fire_events);
381
    }
382
383
    /**
384
     * @param integer $id
385
     * @return MODxAPI
386
     */
387
    public function switchObject($id)
388
    {
389
        switch (true) {
390
            //Если загружен другой объект - не тот, с которым мы хотим временно поработать
391
            case ($this->getID() != $id && $id):
392
                $obj = clone $this;
393
                $obj->edit($id);
394
                break;
395
            //Если уже загружен объект, с которым мы хотим временно поработать
396
            case ($this->getID() == $id && $id):
397
                //Если $id не указан, но уже загружен какой-то объект
398
            case (!$id && null !== $this->getID()):
399
            default:
400
                $obj = $this;
401
                break;
402
        }
403
404
        return $obj;
405
    }
406
407
    /**
408
     * @param bool $flag
409
     * @return $this
410
     */
411
    public function useIgnore($flag = true)
412
    {
413
        $this->ignoreError = $flag ? 'IGNORE' : '';
414
415
        return $this;
416
    }
417
418
    /**
419
     * @return bool
420
     */
421
    public function hasIgnore()
422
    {
423
        return (bool)$this->ignoreError;
424
    }
425
426
    /**
427
     * @param $key
428
     * @param $value
429
     * @return $this
430
     */
431
    public function set($key, $value)
432
    {
433
        if ((is_scalar($value) || $this->isJsonField($key)) && is_scalar($key) && !empty($key)) {
434
            $this->field[$key] = $value;
435
        }
436
437
        return $this;
438
    }
439
440
    /**
441
     * @return null|int
442
     */
443
    final public function getID()
444
    {
445
        return $this->id;
446
    }
447
448
    /**
449
     * @param $key
450
     * @return mixed
451
     */
452
    public function get($key)
453
    {
454
        return APIHelpers::getkey($this->field, $key, null);
455
    }
456
457
    /**
458
     * @param $data
459
     * @return $this
460
     */
461
    public function fromArray($data)
462
    {
463
        if (is_array($data)) {
464
            foreach ($data as $key => $value) {
465
                $this->set($key, $value);
466
            }
467
        }
468
469
        return $this;
470
    }
471
472
    /**
473
     * Формирует массив значений для подстановки в SQL запрос на обновление
474
     *
475
     * @param $key
476
     * @param string $id
477
     * @return $this
478
     * @throws Exception
479
     */
480
    final protected function Uset($key, $id = '')
481
    {
482
        if (!isset($this->field[$key])) {
483
            $tmp = "`{$key}`=''";
484
            $this->log[] = "{$key} is empty";
485
        } else {
486
            if ($this->issetField($key) && is_scalar($this->field[$key])) {
487
                $tmp = "`{$key}`='{$this->escape($this->field[$key])}'";
488
            } else {
489
                throw new Exception("{$key} is invalid <pre>" . print_r($this->field[$key], true) . "</pre>");
490
            }
491
        }
492
        if (!empty($tmp) && $this->isChanged($key)) {
493
            if ($id == '') {
494
                $this->set[] = $tmp;
495
            } else {
496
                $this->set[$id][] = $tmp;
497
            }
498
        }
499
500
        return $this;
501
    }
502
503
    /**
504
     * Сохраняет начальные значения полей
505
     *
506
     * @param array $data
507
     * @return $this
508
     */
509
    public function store($data = array()) {
510
        if (is_array($data)) $this->store = $data;
0 ignored issues
show
introduced by
The condition is_array($data) can never be false.
Loading history...
511
512
        return $this;
513
    }
514
515
    /**
516
     * Откатывает изменения отдельного поля или всех полей сразу
517
     *
518
     * @param string $key
519
     * @return MODxAPI
520
     */
521
    public function rollback($key = '') {
522
        if (!empty($key) && isset($this->store[$key])) {
523
            $this->set($key,$this->store[$key]);
524
        } else {
525
            $this->fromArray($this->store);
526
        }
527
528
        return $this;
529
    }
530
531
    /**
532
     * Проверяет изменилось ли поле
533
     *
534
     * @param $key
535
     * @return bool
536
     */
537
    public function isChanged($key) {
538
        $flag = !isset($this->store[$key]) || (isset($this->store[$key]) && $this->store[$key] != $this->field[$key]);
539
540
        return $flag;
541
    }
542
543
    /**
544
     * @param $IDs
545
     * @param string $sep
546
     * @param integer[] $ignore
547
     * @return array
548
     * @throws Exception
549
     */
550
    final public function cleanIDs($IDs, $sep = ',', $ignore = array())
551
    {
552
        $out = array();
553
        if (!is_array($IDs)) {
554
            if (is_scalar($IDs)) {
555
                $IDs = explode($sep, $IDs);
556
            } else {
557
                $IDs = array();
558
                throw new Exception('Invalid IDs list <pre>' . print_r($IDs, 1) . '</pre>');
559
            }
560
        }
561
        foreach ($IDs as $item) {
562
            $item = trim($item);
563
            if (is_scalar($item) && (int)$item >= 0) { //Fix 0xfffffffff
564
                if (!empty($ignore) && in_array((int)$item, $ignore, true)) {
565
                    $this->log[] = 'Ignore id ' . (int)$item;
566
                } else {
567
                    $out[] = (int)$item;
568
                }
569
            }
570
        }
571
        $out = array_unique($out);
572
573
        return $out;
574
    }
575
576
    /**
577
     * @param $data
578
     * @param null $callback
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $callback is correct as it would always require null to be passed?
Loading history...
579
     * @return $this
580
     * @throws Exception
581
     */
582
    final public function fromJson($data, $callback = null)
583
    {
584
        if (is_scalar($data) && !empty($data)) {
585
            $json = json_decode($data);
586
        } else {
587
            throw new Exception("json is not string with json data");
588
        }
589
590
        if ($this->jsonError($json)) {
591
            if (isset($callback) && is_callable($callback)) {
592
                call_user_func_array($callback, array($json));
593
            } else {
594
                if (isset($callback)) {
595
                    throw new Exception("Can't call callback JSON unpack <pre>" . print_r($callback, 1) . "</pre>");
596
                }
597
                foreach ($json as $key => $val) {
598
                    $this->set($key, $val);
599
                }
600
            }
601
        } else {
602
            throw new Exception('Error from JSON decode: <pre>' . print_r($data, 1) . '</pre>');
603
        }
604
605
        return $this;
606
    }
607
608
    /**
609
     * @param null $callback
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $callback is correct as it would always require null to be passed?
Loading history...
610
     * @return string
611
     * @throws Exception
612
     */
613
    final public function toJson($callback = null)
614
    {
615
        $data = $this->toArray();
616
        if (isset($callback) && is_callable($callback)) {
617
            $data = call_user_func_array($callback, array($data));
618
        } else {
619
            if (isset($callback)) {
620
                throw new Exception("Can't call callback JSON pre pack <pre>" . print_r($callback, 1) . "</pre>");
621
            }
622
        }
623
        $json = json_encode($data);
624
625
        if ($this->jsonError($data)) {
626
            throw new Exception('Error from JSON decode: <pre>' . print_r($data, 1) . '</pre>');
627
        }
628
629
        return $json;
630
    }
631
632
    /**
633
     * @param $data
634
     * @return bool
635
     */
636
    final protected function jsonError($data)
637
    {
638
        $flag = false;
639
        if (json_last_error() === JSON_ERROR_NONE && is_object($data) && $data instanceof stdClass) {
640
            $flag = true;
641
        }
642
643
        return $flag;
644
    }
645
646
    /**
647
     * @param string $prefix
648
     * @param string $suffix
649
     * @param string $sep
650
     * @return array
651
     */
652
    public function toArray($prefix = '', $suffix = '', $sep = '_')
653
    {
654
        $tpl = '';
655
        $plh = '[+key+]';
656
        if ($prefix !== '') {
657
            $tpl = $prefix . $sep;
658
        }
659
        $tpl .= $plh;
660
        if ($suffix !== '') {
661
            $tpl .= $sep . $suffix;
662
        }
663
        $out = array();
664
        $fields = $this->field;
665
        $fields[$this->fieldPKName()] = $this->getID();
666
        if ($tpl != $plh) {
667
            foreach ($fields as $key => $value) {
668
                $out[str_replace($plh, $key, $tpl)] = $value;
669
            }
670
        } else {
671
            $out = $fields;
672
        }
673
674
        return $out;
675
    }
676
677
    /**
678
     * @return string
679
     */
680
    final public function fieldPKName()
681
    {
682
        return $this->pkName;
683
    }
684
685
    /**
686
     * @param $table
687
     * @return mixed|string
688
     */
689
    final public function makeTable($table)
690
    {
691
        //Без использования APIHelpers::getkey(). Иначе getFullTableName будет всегда выполняться
692
        return (isset($this->_table[$table])) ? $this->_table[$table] : $this->modx->getFullTableName($table);
693
    }
694
695
    /**
696
     * @param $data
697
     * @param string $sep
698
     * @return array|string
699
     */
700
    final public function sanitarIn($data, $sep = ',')
701
    {
702
        if (!is_array($data)) {
703
            $data = explode($sep, $data);
704
        }
705
        $out = array();
706
        foreach ($data as $item) {
707
            if ($item !== '') {
708
                $out[] = $this->escape($item);
709
            }
710
        }
711
        $out = empty($out) ? '' : "'" . implode("','", $out) . "'";
712
713
        return $out;
714
    }
715
716
    /**
717
     * @param string $table
718
     * @param string $field
719
     * @param string $PK
720
     * @return bool
721
     */
722
    public function checkUnique($table, $field, $PK = 'id')
723
    {
724
        if (is_array($field)) {
0 ignored issues
show
introduced by
The condition is_array($field) can never be true.
Loading history...
725
            $where = array();
726
            foreach ($field as $_field) {
727
                $val = $this->get($_field);
728
                if ($val != '') {
729
                    $where[] = "`" . $this->escape($_field) . "` = '" . $this->escape($val) . "'";
730
                }
731
            }
732
            $where = implode(' AND ', $where);
733
        } else {
734
            $where = '';
735
            $val = $this->get($field);
736
            if ($val != '') {
737
                $where = "`" . $this->escape($field) . "` = '" . $this->escape($val) . "'";
738
            }
739
        }
740
741
        if ($where != '') {
742
            $sql = $this->query("SELECT `" . $this->escape($PK) . "` FROM " . $this->makeTable($table) . " WHERE " . $where);
743
            $id = $this->modx->db->getValue($sql);
744
            if (is_null($id) || (!$this->newDoc && $id == $this->getID())) {
745
                $flag = true;
746
            } else {
747
                $flag = false;
748
            }
749
        } else {
750
            $flag = false;
751
        }
752
753
        return $flag;
754
    }
755
756
    /**
757
     * @param array $data
758
     * @return $this
759
     */
760
    public function create($data = array())
761
    {
762
        $this->close();
763
        $this->fromArray($data);
764
765
        return $this;
766
    }
767
768
    /**
769
     * @param $id
770
     * @return $this
771
     */
772
    public function copy($id)
773
    {
774
        $this->edit($id)->id = 0;
775
        $this->newDoc = true;
776
        $this->store = array();
777
778
        return $this;
779
    }
780
781
    /**
782
     *
783
     */
784
    public function close()
785
    {
786
        $this->newDoc = true;
787
        $this->id = null;
788
        $this->field = array();
789
        $this->set = array();
790
        $this->store = array();
791
        $this->markAllDecode();
792
    }
793
794
    /**
795
     * @param $key
796
     * @return bool
797
     */
798
    public function issetField($key)
799
    {
800
        return (is_scalar($key) && array_key_exists($key, $this->default_field));
801
    }
802
803
    /**
804
     * @param $id
805
     * @return mixed
806
     */
807
    abstract public function edit($id);
808
809
    /**
810
     * @param bool $fire_events
811
     * @param bool $clearCache
812
     * @return mixed
813
     */
814
    abstract public function save($fire_events = false, $clearCache = false);
815
816
    /**
817
     * @param $ids
818
     * @param null $fire_events
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fire_events is correct as it would always require null to be passed?
Loading history...
819
     * @return mixed
820
     */
821
    abstract public function delete($ids, $fire_events = null);
822
823
    /**
824
     * @param $data
825
     * @return array|mixed|string
826
     */
827
    final public function sanitarTag($data)
828
    {
829
        return parent::sanitarTag($this->modx->stripTags($data));
830
    }
831
832
    /**
833
     * @param string $version
834
     * @param bool $dmi3yy
835
     * @return bool
836
     */
837
    final protected function checkVersion($version, $dmi3yy = true)
838
    {
839
        $flag = false;
840
        $currentVer = $this->modx->getVersionData('version');
841
        if (is_array($currentVer)) {
842
            $currentVer = APIHelpers::getkey($currentVer, 'version', '');
843
        }
844
        $tmp = substr($currentVer, 0, strlen($version));
845
        if (version_compare($tmp, $version, '>=')) {
846
            $flag = true;
847
            if ($dmi3yy) {
848
                $flag = (boolean)preg_match('/^' . $tmp . '(.*)\-d/', $currentVer);
849
            }
850
        }
851
852
        return $flag;
853
    }
854
855
    /**
856
     * @param string $name
857
     * @return bool|mixed
858
     */
859
    protected function eraseField($name)
860
    {
861
        $flag = false;
862
        if (array_key_exists($name, $this->field)) {
863
            $flag = $this->field[$name];
864
            unset($this->field[$name]);
865
        }
866
867
        return $flag;
868
    }
869
870
    /**
871
     * Может ли содержать данное поле json массив
872
     * @param  string $field имя поля
873
     * @return boolean
874
     */
875
    public function isJsonField($field)
876
    {
877
        return (is_scalar($field) && in_array($field, $this->jsonFields));
878
    }
879
880
    /**
881
     * Пометить поле как распакованное
882
     * @param  string $field имя поля
883
     * @return $this
884
     */
885
    public function markAsDecode($field)
886
    {
887
        if (is_scalar($field)) {
0 ignored issues
show
introduced by
The condition is_scalar($field) can never be false.
Loading history...
888
            $this->_decodedFields->set($field, false);
889
        }
890
891
        return $this;
892
    }
893
894
    /**
895
     * Пометить поле как запакованное
896
     * @param  string $field имя поля
897
     * @return $this
898
     */
899
    public function markAsEncode($field)
900
    {
901
        if (is_scalar($field)) {
0 ignored issues
show
introduced by
The condition is_scalar($field) can never be false.
Loading history...
902
            $this->_decodedFields->set($field, true);
903
        }
904
905
        return $this;
906
    }
907
908
    /**
909
     * Пометить все поля как запакованные
910
     * @return $this
911
     */
912
    public function markAllEncode()
913
    {
914
        $this->_decodedFields->clear();
915
        foreach ($this->jsonFields as $field) {
916
            $this->markAsEncode($field);
917
        }
918
919
        return $this;
920
    }
921
922
    /**
923
     * Пометить все поля как распакованные
924
     * @return $this
925
     */
926
    public function markAllDecode()
927
    {
928
        $this->_decodedFields->clear();
929
        foreach ($this->jsonFields as $field) {
930
            $this->markAsDecode($field);
931
        }
932
933
        return $this;
934
    }
935
936
    /**
937
     * Получить список не запакованных полей
938
     * @return DLCollection
939
     */
940
    public function getNoEncodeFields()
941
    {
942
        return $this->_decodedFields->filter(function ($value) {
943
            return ($value === false);
944
        });
945
    }
946
947
    /**
948
     * Получить список не распакованных полей
949
     * @return DLCollection
950
     */
951
    public function getNoDecodeFields()
952
    {
953
        return $this->_decodedFields->filter(function ($value) {
954
            return ($value === true);
955
        });
956
    }
957
958
    /**
959
     * Можно ли данное декодировать с помощью json_decode
960
     * @param  string $field имя поля
961
     * @return boolean
962
     */
963
    public function isDecodableField($field)
964
    {
965
        $data = $this->get($field);
966
967
        /**
968
         * Если поле скалярного типа и оно не распаковывалось раньше
969
         */
970
971
        return (is_scalar($data) && is_scalar($field) && $this->_decodedFields->get($field) === true);
972
    }
973
974
    /**
975
     * Можно ли закодировать данные с помощью json_encode
976
     * @param  string $field имя поля
977
     * @return boolean
978
     */
979
    public function isEncodableField($field)
980
    {
981
        /**
982
         * Если поле было распаковано ранее и еще не упаковано
983
         */
984
        return (is_scalar($field) && $this->_decodedFields->get($field) === false);
985
    }
986
987
    /**
988
     * Декодирует конкретное поле
989
     * @param  string $field Имя поля
990
     * @param  bool $store обновить распакованное поле
991
     * @return array ассоциативный массив с данными из json строки
992
     */
993
    public function decodeField($field, $store = false)
994
    {
995
        $out = array();
996
        if ($this->isDecodableField($field)) {
997
            $data = $this->get($field);
998
            $out = jsonHelper::jsonDecode($data, array('assoc' => true), true);
999
        }
1000
        if ($store) {
1001
            $this->field[$field] = $out;
1002
            $this->markAsDecode($field);
1003
        }
1004
1005
        return $out;
1006
    }
1007
1008
    /**
1009
     * Декодирование всех json полей
1010
     * @return $this
1011
     */
1012
    protected function decodeFields()
1013
    {
1014
        foreach ($this->getNoDecodeFields() as $field => $flag) {
1015
            $this->decodeField($field, true);
1016
        }
1017
1018
        return $this;
1019
    }
1020
1021
    /**
1022
     * Запаковывает конкретное поле в JSON
1023
     * @param  string $field Имя поля
1024
     * @param  bool $store обновить запакованное поле
1025
     * @return string|null json строка
1026
     */
1027
    public function encodeField($field, $store = false)
1028
    {
1029
        $out = null;
1030
        if ($this->isEncodableField($field)) {
1031
            $data = $this->get($field);
1032
            $out = json_encode($data);
1033
        }
1034
        if ($store) {
1035
            $this->field[$field] = $out;
1036
            $this->markAsEncode($field);
1037
        }
1038
1039
        return $out;
1040
    }
1041
1042
    /**
1043
     * Запаковка всех json полей
1044
     * @return $this
1045
     */
1046
    protected function encodeFields()
1047
    {
1048
        foreach ($this->getNoEncodeFields() as $field => $flag) {
1049
            $this->encodeField($field, true);
1050
        }
1051
1052
        return $this;
1053
    }
1054
}
1055