-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecretObject.php
More file actions
1365 lines (1287 loc) · 47.8 KB
/
SecretObject.php
File metadata and controls
1365 lines (1287 loc) · 47.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace MagicObject;
use MagicObject\Exceptions\InvalidAnnotationException;
use MagicObject\Util\PicoEnvironmentVariable;
use MagicObject\Secret\PicoSecret;
use MagicObject\Util\ClassUtil\PicoAnnotationParser;
use MagicObject\Util\ClassUtil\PicoSecretParser;
use MagicObject\Util\PicoArrayUtil;
use MagicObject\Util\PicoGenericObject;
use MagicObject\Util\PicoIniUtil;
use MagicObject\Util\PicoStringUtil;
use MagicObject\Util\PicoYamlUtil;
use MagicObject\Util\ValidationUtil;
use ReflectionClass;
use stdClass;
/**
* SecretObject class
*
* This class provides mechanisms to manage properties that require encryption
* and decryption during their lifecycle. It uses annotations to specify which
* properties should be encrypted or decrypted when they are set or retrieved.
* These annotations help identify when to apply encryption or decryption,
* either before saving (SET) or before fetching (GET).
*
* The class supports flexibility in data initialization, allowing data to be
* passed as an array, an object, or even left empty. Additionally, a secure
* callback function can be provided to handle key generation for encryption
* and decryption operations.
*
* Key features:
* - Encryption and decryption of object properties based on annotations.
* - Support for customizing property naming strategies.
* - Option to provide a secure function for key generation.
*
* @author Kamshory
* @package MagicObject
* @link https://github.com/Planetbiru/MagicObject
*/
class SecretObject extends stdClass // NOSONAR
{
const JSON = 'JSON';
const YAML = 'Yaml';
const PROPERTY_NAMING_STRATEGY = "property-naming-strategy";
const PROPERTY_NAMING_STRATEGY_CAMEL = "propertyNamingStrategy";
const KEY_NAME = "name";
const KEY_VALUE = "value";
const KEY_PROPERTY_TYPE = "propertyType";
const KEY_DEFAULT_VALUE = "defaultValue";
const ANNOTATION_ENCRYPT_IN = "EncryptIn";
const ANNOTATION_DECRYPT_IN = "DecryptIn";
const ANNOTATION_ENCRYPT_OUT = "EncryptOut";
const ANNOTATION_DECRYPT_OUT = "DecryptOut";
const SNAKE_CASE = 'SNAKE_CASE';
const UPPER_CAMEL_CASE = 'UPPER_CAMEL_CASE';
/**
* List of properties to be encrypted when calling SET.
*
* The property name starts with an underscore to prevent child classes
* from overriding its value.
*
* @var string[]
*/
private $_encryptInProperties = array(); // NOSONAR
/**
* Class parameters.
*
* The property name starts with an underscore to prevent child classes
* from overriding its value.
*
* @var array
*/
protected $_classParams = array(); // NOSONAR
/**
* NULL properties.
*
* The property name starts with an underscore to prevent child classes
* from overriding its value.
*
* @var array
*/
protected $_nullProperties = array(); // NOSONAR
/**
* List of properties to be decrypted when calling GET.
*
* The property name starts with an underscore to prevent child classes
* from overriding its value.
*
* @var string[]
*/
private $_decryptOutProperties = array(); // NOSONAR
/**
* List of properties to be encrypted when calling GET.
*
* The property name starts with an underscore to prevent child classes
* from overriding its value.
*
* @var string[]
*/
private $_encryptOutProperties = array(); // NOSONAR
/**
* List of properties to be decrypted when calling SET.
*
* The property name starts with an underscore to prevent child classes
* from overriding its value.
*
* @var string[]
*/
private $_decryptInProperties = array(); // NOSONAR
/**
* Indicates if the object is read-only.
*
* The property name starts with an underscore to prevent child classes
* from overriding its value.
*
* @var bool
*/
private $_readonly = false; // NOSONAR
/**
* Secure function to get encryption key.
*
* The property name starts with an underscore to prevent child classes
* from overriding its value.
*
* @var callable
*/
private $_secureFunction = null; // NOSONAR
/**
* Constructor for initializing the object with data.
*
* This constructor accepts initial data in various formats (array or object) and
* allows the optional specification of a callback function for secure key generation.
* The data is processed and loaded into the object upon instantiation.
*
* @param self|array|object|null $data The initial data for the object. Can be an
* associative array, an object, or null.
* @param callable|null $secureCallback An optional callback function for generating
* secure keys. If provided, it must be callable.
*/
public function __construct($data = null, $secureCallback = null)
{
$this->_objectInfo();
// set callback secure before load default data
if($secureCallback != null && is_callable($secureCallback))
{
$this->_secureFunction = $secureCallback;
}
if($data != null)
{
if(is_array($data))
{
$data = PicoArrayUtil::camelize($data);
}
$this->loadData($data);
}
}
/**
* Analyzes the class's parameters and properties to determine which should be
* encrypted or decrypted based on annotations.
*
* This method uses reflection to retrieve the class's parameters and properties.
* It then parses annotations associated with these members to identify which
* properties should undergo encryption or decryption during specific stages
* (before storage or before retrieval). The appropriate lists of properties
* are populated accordingly.
*
* @return void
*
* @throws InvalidAnnotationException If the annotations are invalid or cannot be parsed.
*/
private function _objectInfo()
{
$className = get_class($this);
$reflexClass = new PicoAnnotationParser($className);
$params = $reflexClass->getParameters();
$props = $reflexClass->getProperties();
// Process each class parameter
foreach ($params as $paramName => $paramValue) {
try {
$vals = $reflexClass->parseKeyValue($paramValue);
$this->_classParams[$paramName] = $vals;
} catch (InvalidAnnotationException $e) {
throw new InvalidAnnotationException("Invalid annotation @" . $paramName);
}
}
// Process each class property
foreach ($props as $prop) {
$reflexProp = new PicoAnnotationParser($className, $prop->name, 'property');
$parameters = $reflexProp->getParameters();
// Check each property for encryption/decryption annotations
foreach ($parameters as $param => $val) {
if (strcasecmp($param, self::ANNOTATION_ENCRYPT_IN) == 0) {
// Property should be encrypted before storing
$this->_encryptInProperties[] = $prop->name;
} else if (strcasecmp($param, self::ANNOTATION_DECRYPT_OUT) == 0) {
// Property should be decrypted before retrieval
$this->_decryptOutProperties[] = $prop->name;
} else if (strcasecmp($param, self::ANNOTATION_ENCRYPT_OUT) == 0) {
// Property should be encrypted before retrieval
$this->_encryptOutProperties[] = $prop->name;
} else if (strcasecmp($param, self::ANNOTATION_DECRYPT_IN) == 0) {
// Property should be decrypted before storing
$this->_decryptInProperties[] = $prop->name;
}
}
}
}
/**
* Generates a secure key for encryption and decryption.
*
* This method checks for a user-defined secure key generation function. If a valid
* function is provided, it calls that function to generate the key. Otherwise, it
* returns a concatenation of predefined random keys.
*
* @return string The secure key for encryption/decryption.
*/
private function secureKey()
{
if($this->_secureFunction != null && is_callable($this->_secureFunction))
{
return call_user_func($this->_secureFunction);
}
else
{
return PicoSecret::RANDOM_KEY_1.PicoSecret::RANDOM_KEY_2;
}
}
/**
* Magic method called when invoking undefined methods.
*
* This method handles dynamic method calls for property management.
*
* Supported methods:
*
* - `isset<PropertyName>`: Checks if the property is set.
* - Example: `$obj->issetFoo()` returns true if property `foo` is set.
*
* - `is<PropertyName>`: Checks if the property is set and equals 1 (truthy).
* - Example: `$obj->isFoo()` returns true if property `foo` is set and is equal to 1.
*
* - `get<PropertyName>`: Retrieves the value of the property.
* - Example: `$value = $obj->getFoo()` gets the value of property `foo`.
*
* - `set<PropertyName>`: Sets the value of the property.
* - Example: `$obj->setFoo($value)` sets the property `foo` to `$value`.
*
* - `unset<PropertyName>`: Unsets the property.
* - Example: `$obj->unsetFoo()` removes the property `foo`.
*
* - `push<PropertyName>`: Pushes a value onto an array property.
* - Example: `$obj->pushFoo($value)` adds `$value` to the array property `foo`.
*
* - `pop<PropertyName>`: Pops a value from an array property.
* - Example: `$value = $obj->popFoo()` removes and returns the last value from the array property `foo`.
*
* @param string $method Method name.
* @param array $params Parameters for the method.
* @return mixed|null The result of the method call or null if not applicable.
*/
public function __call($method, $params) // NOSONAR
{
if (strncasecmp($method, "isset", 5) === 0) {
$var = PicoStringUtil::camelize(substr($method, 5));
return isset($this->{$var});
}
else if (strncasecmp($method, "is", 2) === 0) {
$var = PicoStringUtil::camelize(substr($method, 2));
return isset($this->{$var}) ? $this->{$var} == 1 : false;
} else if (strncasecmp($method, "get", 3) === 0) {
$var = PicoStringUtil::camelize(substr($method, 3));
return $this->_get($var);
}
else if (strncasecmp($method, "set", 3) === 0 && isset($params) && is_array($params) && !empty($params) && !$this->_readonly) {
$var = PicoStringUtil::camelize(substr($method, 3));
$this->_set($var, $params[0]);
$this->modifyNullProperties($var, $params[0]);
return $this;
}
else if (strncasecmp($method, "unset", 5) === 0) {
$var = PicoStringUtil::camelize(substr($method, 5));
unset($this->{$var});
return $this;
}
else if (strncasecmp($method, "push", 4) === 0 && isset($params) && is_array($params) && !$this->_readonly) {
$var = PicoStringUtil::camelize(substr($method, 4));
if(!isset($this->{$var}))
{
$this->{$var} = array();
}
if(is_array($this->{$var}))
{
array_push($this->{$var}, isset($params) && is_array($params) && isset($params[0]) ? $params[0] : null);
}
return $this;
}
else if (strncasecmp($method, "pop", 3) === 0) {
$var = PicoStringUtil::camelize(substr($method, 3));
if(isset($this->{$var}) && is_array($this->{$var}))
{
return array_pop($this->{$var});
}
return null;
}
}
/**
* Set a value for the specified property.
*
* This method sets the value of a property and applies encryption or decryption
* if necessary based on the defined property rules.
*
* @param string $var The name of the property.
* @param mixed $value The value to set.
* @return self Returns the current instance for method chaining.
*/
private function _set($var, $value)
{
if($this->needInputEncryption($var))
{
$value = $this->encryptValue($value, $this->secureKey());
}
else if($this->needInputDecryption($var))
{
$value = $this->decryptValue($value, $this->secureKey());
}
$this->{$var} = $value;
return $this;
}
/**
* Get the value of the specified property.
*
* This method retrieves the value of a property and applies encryption or decryption
* if necessary based on the defined property rules.
*
* @param string $var The name of the property.
* @return mixed The value of the property.
*/
private function _get($var)
{
$value = $this->_getValue($var);
if($this->needOutputEncryption($var))
{
$value = $this->encryptValue($value, $this->secureKey());
}
else if($this->needOutputDecryption($var))
{
$value = $this->decryptValue($value, $this->secureKey());
}
return $value;
}
/**
* Get the raw value of the specified property.
*
* This method retrieves the raw value of a property without any encryption or decryption.
*
* @param string $var The name of the property.
* @return mixed The raw value of the property, or null if not set.
*/
private function _getValue($var)
{
return isset($this->{$var}) ? $this->{$var} : null;
}
/**
* Check if the given data is an instance of MagicObject or PicoGenericObject.
*
* @param mixed $data The data to check.
* @return bool true if the data is an instance, otherwise false.
*/
private function typeObject($data)
{
if($data instanceof MagicObject || $data instanceof PicoGenericObject)
{
return true;
}
return false;
}
/**
* Check if the given data is an instance of self or stdClass.
*
* @param mixed $data The data to check.
* @return bool true if the data is an instance, otherwise false.
*/
private function typeStdClass($data)
{
if($data instanceof self || $data instanceof stdClass)
{
return true;
}
return false;
}
/**
* Encrypt data recursively.
*
* This method encrypts the provided data, which can be an object, array, or scalar value.
* It handles nested structures by encrypting each value individually.
*
* @param MagicObject|PicoGenericObject|self|array|stdClass|string|number $data The data to encrypt.
* @param string|null $hexKey The encryption key in hexadecimal format. If null, a secure key will be generated.
* @return mixed The encrypted data.
*/
public function encryptValue($data, $hexKey = null)
{
if($hexKey == null)
{
$hexKey = $this->secureKey();
}
if($this->typeObject($data))
{
$values = $data->value();
foreach($values as $key=>$value)
{
$data->set($key, $this->encryptValue($value, $hexKey));
}
}
else if($this->typeStdClass($data))
{
foreach($data as $key=>$value)
{
$data->{$key} = $this->encryptValue($value, $hexKey);
}
}
else if(is_array($data))
{
foreach($data as $key=>$value)
{
$data[$key] = $this->encryptValue($value, $hexKey);
}
}
else
{
$data = (string) $data;
return $this->encryptString($data, $hexKey);
}
return $data;
}
/**
* Encrypt a string.
*
* This method encrypts a plain text string using a specified or generated secure key.
*
* @param string $plaintext The plain text to be encrypted.
* @param string|null $hexKey The key in hexadecimal format. If null, a secure key will be generated.
* @return string The encrypted string in base64 format.
*/
public function encryptString($plaintext, $hexKey = null)
{
if($hexKey == null)
{
$hexKey = $this->secureKey();
}
$key = $hexKey;
$method = "AES-256-CBC";
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
$hash = hash_hmac('sha256', $ciphertext . $iv, $key, true);
return base64_encode($iv . $hash . $ciphertext);
}
/**
* Decrypt data recursively.
*
* This method decrypts the provided ciphertext, which can be an object, array, or scalar value.
* It handles nested structures by decrypting each value individually.
*
* @param MagicObject|PicoGenericObject|self|array|stdClass|string $data The ciphertext to decrypt.
* @param string|null $hexKey The key in hexadecimal format. If null, a secure key will be generated.
* @return string|null The decrypted string or null if decryption fails.
*/
public function decryptValue($data, $hexKey = null)
{
if($hexKey == null)
{
$hexKey = $this->secureKey();
}
if($this->typeObject($data))
{
$values = $data->value();
foreach($values as $key=>$value)
{
$data->set($key, $this->decryptValue($value, $hexKey));
}
}
else if($this->typeStdClass($data))
{
foreach($data as $key=>$value)
{
$data->{$key} = $this->decryptValue($value, $hexKey);
}
}
else if(is_array($data))
{
foreach($data as $key=>$value)
{
$data[$key] = $this->decryptValue($value, $hexKey);
}
}
else
{
$data = (string) $data;
return $this->decryptString($data, $hexKey);
}
return $data;
}
/**
* Decrypt a string.
*
* This method decrypts a given ciphertext string using a specified or generated secure key.
*
* @param string $ciphertext The encrypted data to be decrypted.
* @param string|null $hexKey The key in hexadecimal format. If null, a secure key will be generated.
* @return string|null The decrypted string or null if decryption fails.
*/
public function decryptString($ciphertext, $hexKey = null)
{
if($hexKey == null)
{
$hexKey = $this->secureKey();
}
if(!isset($ciphertext) || empty($ciphertext))
{
return null;
}
$ivHashCiphertext = base64_decode($ciphertext);
$key = $hexKey;
$method = "AES-256-CBC";
$iv = substr($ivHashCiphertext, 0, 16);
$hash = substr($ivHashCiphertext, 16, 32);
$ciphertext = substr($ivHashCiphertext, 48);
if (!$hash || !hash_equals(hash_hmac('sha256', $ciphertext . $iv, $key, true), $hash))
{
return null;
}
return openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
}
/**
* Check if a value requires encryption before being stored.
*
* @param string $var The variable name.
* @return bool true if the value needs to be encrypted, otherwise false.
*/
private function needInputEncryption($var)
{
return in_array($var, $this->_encryptInProperties);
}
/**
* Check if a value requires decryption after being read.
*
* @param string $var The variable name.
* @return bool true if the value needs to be decrypted, otherwise false.
*/
private function needOutputDecryption($var)
{
return in_array($var, $this->_decryptOutProperties);
}
/**
* Check if a value requires encryption after being read.
*
* @param string $var The variable name.
* @return bool true if the value needs to be encrypted, otherwise false.
*/
private function needOutputEncryption($var)
{
return in_array($var, $this->_encryptOutProperties);
}
/**
* Check if a value requires decryption before being stored.
*
* @param string $var The variable name.
* @return bool true if the value needs to be decrypted, otherwise false.
*/
private function needInputDecryption($var)
{
return in_array($var, $this->_decryptInProperties);
}
/**
* Load data into the object.
*
* This method populates the object's properties from the provided data, which can be an object,
* array, or scalar value.
*
* @param mixed $data The data to load.
* @return self Returns the current instance for method chaining.
*/
public function loadData($data)
{
if($data != null)
{
if($data instanceof self || $data instanceof MagicObject || $data instanceof PicoGenericObject)
{
$values = $data->value();
foreach ($values as $key => $value) {
$key2 = PicoStringUtil::camelize($key);
$this->_set($key2, $value);
}
}
else if (is_array($data) || is_object($data)) {
foreach ($data as $key => $value) {
$key2 = PicoStringUtil::camelize($key);
$this->_set($key2, $value);
}
}
}
return $this;
}
/**
* Load data from an INI string.
*
* This method parses an INI formatted string and loads the data into the object.
*
* @param string $rawData The raw INI data as a string.
* @param bool $systemEnv Flag to indicate whether to use environment variable replacement.
* @return self Returns the current instance for method chaining.
*/
public function loadIniString($rawData, $systemEnv = false)
{
// Parse without sections
$data = PicoIniUtil::parseIniString($rawData);
if(isset($data) && !empty($data))
{
$data = PicoEnvironmentVariable::replaceValueAll($data, $data, true);
if($systemEnv)
{
$data = PicoEnvironmentVariable::replaceSysEnvAll($data, true);
}
$data = PicoArrayUtil::camelize($data);
$this->loadData($data);
}
return $this;
}
/**
* Load data from an INI file.
*
* This method reads an INI file and loads the data into the object.
*
* @param string $path The path to the INI file.
* @param bool $systemEnv Flag to indicate whether to use environment variable replacement.
* @return self Returns the current instance for method chaining.
*/
public function loadIniFile($path, $systemEnv = false)
{
// Parse without sections
$data = PicoIniUtil::parseIniFile($path);
if(isset($data) && !empty($data))
{
$data = PicoEnvironmentVariable::replaceValueAll($data, $data, true);
if($systemEnv)
{
$data = PicoEnvironmentVariable::replaceSysEnvAll($data, true);
}
$data = PicoArrayUtil::camelize($data);
$this->loadData($data);
}
return $this;
}
/**
* Load data from a YAML string.
*
* This method parses a YAML formatted string and loads the data into the object.
*
* @param string $rawData The YAML data as a string.
* @param bool $systemEnv Flag to indicate whether to replace environment variables.
* @param bool $asObject Flag to indicate whether to return results as an object.
* @param bool $recursive Flag to indicate whether to convert nested objects to MagicObject.
* @return self Returns the current instance for method chaining.
*/
public function loadYamlString($rawData, $systemEnv = false, $asObject = false, $recursive = false)
{
$data = PicoYamlUtil::parse($rawData);
if(isset($data) && !empty($data))
{
$data = PicoEnvironmentVariable::replaceValueAll($data, $data, true);
if($systemEnv)
{
$data = PicoEnvironmentVariable::replaceSysEnvAll($data, true);
}
$data = PicoArrayUtil::camelize($data);
if($recursive)
{
$this->loadData(PicoSecretParser::parseRecursiveObject($data));
}
else
{
$this->loadData($data);
}
}
return $this;
}
/**
* Load data from a YAML file.
*
* This method reads a YAML file and loads the data into the object.
*
* @param string $path The path to the YAML file.
* @param bool $systemEnv Flag to indicate whether to replace environment variables.
* @param bool $asObject Flag to indicate whether to return results as an object.
* @param bool $recursive Flag to indicate whether to convert nested objects to MagicObject.
* @return self Returns the current instance for method chaining.
*/
public function loadYamlFile($path, $systemEnv = false, $asObject = false, $recursive = false)
{
$data = PicoYamlUtil::parseFile($path);
if(isset($data) && !empty($data))
{
$data = PicoEnvironmentVariable::replaceValueAll($data, $data, true);
if($systemEnv)
{
$data = PicoEnvironmentVariable::replaceSysEnvAll($data, true);
}
$data = PicoArrayUtil::camelize($data);
if($recursive)
{
$this->loadData(PicoSecretParser::parseRecursiveObject($data));
}
else
{
$this->loadData($data);
}
}
return $this;
}
/**
* Load data from a JSON string.
*
* This method parses a JSON formatted string and loads the data into the object.
*
* @param string $rawData The JSON data as a string.
* @param bool $systemEnv Flag to indicate whether to replace environment variables.
* @param bool $recursive Flag to create recursive object.
* @return self Returns the current instance for method chaining.
*/
public function loadJsonString($rawData, $systemEnv = false, $asObject = false, $recursive = false)
{
$data = json_decode($rawData);
if(isset($data) && !empty($data))
{
$data = PicoEnvironmentVariable::replaceValueAll($data, $data, true);
if($systemEnv)
{
$data = PicoEnvironmentVariable::replaceSysEnvAll($data, true);
}
$data = PicoArrayUtil::camelize($data);
if($recursive)
{
$this->loadData(PicoSecretParser::parseRecursiveObject($data));
}
else
{
$this->loadData($data);
}
}
return $this;
}
/**
* Load data from a JSON file.
*
* This method reads a JSON file and loads the data into the object.
*
* @param string $path The path to the JSON file.
* @param bool $systemEnv Flag to indicate whether to replace environment variables.
* @param bool $recursive Flag to create recursive object.
* @return self Returns the current instance for method chaining.
*/
public function loadJsonFile($path, $systemEnv = false, $asObject = false, $recursive = false)
{
$data = json_decode(file_get_contents($path));
if(isset($data) && !empty($data))
{
$data = PicoEnvironmentVariable::replaceValueAll($data, $data, true);
if($systemEnv)
{
$data = PicoEnvironmentVariable::replaceSysEnvAll($data, true);
}
$data = PicoArrayUtil::camelize($data);
if($recursive)
{
$this->loadData(PicoSecretParser::parseRecursiveObject($data));
}
else
{
$this->loadData($data);
}
}
return $this;
}
/**
* Set the object to read-only mode.
*
* When in read-only mode, setters will not change the value of the object's properties,
* but the loadData method will still work.
*
* @param bool $readonly Flag to set the object to read-only.
* @return self Returns the current instance for method chaining.
*/
protected function readOnly($readonly)
{
$this->_readonly = $readonly;
return $this;
}
/**
* Set a property value.
*
* @param string $propertyName The name of the property to set.
* @param mixed|null $propertyValue The value to set for the property.
* @return self Returns the current instance for method chaining.
*/
public function set($propertyName, $propertyValue)
{
return $this->_set($propertyName, $propertyValue);
}
/**
* Add an element to a property array.
*
* @param string $propertyName The name of the property.
* @param mixed $propertyValue The value to add.
* @return self Returns the current instance for method chaining.
*/
public function push($propertyName, $propertyValue)
{
$var = PicoStringUtil::camelize($propertyName);
if(!isset($this->{$var}))
{
$this->{$var} = array();
}
array_push($this->{$var}, $propertyValue);
return $this;
}
/**
* Remove the last element from a property array.
*
* @param string $propertyName The name of the property.
* @return mixed|null The removed value or null if the property is not an array.
*/
public function pop($propertyName)
{
$var = PicoStringUtil::camelize($propertyName);
if(isset($this->{$var}) && is_array($this->{$var}))
{
return array_pop($this->{$var});
}
return null;
}
/**
* Get a property value.
*
* @param string $propertyName The name of the property.
* @return mixed|null The value of the property or null if not set.
*/
public function get($propertyName)
{
return $this->_get($propertyName);
}
/**
* Get a property value or return a default value if not set.
*
* @param string $propertyName The name of the property.
* @param mixed|null $defaultValue The default value to return if the property is not set.
* @return mixed The property value or the default value.
*/
public function getOrDefault($propertyName, $defaultValue = null)
{
$var = PicoStringUtil::camelize($propertyName);
return isset($this->{$var}) ? $this->{$var} : $defaultValue;
}
/**
* Copies values from another object to the current object based on specified filters.
*
* This method allows selective copying of property values from a source object to the
* current object. You can specify which properties to copy using a filter, and you can
* choose whether to include properties with null values.
*
* @param self|mixed $source The source object from which to copy values.
* @param array|null $filter An optional array of property names to filter which values
* should be copied. If null, all properties will be considered.
* @param bool $includeNull A flag indicating whether to include properties with null
* values. Defaults to false, meaning null values will be excluded.
* @return self Returns the current instance for method chaining.
*/
public function copyValueFrom($source, $filter = null, $includeNull = false)
{
if($filter != null)
{
$tmp = array();
$index = 0;
foreach($filter as $val)
{
$tmp[$index] = trim(PicoStringUtil::camelize($val));
$index++;
}
$filter = $tmp;
}
$values = $source->value();
foreach($values as $property=>$value)
{
if(
($filter == null || (is_array($filter) && !empty($filter) && in_array($property, $filter)))
&&
($includeNull || $value != null)
)
{
$this->set($property, $value);
}
}
return $this;
}
/**
* Get object value.
*
* This method retrieves the values of the object's properties, optionally converting
* the property names to snake case.
*
* @param bool $snakeCase Flag to convert property names to snake case.
* @return stdClass An object containing the values of the properties.
*/
public function value($snakeCase = false)
{
$parentProps = $this->propertyList(true, true);
$value = new stdClass;
foreach ($this as $key => $val) {
if(!in_array($key, $parentProps))
{
// get decripted or encrypted value
$value->{$key} = $this->_get($key);
}
}
if($snakeCase)
{
$value2 = new stdClass;
foreach ($value as $key => $val) {
$key2 = PicoStringUtil::snakeize($key);
// get decripted or encrypted value
$value2->{$key2} = PicoStringUtil::snakeizeObject($val);
}
return $value2;
}
return $value;
}
/**
* Get object value as an object.
*
* This method is an alias for the value() method, allowing for retrieval of
* object values, optionally in snake case.
*
* @param bool $snakeCase Flag to convert property names to snake case.
* @return stdClass An object containing the values of the properties.
*/
public function valueObject($snakeCase = false)
{
return $this->value($snakeCase);
}
/**