1 | <?php |
||
17 | class ImageUploader implements ImageUploaderInterface |
||
18 | { |
||
19 | /** |
||
20 | * @var Filesystem |
||
21 | */ |
||
22 | protected $filesystem; |
||
23 | |||
24 | /** |
||
25 | * @param Filesystem $filesystem |
||
26 | */ |
||
27 | public function __construct(Filesystem $filesystem) |
||
31 | |||
32 | /** |
||
33 | * {@inheritdoc} |
||
34 | */ |
||
35 | public function upload(ImageInterface $image) |
||
36 | { |
||
37 | if (!$image->hasFile()) { |
||
38 | return; |
||
39 | } |
||
40 | |||
41 | if (null !== $image->getPath() && $this->has($image->getPath())) { |
||
42 | $this->remove($image->getPath()); |
||
43 | } |
||
44 | |||
45 | do { |
||
46 | $hash = md5(uniqid(mt_rand(), true)); |
||
47 | $path = $this->expandPath($hash.'.'.$image->getFile()->guessExtension()); |
||
|
|||
48 | } while ($this->filesystem->has($path)); |
||
49 | |||
50 | $image->setPath($path); |
||
51 | |||
52 | $this->filesystem->write( |
||
53 | $image->getPath(), |
||
54 | file_get_contents($image->getFile()->getPathname()) |
||
55 | ); |
||
56 | } |
||
57 | |||
58 | /** |
||
59 | * {@inheritdoc} |
||
60 | */ |
||
61 | public function remove($path) |
||
65 | |||
66 | /** |
||
67 | * @param string $path |
||
68 | * |
||
69 | * @return string |
||
70 | */ |
||
71 | private function expandPath($path) |
||
80 | |||
81 | /** |
||
82 | * @param string $path |
||
83 | * |
||
84 | * @return bool |
||
85 | */ |
||
86 | private function has($path) |
||
90 | } |
||
91 |
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: