|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* KNUT7 K7F (https://marciozebedeu.com/) |
|
4
|
|
|
* KNUT7 K7F (tm) : Rapid Development Framework (https://marciozebedeu.com/) |
|
5
|
|
|
* |
|
6
|
|
|
* Licensed under The MIT License |
|
7
|
|
|
* For full copyright and license information, please see the LICENSE.txt |
|
8
|
|
|
* Redistributions of files must retain the above copyright notice. |
|
9
|
|
|
* |
|
10
|
|
|
* @link https://github.com/knut7/framework/ for the canonical source repository |
|
11
|
|
|
* @copyright (c) 2015. KNUT7 Software Technologies AO Inc. (https://marciozebedeu.com/) |
|
12
|
|
|
* @license https://marciozebedeu.com/license/new-bsd New BSD License |
|
13
|
|
|
* @author Marcio Zebedeu - [email protected] |
|
14
|
|
|
* @version 1.0.2 |
|
15
|
|
|
*/ |
|
16
|
|
|
|
|
17
|
|
|
namespace Ballybran\Helpers\Stdlib; |
|
18
|
|
|
|
|
19
|
|
|
class HydratorConverter |
|
20
|
|
|
{ |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Convert an array to object |
|
24
|
|
|
* @param array $array |
|
25
|
|
|
* @return object |
|
26
|
|
|
*/ |
|
27
|
|
|
|
|
28
|
|
|
|
|
29
|
|
|
public static function toObject(array $array, $object): object |
|
30
|
|
|
{ |
|
31
|
|
|
$class = get_class($object); |
|
32
|
|
|
$methods = get_class_methods($class); |
|
33
|
|
|
|
|
34
|
|
|
foreach ($methods as $method) { |
|
35
|
|
|
preg_match(' /^(set)(.*?)$/i', $method, $results); |
|
36
|
|
|
|
|
37
|
|
|
$pre = $results[1] ?? ''; |
|
38
|
|
|
$k = $results[2] ?? ''; |
|
39
|
|
|
$k = strtolower(substr($k, 0, 1)) . substr($k, 1); |
|
40
|
|
|
|
|
41
|
|
|
if ($pre == 'set' && !empty($array[$k])) { |
|
42
|
|
|
$object->$method($array[$k]); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
return $object; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* Extract values from an object |
|
50
|
|
|
* converting the object to an associative array |
|
51
|
|
|
* @param object $object |
|
52
|
|
|
* @return array |
|
53
|
|
|
*/ |
|
54
|
|
|
public static function toArray($object): array |
|
55
|
|
|
{ |
|
56
|
|
|
$array = array(); |
|
57
|
|
|
$class = get_class($object); |
|
58
|
|
|
$methods = get_class_methods($class); |
|
59
|
|
|
|
|
60
|
|
|
foreach ($methods as $method) { |
|
61
|
|
|
|
|
62
|
|
|
preg_match(' /^(get)(.*?)$/i', $method, $results); |
|
63
|
|
|
|
|
64
|
|
|
$pre = $results[1] ?? ''; |
|
65
|
|
|
$k = $results[2] ?? ''; |
|
66
|
|
|
$k = strtolower(substr($k, 0, 1)) . substr($k, 1); |
|
67
|
|
|
|
|
68
|
|
|
if ($pre == 'get') { |
|
69
|
|
|
$array[$k] = $object->$method(); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
return array_filter($array); |
|
73
|
|
|
} |
|
74
|
|
|
} |