1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Modules\Entitizer\Utils { |
4
|
|
|
|
5
|
|
|
use Modules\Entitizer, Config; |
6
|
|
|
|
7
|
|
|
abstract class Collection { |
8
|
|
|
|
9
|
|
|
protected $definition = null, $config = null; |
10
|
|
|
|
11
|
|
|
# Cast order set to be suitable with entity definition |
12
|
|
|
|
13
|
|
|
private function castOrderBy(array $data) { |
14
|
|
|
|
15
|
|
|
$order_by = []; |
16
|
|
|
|
17
|
|
|
foreach ($data as $field => $direction) { |
18
|
|
|
|
19
|
|
|
if (false === ($param = $this->definition->param($field))) continue; |
20
|
|
|
|
21
|
|
|
$order_by[$param->name] = ((strtoupper($direction) !== 'DESC') ? 'ASC' : 'DESC'); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
# ------------------------ |
25
|
|
|
|
26
|
|
|
return (([] !== $order_by) ? $order_by : static::$order_by); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
# Get selection |
30
|
|
|
|
31
|
|
|
protected function getSelection() { |
32
|
|
|
|
33
|
|
|
$selection = []; |
34
|
|
|
|
35
|
|
|
foreach ($this->definition->paramsSecure() as $field) $selection[] = ('ent.' . $field); |
36
|
|
|
|
37
|
|
|
# ------------------------ |
38
|
|
|
|
39
|
|
|
return implode(', ', $selection); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
# Get order by |
43
|
|
|
|
44
|
|
|
protected function getOrderBy(array $data) { |
45
|
|
|
|
46
|
|
|
$order_by = []; |
47
|
|
|
|
48
|
|
|
foreach ($this->castOrderBy($data) as $field => $direction) $order_by[] = ('ent.' . $field . ' ' . $direction); |
49
|
|
|
|
50
|
|
|
# ------------------------ |
51
|
|
|
|
52
|
|
|
return implode(', ', $order_by); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
# Get condition |
56
|
|
|
|
57
|
|
|
protected function getCondition(array $data) { |
58
|
|
|
|
59
|
|
|
return implode(' AND ', array_filter($this->config->cast($data, true))); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
# Constructor |
63
|
|
|
|
64
|
|
|
public function __construct() { |
65
|
|
|
|
66
|
|
|
$this->definition = Entitizer::definition(static::$table); |
67
|
|
|
|
68
|
|
|
$this->config = new Config(); |
69
|
|
|
|
70
|
|
|
$this->init(); |
|
|
|
|
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the parent class: