Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
89.66% covered (warning)
89.66%
78 / 87
66.67% covered (warning)
66.67%
6 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
ReplaceObjectAction
89.66% covered (warning)
89.66%
78 / 87
66.67% covered (warning)
66.67%
6 / 9
35.28
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isAuthorized
72.73% covered (warning)
72.73%
8 / 11
0.00% covered (danger)
0.00%
0 / 1
12.03
 __invoke
91.38% covered (success)
91.38%
53 / 58
0.00% covered (danger)
0.00%
0 / 1
16.16
 getInputType
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getOutputType
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getPossibleActionResponseStatuses
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 getDescription
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 getTags
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRouteAttributes
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2namespace Apie\Common\Actions;
3
4use Apie\Common\Events\ApieResourceCreated;
5use Apie\Common\Exceptions\EntityEtagConflictException;
6use Apie\Common\IntegrationTestLogger;
7use Apie\Common\Other\LockUtil;
8use Apie\Core\Actions\ActionInterface;
9use Apie\Core\Actions\ActionResponse;
10use Apie\Core\Actions\ActionResponseStatus;
11use Apie\Core\Actions\ActionResponseStatusList;
12use Apie\Core\Actions\ApieFacadeInterface;
13use Apie\Core\Attributes\Description;
14use Apie\Core\BoundedContext\BoundedContextId;
15use Apie\Core\Context\ApieContext;
16use Apie\Core\ContextConstants;
17use Apie\Core\Datalayers\ApieDatalayer;
18use Apie\Core\Entities\EntityInterface;
19use Apie\Core\Exceptions\EntityAlreadyPersisted;
20use Apie\Core\Exceptions\EntityNotFoundException;
21use Apie\Core\Exceptions\IndexNotFoundException;
22use Apie\Core\Exceptions\InvalidTypeException;
23use Apie\Core\Lists\StringList;
24use Apie\Core\Utils\EntityUtils;
25use Apie\Core\ValueObjects\Utils;
26use Exception;
27use LogicException;
28use Psr\Http\Message\ServerRequestInterface;
29use ReflectionClass;
30
31/**
32 * Action to create/replace a new object.
33 */
34final class ReplaceObjectAction implements ActionInterface
35{
36    public function __construct(private readonly ApieFacadeInterface $apieFacade)
37    {
38    }
39
40    public static function isAuthorized(ApieContext $context, bool $runtimeChecks, bool $throwError = false): bool
41    {
42        $refl = new ReflectionClass($context->getContext(ContextConstants::RESOURCE_NAME, $throwError));
43        if (!$context->appliesToContext($refl, $runtimeChecks, $throwError ? new LogicException('Class access is not allowed') : null)) {
44            return false;
45        }
46        if (EntityUtils::isPolymorphicEntity($refl) && $runtimeChecks && $context->hasContext(ContextConstants::RAW_CONTENTS)) {
47            $rawContents = Utils::toArray($context->getContext(ContextConstants::RAW_CONTENTS, $throwError));
48            try {
49                $refl = EntityUtils::findClass($rawContents, $refl);
50            } catch (IndexNotFoundException) {
51            }
52        }
53        $constructor = $refl->getConstructor();
54        if ($constructor && !$context->appliesToContext($constructor, $runtimeChecks, $throwError ? new LogicException('Class instantiation is not allowed') : null)) {
55            return false;
56        }
57        return true;
58    }
59    
60    /**
61     * @param array<string|int, mixed> $rawContents
62     */
63    public function __invoke(ApieContext $context, array $rawContents): ActionResponse
64    {
65        if ($context->hasContext(ContextConstants::RESOURCE_ID)) {
66            $rawContents['id'] = $context->getContext(ContextConstants::RESOURCE_ID);
67        }
68
69        $context->withContext(ContextConstants::RAW_CONTENTS, $rawContents)
70            ->withContext(ContextConstants::APIE_ACTION, __CLASS__)
71            ->checkAuthorization();
72        try {
73            $resource = $this->apieFacade->denormalizeNewObject(
74                $rawContents,
75                $context->getContext(ContextConstants::RESOURCE_NAME),
76                $context
77            );
78        } catch (Exception $error) {
79            IntegrationTestLogger::logException($error);
80            return ActionResponse::createClientError($this->apieFacade, $context, $error);
81        }
82
83        if (!$resource instanceof EntityInterface) {
84            throw new InvalidTypeException($resource, EntityInterface::class);
85        }
86        $request = $context->getContext(ServerRequestInterface::class, false);
87        $ifMatch = $request instanceof ServerRequestInterface && $request->hasHeader('If-Match')
88            ? trim($request->getHeaderLine('If-Match'))
89            : null;
90
91        $context = $context->withContext(ContextConstants::RESOURCE, $resource);
92        $boundedContextId = new BoundedContextId($context->getContext(ContextConstants::BOUNDED_CONTEXT_ID));
93        $request = $context->getContext(ServerRequestInterface::class, false);
94        $ifMatch = $request instanceof ServerRequestInterface && $request->hasHeader('If-Match')
95            ? trim($request->getHeaderLine('If-Match'))
96            : null;
97        $putContext = $context
98            ->withContext(ContextConstants::DISABLE_CONTEXT_FILTER, true);
99        $lock = LockUtil::createLock(
100            $putContext,
101            [ContextConstants::BOUNDED_CONTEXT_ID, ContextConstants::RESOURCE_NAME, ContextConstants::RESOURCE_ID],
102            write: true
103        );
104        try {
105            $existing = null;
106            try {
107                $existing = $this->apieFacade->find($resource->getId(), $boundedContextId);
108            } catch (EntityNotFoundException) {
109            }
110            if ($existing === null) {
111                if ($ifMatch !== null) {
112                    throw new EntityEtagConflictException();
113                }
114            } else {
115                $resourceContext = $putContext
116                    ->withContext(ContextConstants::RESOURCE, $existing)
117                    ->withContext(ContextConstants::APIE_ACTION, GetItemAction::class);
118                if (!GetItemAction::isAuthorized($resourceContext, true)) {
119                    throw new EntityAlreadyPersisted($resource);
120                }
121                if ($ifMatch !== null) {
122                    $metadata = $context->getContext(ApieDatalayer::class)
123                        ->getMetadata($resource->getId(), $boundedContextId);
124                    $currentEtag = '"' . $metadata->etag . '"';
125                    $providedEtags = array_map('trim', explode(',', $ifMatch));
126                    if (!in_array('*', $providedEtags, true) && !in_array($currentEtag, $providedEtags, true)) {
127                        throw new EntityEtagConflictException();
128                    }
129                }
130            }
131            $resource = $this->apieFacade->upsert($resource, $boundedContextId);
132        } catch (Exception $error) {
133            IntegrationTestLogger::logException($error);
134            return ActionResponse::createClientError($this->apieFacade, $context, $error);
135        } finally {
136            $lock->release();
137        }
138        $context = $context->withContext(ContextConstants::RESOURCE, $resource);
139        $context->dispatchEvent(new ApieResourceCreated($resource, $context));
140        return ActionResponse::createCreationSuccess($this->apieFacade, $context, $resource, $resource);
141    }
142
143    /**
144     * @return ReflectionClass<EntityInterface>
145     */
146    public static function getInputType(ReflectionClass $class): ReflectionClass
147    {
148        return $class;
149    }
150
151    /**
152     * @return ReflectionClass<EntityInterface>
153     */
154    public static function getOutputType(ReflectionClass $class): ReflectionClass
155    {
156        return $class;
157    }
158
159    public static function getPossibleActionResponseStatuses(): ActionResponseStatusList
160    {
161        return new ActionResponseStatusList([
162            ActionResponseStatus::CREATED,
163            ActionResponseStatus::CLIENT_ERROR,
164            ActionResponseStatus::PERISTENCE_ERROR
165        ]);
166    }
167
168    /**
169     * @param ReflectionClass<covariant object> $class
170     */
171    public static function getDescription(ReflectionClass $class): string
172    {
173        $description = 'Creates an instance of ' . $class->getShortName();
174        foreach ($class->getAttributes(Description::class) as $attribute) {
175            $description .= '. ' . $attribute->newInstance()->description;
176        }
177
178        return $description;
179    }
180    
181    /**
182     * @param ReflectionClass<covariant object> $class
183     */
184    public static function getTags(ReflectionClass $class): StringList
185    {
186        return new StringList([$class->getShortName(), 'resource']);
187    }
188
189    /**
190     * @param ReflectionClass<covariant object> $class
191     */
192    public static function getRouteAttributes(ReflectionClass $class): array
193    {
194        return [
195            ContextConstants::REPLACE_OBJECT => true,
196            ContextConstants::RESOURCE_NAME => $class->name,
197            ContextConstants::DISPLAY_FORM => true,
198        ];
199    }
200}