-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathNormalizer.php
121 lines (106 loc) · 2.88 KB
/
Normalizer.php
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
<?php
namespace Stidges\LaravelDbNormalizer;
class Normalizer implements NormalizerInterface
{
/**
* Normalize the given array to a collection / entity.
*
* @param array $data
* @return \Stidges\LaravelDbNormalizer\Collection|\Stidges\LaravelDbNormalizer\Entity
*/
public function normalize(array $data)
{
if ($this->isAssociative($data)) {
return $this->normalizeEntity($data);
}
return $this->normalizeCollection($data);
}
/**
* Determine whether the given array is associative or not.
*
* @param array $array
* @return bool
*/
protected function isAssociative(array $array)
{
return (bool) count(array_filter(array_keys($array), 'is_string'));
}
/**
* Normalize the given array to an Entity.
*
* @param array $entity
* @return \Stidges\LaravelDbNormalizer\Entity
*/
protected function normalizeEntity(array $entity)
{
$normalized = [];
foreach ($entity as $attribute => $value)
{
if ($this->isCollection($value))
{
$value = $this->normalizeCollection($value);
}
elseif ($this->isEntity($value))
{
$value = $this->normalizeEntity($value);
}
$normalized[$attribute] = $value;
}
return $this->newEntity($normalized);
}
/**
* Normalize the given array to a Collection.
*
* @param array $collection
* @return \Stidges\LaravelDbNormalizer\Collection
*/
protected function normalizeCollection(array $collection)
{
$normalized = [];
foreach ($collection as $entity)
{
$normalized[] = $this->normalizeEntity($entity);
}
return $this->newCollection($normalized);
}
/**
* Determine whether the given value should be cast to an Entity.
*
* @param mixed $value
* @return bool
*/
protected function isEntity($value)
{
return is_array($value) && $this->isAssociative($value);
}
/**
* Determine whether the given value should be cast to a Collection.
*
* @param mixed $value
* @return bool
*/
protected function isCollection($value)
{
return is_array($value) && ! $this->isAssociative($value);
}
/**
* Get a new Collection instance.
*
* @param array $entities
* @return \Stidges\LaravelDbNormalizer\Collection
*/
protected function newCollection(array $entities = array())
{
return new Collection($entities);
}
/**
* Get a new Entity instance.
*
* @param array $attributes
* @return \Stidges\LaravelDbNormalizer\Entity
*/
protected function newEntity(array $attributes = array())
{
return new Entity($attributes);
}
}