1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LaravelLangBundler\BundleItems; |
4
|
|
|
|
5
|
|
|
use Illuminate\Container\Container; |
6
|
|
|
use LaravelLangBundler\Exceptions\InvalidModificationArgument; |
7
|
|
|
|
8
|
|
|
class ItemFactory |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Allowed values for BundleItem target property. |
12
|
|
|
* |
13
|
|
|
* @var array |
14
|
|
|
*/ |
15
|
|
|
const ALLOWEDTARGETS = [ |
16
|
|
|
'value', |
17
|
|
|
'key', |
18
|
|
|
'both', |
19
|
|
|
]; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Build a BundleItem instance. |
23
|
|
|
* |
24
|
|
|
* @param string $id |
25
|
|
|
* @param string $type Filename_affected |
26
|
|
|
* @param array $parameters |
27
|
|
|
* |
28
|
|
|
* @return BundleItem |
29
|
|
|
*/ |
30
|
|
|
public static function build($id, $type = null, array $parameters = []) |
31
|
|
|
{ |
32
|
|
|
if (is_null($type)) { |
33
|
|
|
return new BundleItem($id); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
list($target, $name) = explode('_', $type); |
37
|
|
|
|
38
|
|
|
self::validateTarget($target); |
39
|
|
|
|
40
|
|
|
$className = ucfirst($name).'Mod'; |
41
|
|
|
|
42
|
|
|
$appNamespace = Container::getInstance()->getNamespace(); |
|
|
|
|
43
|
|
|
|
44
|
|
|
$localClass = "\\{$appNamespace}LangBundler\\Mods\\{$className}"; |
45
|
|
|
|
46
|
|
|
$vendorClass = "\LaravelLangBundler\\BundleItems\\Mods\\{$className}"; |
47
|
|
|
|
48
|
|
|
if (class_exists($localClass)) { |
49
|
|
|
return new $localClass($id, $target, $parameters); |
50
|
|
|
} elseif (class_exists($vendorClass)) { |
51
|
|
|
return new $vendorClass($id, $target, $parameters); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
throw InvalidModificationArgument::modifcationClassNotFound($className); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Validate the target. |
59
|
|
|
* |
60
|
|
|
* @param string $target |
61
|
|
|
* |
62
|
|
|
* @throws InvalidModificationTarget |
63
|
|
|
*/ |
64
|
|
|
protected static function validateTarget($target) |
65
|
|
|
{ |
66
|
|
|
if (!in_array($target, self::ALLOWEDTARGETS)) { |
67
|
|
|
throw InvalidModificationArgument::targetNotAllowed($target); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
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: