1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ScayTrase\Api\Cruds\Controller; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Persistence\ObjectManager; |
6
|
|
|
use Doctrine\Common\Persistence\ObjectRepository; |
7
|
|
|
use ScayTrase\Api\Cruds\EntityProcessorInterface; |
8
|
|
|
use ScayTrase\Api\Cruds\Event\CollectionCrudEvent; |
9
|
|
|
use ScayTrase\Api\Cruds\Event\CrudEvents; |
10
|
|
|
use ScayTrase\Api\Cruds\Exception\EntityNotFoundException; |
11
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcher; |
12
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
13
|
|
|
|
14
|
|
|
final class UpdateController |
15
|
|
|
{ |
16
|
|
|
const ACTION = 'patchAction'; |
17
|
|
|
|
18
|
|
|
/** @var ObjectManager */ |
19
|
|
|
private $manager; |
20
|
|
|
/** @var EventDispatcherInterface */ |
21
|
|
|
private $evm; |
22
|
|
|
/** @var ObjectRepository */ |
23
|
|
|
private $repository; |
24
|
|
|
/** @var EntityProcessorInterface */ |
25
|
|
|
private $processor; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* UpdateController constructor. |
29
|
|
|
* |
30
|
|
|
* @param ObjectRepository $repository |
31
|
|
|
* @param EntityProcessorInterface $processor |
32
|
|
|
* @param ObjectManager $manager |
33
|
|
|
* @param EventDispatcherInterface $evm |
34
|
|
|
*/ |
35
|
10 |
View Code Duplication |
public function __construct( |
|
|
|
|
36
|
|
|
ObjectRepository $repository, |
37
|
|
|
EntityProcessorInterface $processor, |
38
|
|
|
ObjectManager $manager, |
39
|
|
|
EventDispatcherInterface $evm = null |
40
|
|
|
) { |
41
|
10 |
|
$this->manager = $manager; |
42
|
10 |
|
$this->repository = $repository; |
43
|
10 |
|
$this->processor = $processor; |
44
|
10 |
|
$this->evm = $evm ?: new EventDispatcher(); |
45
|
10 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param mixed $identifier |
49
|
|
|
* @param mixed $data |
50
|
|
|
* |
51
|
|
|
* @return object |
52
|
|
|
* @throws EntityNotFoundException |
53
|
|
|
*/ |
54
|
10 |
|
public function patchAction($identifier, $data) |
55
|
|
|
{ |
56
|
10 |
|
$entity = $this->repository->find($identifier); |
57
|
|
|
|
58
|
10 |
|
if (!$entity) { |
59
|
|
|
throw EntityNotFoundException::byIdentifier($identifier); |
60
|
|
|
} |
61
|
|
|
|
62
|
10 |
|
$this->evm->dispatch(CrudEvents::READ, new CollectionCrudEvent([$entity])); |
63
|
10 |
|
$entity = $this->processor->updateEntity($entity, $data); |
64
|
10 |
|
$this->evm->dispatch(CrudEvents::UPDATE, new CollectionCrudEvent([$entity])); |
65
|
10 |
|
$this->manager->flush(); |
66
|
|
|
|
67
|
10 |
|
return $entity; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.