1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Webcook\Cms\SecurityBundle\EventSubscriber; |
4
|
|
|
|
5
|
|
|
use ApiPlatform\Core\EventListener\EventPriorities; |
6
|
|
|
use Webcook\Cms\SecurityBundle\Entity\User; |
7
|
|
|
use Symfony\Component\HttpFoundation\Request; |
8
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
9
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; |
10
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
11
|
|
|
|
12
|
|
|
final class UserControllerSubscriber implements EventSubscriberInterface |
13
|
|
|
{ |
14
|
|
|
private $em; |
15
|
|
|
|
16
|
|
|
private $encoderFactory; |
17
|
|
|
|
18
|
|
|
public function __construct($em, $encoderFactory) |
19
|
|
|
{ |
20
|
|
|
$this->em = $em; |
21
|
|
|
$this->encoderFactory = $encoderFactory; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public static function getSubscribedEvents() |
25
|
|
|
{ |
26
|
|
|
return [ |
27
|
|
|
KernelEvents::VIEW => [['postWrite', EventPriorities::POST_WRITE]], |
28
|
|
|
]; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function postWrite(GetResponseForControllerResultEvent $event) |
32
|
|
|
{ |
33
|
|
|
$user = $event->getControllerResult(); |
34
|
|
|
$method = $event->getRequest()->getMethod(); |
35
|
|
|
|
36
|
|
|
if (!$user instanceof User) { |
37
|
|
|
return; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$data = json_decode($event->getRequest()->getContent()); |
41
|
|
|
|
42
|
|
|
if (isset($data->password) && !empty($data->password)) { |
43
|
|
|
if ($method === 'PUT') { |
44
|
|
|
$oldPassword = $user->getPassword(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$plainPassword = $user->getPassword(); |
48
|
|
|
|
49
|
|
|
if (!empty($plainPassword)) { |
50
|
|
|
$factory = $this->encoderFactory; |
51
|
|
|
$encoder = $factory->getEncoder($user); |
52
|
|
|
$password = $encoder->encodePassword($plainPassword, $user->getSalt()); |
53
|
|
|
$user->setPassword($password); |
54
|
|
|
} else { |
55
|
|
|
$user->setPassword($oldPassword); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$this->em->persist($user); |
59
|
|
|
$this->em->flush(); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
If you define a variable conditionally, it can happen that it is not defined for all execution paths.
Let’s take a look at an example:
In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.
Available Fixes
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: