Passed
Pull Request — feature/publishable (#53)
by Vincent
06:53
created

PublishableEventListener::onPostRespond()   B

Complexity

Conditions 9
Paths 13

Size

Total Lines 40
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

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