1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Silverback API Component Bundle Project |
5
|
|
|
* |
6
|
|
|
* (c) Daniel West <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Silverback\ApiComponentBundle\Metadata; |
15
|
|
|
|
16
|
|
|
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; |
17
|
|
|
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; |
18
|
|
|
use Silverback\ApiComponentBundle\Publishable\PublishableHelper; |
19
|
|
|
use Symfony\Component\HttpFoundation\RequestStack; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Builds and add validation group for published resources. |
23
|
|
|
* |
24
|
|
|
* @author Vincent Chalamon <[email protected]> |
25
|
|
|
*/ |
26
|
|
|
class PublishableMetadataFactory implements ResourceMetadataFactoryInterface |
27
|
|
|
{ |
28
|
|
|
private ResourceMetadataFactoryInterface $decorated; |
29
|
|
|
private PublishableHelper $publishableHelper; |
30
|
|
|
private RequestStack $requestStack; |
31
|
|
|
|
32
|
|
|
public function __construct(ResourceMetadataFactoryInterface $decorated, PublishableHelper $publishableHelper, RequestStack $requestStack) |
33
|
|
|
{ |
34
|
|
|
$this->decorated = $decorated; |
35
|
|
|
$this->publishableHelper = $publishableHelper; |
36
|
|
|
$this->requestStack = $requestStack; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function create(string $resourceClass): ResourceMetadata |
40
|
|
|
{ |
41
|
|
|
$resourceMetadata = $this->decorated->create($resourceClass); |
42
|
|
|
if (!$this->publishableHelper->isPublishable($resourceClass)) { |
43
|
|
|
return $resourceMetadata; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
// Try to retrieve data from request |
47
|
|
|
// todo Find a better way to retrieve the data |
48
|
|
|
if (!($request = $this->requestStack->getCurrentRequest()) || empty($data = $request->attributes->get('data'))) { |
49
|
|
|
return $resourceMetadata; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if ($this->publishableHelper->hasPublicationDate($data)) { |
53
|
|
|
$configuration = $this->publishableHelper->getConfiguration($resourceClass); |
54
|
|
|
$attributes = $resourceMetadata->getAttributes() ?: []; |
55
|
|
|
|
56
|
|
|
$resourceMetadata = $resourceMetadata->withAttributes(array_unique(array_merge_recursive($attributes, [ |
57
|
|
|
'validation_groups' => null !== $configuration->validationGroups ? $configuration->validationGroups : [ |
58
|
|
|
'Default', |
59
|
|
|
"$resourceClass:published", |
60
|
|
|
], |
61
|
|
|
]))); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $resourceMetadata; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|