Completed
Push — master ( d88b49...82b4a5 )
by
unknown
02:25
created

MODxAPI::getTime()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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