1 | <?php declare(strict_types=1); |
||
2 | |||
3 | namespace VSV\GVQ_API\Company\Serializers; |
||
4 | |||
5 | use Ramsey\Uuid\UuidFactoryInterface; |
||
6 | use VSV\GVQ_API\Common\Serializers\JsonEnricher; |
||
7 | use VSV\GVQ_API\User\Repositories\UserRepository; |
||
8 | |||
9 | class CompanyJsonEnricher implements JsonEnricher |
||
10 | { |
||
11 | /** |
||
12 | * @var UuidFactoryInterface |
||
13 | */ |
||
14 | private $uuidFactory; |
||
15 | |||
16 | /** |
||
17 | * @var UserRepository |
||
18 | */ |
||
19 | private $userRepository; |
||
20 | |||
21 | /** |
||
22 | * @param UuidFactoryInterface $uuidFactory |
||
23 | * @param UserRepository $userRepository |
||
24 | */ |
||
25 | public function __construct( |
||
26 | UuidFactoryInterface $uuidFactory, |
||
27 | UserRepository $userRepository |
||
28 | ) { |
||
29 | $this->uuidFactory = $uuidFactory; |
||
30 | $this->userRepository = $userRepository; |
||
31 | } |
||
32 | |||
33 | /** |
||
34 | * @param string $json |
||
35 | * @return string |
||
36 | */ |
||
37 | public function enrich(string $json): string |
||
38 | { |
||
39 | $companyAsArray = json_decode($json, true); |
||
40 | |||
41 | $companyAsArray['id'] = $this->uuidFactory->uuid4()->toString(); |
||
42 | |||
43 | for ($index = 0; $index < count($companyAsArray['aliases']); $index++) { |
||
0 ignored issues
–
show
|
|||
44 | $companyAsArray['aliases'][$index]['id'] = $this->uuidFactory->uuid4()->toString(); |
||
45 | } |
||
46 | |||
47 | $companyAsArray = $this->enrichWithUser($companyAsArray); |
||
48 | |||
49 | return json_encode($companyAsArray); |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * @param array $companyAsArray |
||
54 | * @return array |
||
55 | */ |
||
56 | private function enrichWithUser(array $companyAsArray): array |
||
57 | { |
||
58 | $user = $this->userRepository->getById( |
||
59 | $this->uuidFactory->fromString($companyAsArray['user']['id']) |
||
60 | ); |
||
61 | |||
62 | if ($user !== null) { |
||
63 | $companyAsArray['user']['email'] = $user->getEmail()->toNative(); |
||
64 | $companyAsArray['user']['firstName'] = $user->getFirstName()->toNative(); |
||
65 | $companyAsArray['user']['lastName'] = $user->getLastName()->toNative(); |
||
66 | $companyAsArray['user']['role'] = $user->getRole()->toNative(); |
||
67 | $companyAsArray['user']['language'] = $user->getLanguage()->toNative(); |
||
68 | } |
||
69 | |||
70 | return $companyAsArray; |
||
71 | } |
||
72 | } |
||
73 |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: