Passed
Push — feature/publishable ( 37a3c2...12f3b6 )
by Daniel
15:22 queued 09:09
created

PublishableEventListener::getValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 2
crap 2
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\EventListener\Api;
15
16
use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
17
use ApiPlatform\Core\Validator\ValidatorInterface;
18
use Doctrine\Persistence\ManagerRegistry;
19
use Silverback\ApiComponentBundle\Entity\Utility\PublishableTrait;
20
use Silverback\ApiComponentBundle\Helper\PublishableHelper;
21
use Silverback\ApiComponentBundle\Utility\ClassMetadataTrait;
22
use Silverback\ApiComponentBundle\Validator\PublishableValidator;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpKernel\Event\RequestEvent;
25
use Symfony\Component\HttpKernel\Event\ResponseEvent;
26
use Symfony\Component\HttpKernel\Event\ViewEvent;
27
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
28
29
/**
30
 * @author Vincent Chalamon <[email protected]>
31
 */
32
final class PublishableEventListener
33
{
34
    use ClassMetadataTrait;
35
36
    public const VALID_TO_PUBLISH_HEADER = 'valid-to-publish';
37
    public const VALID_PUBLISHED_QUERY = 'validate_published';
38
39
    private PublishableHelper $publishableHelper;
40
    private ValidatorInterface $validator;
41
42
    public function __construct(PublishableHelper $publishableHelper, ManagerRegistry $registry, ValidatorInterface $validator)
43
    {
44
        $this->publishableHelper = $publishableHelper;
45
        $this->initRegistry($registry);
46
        $this->validator = $validator;
47
    }
48
49
    public function onPreWrite(ViewEvent $event): void
50
    {
51
        $request = $event->getRequest();
52
        $data = $request->attributes->get('data');
53
        if (
54
            empty($data) ||
55
            !$this->publishableHelper->isConfigured($data) ||
56
            $request->isMethod(Request::METHOD_DELETE)
57
        ) {
58
            return;
59
        }
60
61
        $publishable = $this->checkMergeDraftIntoPublished($request, $data);
62
        $event->setControllerResult($publishable);
63
    }
64
65
    public function onPostRead(RequestEvent $event): void
66
    {
67
        $request = $event->getRequest();
68
        $data = $request->attributes->get('data');
69
        if (
70
            empty($data) ||
71
            !$this->publishableHelper->isConfigured($data) ||
72
            !$request->isMethod(Request::METHOD_GET)
73
        ) {
74
            return;
75
        }
76
77
        $this->checkMergeDraftIntoPublished($request, $data, true);
78
    }
79
80
    public function onPostDeserialize(RequestEvent $event): void
81
    {
82
        $request = $event->getRequest();
83
        $data = $request->attributes->get('data');
84
        if (
85
            empty($data) ||
86
            !$this->publishableHelper->isConfigured($data) ||
87
            !($request->isMethod(Request::METHOD_PUT) || $request->isMethod(Request::METHOD_PATCH))
88
        ) {
89
            return;
90
        }
91
92
        $configuration = $this->publishableHelper->getConfiguration($data);
93
94
        // User cannot change the publication date of the original resource
95
        if (
96
            true === $this->publishableHelper->isPublishedRequest($request) &&
97
            $this->getValue($request->attributes->get('previous_data'), $configuration->fieldName) !== $this->getValue($data, $configuration->fieldName)
98
        ) {
99
            throw new BadRequestHttpException('You cannot change the publication date of a published resource.');
100
        }
101
    }
102
103
    public function onPostRespond(ResponseEvent $event): void
104
    {
105
        $request = $event->getRequest();
106
        /** @var PublishableTrait|null $data */
107
        $data = $request->attributes->get('data');
108
        if (
109
            null === $data ||
110
            !$this->publishableHelper->isConfigured($data)
111
        ) {
112
            return;
113
        }
114
        $response = $event->getResponse();
115
116
        $configuration = $this->publishableHelper->getConfiguration($data);
117
        $classMetadata = $this->getClassMetadata($data);
118
        $draftResource = $classMetadata->getFieldValue($data, $configuration->reverseAssociationName) ?? $data;
119
120
        // Add Expires HTTP header
121
        /** @var \DateTime|null $publishedAt */
122
        $publishedAt = $classMetadata->getFieldValue($draftResource, $configuration->fieldName);
123
        if ($publishedAt && $publishedAt > new \DateTime()) {
124
            $response->setExpires($publishedAt);
125
        }
126
127
        if (!$this->publishableHelper->isGranted($data)) {
128
            return;
129
        }
130
131
        if ($response->isClientError()) {
132
            $response->headers->set(self::VALID_TO_PUBLISH_HEADER, 0);
133
134
            return;
135
        }
136
137
        // Force validation from querystring, and/or add validate-to-publish custom HTTP header
138
        try {
139
            $this->validator->validate($data, [PublishableValidator::PUBLISHED_KEY => true]);
140
            $response->headers->set(self::VALID_TO_PUBLISH_HEADER, 1);
141
        } catch (ValidationException $exception) {
142
            $response->headers->set(self::VALID_TO_PUBLISH_HEADER, 0);
143
144
            if (
145
                \in_array($request->getMethod(), [Request::METHOD_POST, Request::METHOD_PUT], true) &&
146
                true === $request->query->getBoolean(self::VALID_PUBLISHED_QUERY, false)
147
            ) {
148
                throw $exception;
149
            }
150
        }
151
    }
152
153
    private function getValue(object $object, string $property)
154
    {
155
        return $this->getClassMetadata($object)->getFieldValue($object, $property);
156
    }
157
158
    private function checkMergeDraftIntoPublished(Request $request, object $data, bool $flushDatabase = false): object
159
    {
160
        if (!$this->publishableHelper->isActivePublishedAt($data)) {
161
            return $data;
162
        }
163
164
        $configuration = $this->publishableHelper->getConfiguration($data);
165
        $classMetadata = $this->getClassMetadata($data);
166
167
        $publishedResourceAssociation = $classMetadata->getFieldValue($data, $configuration->associationName);
168
        $draftResourceAssociation = $classMetadata->getFieldValue($data, $configuration->reverseAssociationName);
169
        if (
170
            !$publishedResourceAssociation &&
171
            (!$draftResourceAssociation || !$this->publishableHelper->isActivePublishedAt($draftResourceAssociation))
172
        ) {
173
            return $data;
174
        }
175
176
        // the request is for a resource with an active publish date
177
        // either a draft, if so it may be a published version we need to replace with
178
        // or a published resource which may have a draft that has an active publish date
179
        $entityManager = $this->getEntityManager($data);
180
181
        $meta = $entityManager->getClassMetadata(\get_class($data));
182
        $identifierFieldName = $meta->getSingleIdentifierFieldName();
183
184
        if ($publishedResourceAssociation) {
185
            // retrieving a draft that is now published
186
            $draftResource = $data;
187
            $publishedResource = $publishedResourceAssociation;
188
189
            $publishedId = $classMetadata->getFieldValue($publishedResource, $identifierFieldName);
190
            $request->attributes->set('id', $publishedId);
191
            $request->attributes->set('data', $publishedResource);
192
            $request->attributes->set('previous_data', clone $publishedResource);
193
        } else {
194
            // retrieving a published resource and draft should now replace it
195
            $publishedResource = $data;
196
            $draftResource = $draftResourceAssociation;
197
        }
198
199
        $classMetadata->setFieldValue($publishedResource, $configuration->reverseAssociationName, null);
200
        $classMetadata->setFieldValue($draftResource, $configuration->associationName, null);
201
202
        $this->mergeDraftIntoPublished($identifierFieldName, $draftResource, $publishedResource, $flushDatabase);
203
204
        return $publishedResource;
205
    }
206
207
    private function mergeDraftIntoPublished(string $identifierFieldName, object $draftResource, object $publishedResource, bool $flushDatabase): void
208
    {
209
        $draftReflection = new \ReflectionClass($draftResource);
210
        $publishedReflection = new \ReflectionClass($publishedResource);
211
        $properties = $publishedReflection->getProperties();
212
213
        foreach ($properties as $property) {
214
            $property->setAccessible(true);
215
            $name = $property->getName();
216
            if ($identifierFieldName === $name) {
217
                continue;
218
            }
219
            $draftProperty = $draftReflection->hasProperty($name) ? $draftReflection->getProperty($name) : null;
220
            if ($draftProperty) {
221
                $draftProperty->setAccessible(true);
222
                $draftValue = $draftProperty->getValue($draftResource);
223
                $property->setValue($publishedResource, $draftValue);
224
            }
225
        }
226
227
        $entityManager = $this->getEntityManager($draftResource);
228
        $entityManager->remove($draftResource);
229
        if ($flushDatabase) {
230
            $entityManager->flush();
231
        }
232
    }
233
}
234