Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.53% covered (success)
91.53%
54 / 59
77.78% covered (warning)
77.78%
7 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
CreateObjectAction
91.53% covered (success)
91.53%
54 / 59
77.78% covered (warning)
77.78%
7 / 9
23.32
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
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
10.08
 __invoke
86.67% covered (warning)
86.67%
26 / 30
0.00% covered (danger)
0.00%
0 / 1
5.06
 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
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 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\IntegrationTestLogger;
6use Apie\Common\Other\LockUtil;
7use Apie\Core\Actions\ActionInterface;
8use Apie\Core\Actions\ActionResponse;
9use Apie\Core\Actions\ActionResponseStatus;
10use Apie\Core\Actions\ActionResponseStatusList;
11use Apie\Core\Actions\ApieFacadeInterface;
12use Apie\Core\Attributes\Description;
13use Apie\Core\BoundedContext\BoundedContextId;
14use Apie\Core\Context\ApieContext;
15use Apie\Core\ContextConstants;
16use Apie\Core\Entities\EntityInterface;
17use Apie\Core\Exceptions\IndexNotFoundException;
18use Apie\Core\Exceptions\InvalidTypeException;
19use Apie\Core\Lists\StringList;
20use Apie\Core\Utils\EntityUtils;
21use Apie\Core\ValueObjects\Utils;
22use Exception;
23use LogicException;
24use ReflectionClass;
25
26/**
27 * Action to create a new object.
28 */
29final class CreateObjectAction implements ActionInterface
30{
31    public function __construct(private readonly ApieFacadeInterface $apieFacade)
32    {
33    }
34
35    public static function isAuthorized(ApieContext $context, bool $runtimeChecks, bool $throwError = false): bool
36    {
37        $refl = new ReflectionClass($context->getContext(ContextConstants::RESOURCE_NAME, $throwError));
38        if (!$context->appliesToContext($refl, $runtimeChecks, $throwError ? new LogicException('Class access is not allowed') : null)) {
39            return false;
40        }
41        if (EntityUtils::isPolymorphicEntity($refl) && $runtimeChecks && $context->hasContext(ContextConstants::RAW_CONTENTS)) {
42            $rawContents = Utils::toArray($context->getContext(ContextConstants::RAW_CONTENTS, $throwError));
43            try {
44                $refl = EntityUtils::findClass($rawContents, $refl);
45            } catch (IndexNotFoundException) {
46            }
47        }
48        $constructor = $refl->getConstructor();
49        if ($constructor && !$context->appliesToContext($constructor, $runtimeChecks, $throwError ? new LogicException('Class instantiation is not allowed') : null)) {
50            return false;
51        }
52        return true;
53    }
54    
55    /**
56     * @param array<string|int, mixed> $rawContents
57     */
58    public function __invoke(ApieContext $context, array $rawContents): ActionResponse
59    {
60        $context->withContext(ContextConstants::RAW_CONTENTS, $rawContents)
61            ->withContext(ContextConstants::APIE_ACTION, __CLASS__)
62            ->checkAuthorization();
63        try {
64            $resource = $this->apieFacade->denormalizeNewObject(
65                $rawContents,
66                $context->getContext(ContextConstants::RESOURCE_NAME),
67                $context
68            );
69        } catch (Exception $error) {
70            IntegrationTestLogger::logException($error);
71            return ActionResponse::createClientError($this->apieFacade, $context, $error);
72        }
73        if (!$resource instanceof EntityInterface) {
74            throw new InvalidTypeException($resource, EntityInterface::class);
75        }
76        $context = $context->withContext(ContextConstants::RESOURCE, $resource);
77        $boundedContextId = new BoundedContextId($context->getContext(ContextConstants::BOUNDED_CONTEXT_ID));
78
79        // only autoincrement integers should do this, but this means we can not make a lock
80        if ($resource->getId()->toNative() === null) {
81            $resource = $this->apieFacade->persistNew($resource, $boundedContextId);
82        } else {
83            $lock = LockUtil::createLock(
84                $context,
85                [ContextConstants::BOUNDED_CONTEXT_ID, ContextConstants::RESOURCE_NAME, ContextConstants::RESOURCE_ID],
86                write: true
87            );
88            try {
89                $resource = $this->apieFacade->persistNew($resource, $boundedContextId);
90            } catch (Exception $error) {
91                IntegrationTestLogger::logException($error);
92                return ActionResponse::createClientError($this->apieFacade, $context, $error);
93            } finally {
94                $lock->release();
95            }
96        }
97        $context = $context->withContext(ContextConstants::RESOURCE, $resource);
98        $context->dispatchEvent(new ApieResourceCreated($resource, $context));
99        return ActionResponse::createCreationSuccess($this->apieFacade, $context, $resource, $resource);
100    }
101
102    /**
103     * @return ReflectionClass<EntityInterface>
104     */
105    public static function getInputType(ReflectionClass $class): ReflectionClass
106    {
107        return $class;
108    }
109
110    /**
111     * @return ReflectionClass<EntityInterface>
112     */
113    public static function getOutputType(ReflectionClass $class): ReflectionClass
114    {
115        return $class;
116    }
117
118    public static function getPossibleActionResponseStatuses(): ActionResponseStatusList
119    {
120        return new ActionResponseStatusList([
121            ActionResponseStatus::CREATED,
122            ActionResponseStatus::CLIENT_ERROR,
123            ActionResponseStatus::PERISTENCE_ERROR
124        ]);
125    }
126
127    /**
128     * @param ReflectionClass<covariant object> $class
129     */
130    public static function getDescription(ReflectionClass $class): string
131    {
132        $description = 'Creates an instance of ' . $class->getShortName();
133        foreach ($class->getAttributes(Description::class) as $attribute) {
134            $description .= '. ' . $attribute->newInstance()->description;
135        }
136
137        return $description;
138    }
139    
140    /**
141     * @param ReflectionClass<covariant object> $class
142     */
143    public static function getTags(ReflectionClass $class): StringList
144    {
145        return new StringList([$class->getShortName(), 'resource']);
146    }
147
148    /**
149     * @param ReflectionClass<covariant object> $class
150     */
151    public static function getRouteAttributes(ReflectionClass $class): array
152    {
153        return [
154            ContextConstants::CREATE_OBJECT => true,
155            ContextConstants::RESOURCE_NAME => $class->name,
156            ContextConstants::DISPLAY_FORM => true,
157        ];
158    }
159}