Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
SubObjectCodeGenerator
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
8
100.00% covered (success)
100.00%
1 / 1
 run
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
8
1<?php
2namespace Apie\StorageMetadataBuilder\CodeGenerators;
3
4use Apie\Core\Context\ApieContext;
5use Apie\Core\Identifiers\KebabCaseSlug;
6use Apie\Core\Metadata\CompositeMetadata;
7use Apie\Core\Metadata\MetadataFactory;
8use Apie\Core\Utils\ConverterUtils;
9use Apie\StorageMetadata\Attributes\OneToOneAttribute;
10use Apie\StorageMetadataBuilder\Factories\ClassTypeFactory;
11use Apie\StorageMetadataBuilder\Interfaces\RunGeneratedCodeContextInterface;
12use Apie\StorageMetadataBuilder\Mediators\GeneratedCodeContext;
13use Psr\Http\Message\UploadedFileInterface;
14
15/**
16 * Creates the one to many relations for lists.
17 * - create a sub table for the list
18 * - the sub table references the entity with 'parent' property
19 * - an 'order' property is made for the index of the hashmap or the order of the list.
20 */
21final class SubObjectCodeGenerator implements RunGeneratedCodeContextInterface
22{
23    public function run(GeneratedCodeContext $generatedCodeContext): void
24    {
25        $property = $generatedCodeContext->getCurrentProperty();
26        $class = $property ? ConverterUtils::toReflectionClass($property) : null;
27        $currentTable = $generatedCodeContext->getCurrentTable();
28        if (null === $class || null === $currentTable || in_array((string) $property->getType(), [UploadedFileInterface::class])) {
29            return;
30        }
31        $metadata = MetadataFactory::getMetadataStrategyForType($property->getType())
32            ->getResultMetadata(new ApieContext());
33        $propertyName = 'apie_'
34            . str_replace('-', '_', (string) KebabCaseSlug::fromClass($property->getDeclaringClass()))
35            . '_'
36            . str_replace('-', '_', (string) KebabCaseSlug::fromClass($property));
37        if ($currentTable->hasProperty($propertyName)) {
38            return;
39        }
40        if ($metadata instanceof CompositeMetadata) {
41            $tableName = $generatedCodeContext->getPrefix(
42                'apie_resource_'
43            );
44            $table = ClassTypeFactory::createStorageTable($tableName, $class);
45            $generatedCodeContext->withCurrentObject($class)->iterateOverTable($table);
46            $currentTable->addProperty($propertyName)
47                ->setType(($property->getType()->allowsNull() ? '?' : '') . $tableName)
48                ->addAttribute(OneToOneAttribute::class, [$property->name, null, $property->getDeclaringClass()->name]);
49        }
50    }
51}