DoctrineSerializationConfigGenerator::generate()   B
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 33
Code Lines 19

Duplication

Lines 7
Ratio 21.21 %

Code Coverage

Tests 19
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 7
loc 33
rs 8.439
ccs 19
cts 19
cp 1
cc 6
eloc 19
nc 5
nop 2
crap 6
1
<?php
2
3
namespace Pgs\RestfonyBundle\Generator;
4
5
use Doctrine\ORM\Mapping\ClassMetadataInfo;
6
use JMS\Serializer\Annotation\ExclusionPolicy;
7
use Pgs\RestfonyBundle\Generator\Helper\BundleStructureHelper;
8
use Sensio\Bundle\GeneratorBundle\Generator\Generator;
9
use Symfony\Component\Filesystem\Exception\IOException;
10
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
11
use Symfony\Component\Yaml\Yaml;
12
13
class DoctrineSerializationConfigGenerator extends Generator
14
{
15
    protected $groupPrefixes = [''];
16
    protected $groupSuffixes = ['_list', '_get'];
17
18
    protected $excludedRelationPrefixSuffixPairs = [
19
        ['', '_get'],
20
    ];
21
22
    /**
23
     * @var BundleStructureHelper
24
     */
25
    protected $helper;
26
27
    /**
28
     * DoctrineSerializationConfigGenerator constructor.
29
     * @param BundleInterface   $bundle   The bundle in which to create the class
30
     * @param string            $entity   The entity relative class name
31
     */
32 4
    public function __construct(BundleInterface $bundle, $entity)
33
    {
34 4
        $this->helper = new BundleStructureHelper($bundle, $entity);
35 4
    }
36
37
    /**
38
     * Generates the entity form class if it does not exist.
39
     *
40
     * @param ClassMetadataInfo $metadata The entity metadata class
41
     */
42 4
    public function generate(ClassMetadataInfo $metadata, $forceOverwrite = false)
43
    {
44 4
        $file = $this->helper->getResourcesDirname() . '/config/serializer/Entity.' . $this->helper->getEntityClass() . '.yml';
0 ignored issues
show
Documentation Bug introduced by
The method getResourcesDirname does not exist on object<Pgs\RestfonyBundl...\BundleStructureHelper>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
Documentation Bug introduced by
The method getEntityClass does not exist on object<Pgs\RestfonyBundl...\BundleStructureHelper>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
45
46 4
        if (!file_exists(dirname($file)) && !@mkdir(dirname($file), 0777, true)) {
47 1
            throw new IOException('Unable to create config/serializer directory');
48
        }
49
50 3 View Code Duplication
        if (!$this->canWriteToFile($file, $forceOverwrite)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
51 1
            throw new \RuntimeException(sprintf(
52 1
                'Unable to generate the %s serialization config as it already exists under the file: %s',
53 1
                $this->helper->getEntityClass(),
0 ignored issues
show
Documentation Bug introduced by
The method getEntityClass does not exist on object<Pgs\RestfonyBundl...\BundleStructureHelper>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
54
                $file
55
            ));
56
        }
57
58 2
        $entityNameLower = $this->helper->camelToUnderscore($this->helper->getEntityClass());
0 ignored issues
show
Documentation Bug introduced by
The method getEntityClass does not exist on object<Pgs\RestfonyBundl...\BundleStructureHelper>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
59
60 2
        $data[$this->helper->getEntityFullClass()] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
Documentation Bug introduced by
The method getEntityFullClass does not exist on object<Pgs\RestfonyBundl...\BundleStructureHelper>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
61 2
            'exclusion_policy' => ExclusionPolicy::ALL,
62 2
            'xml_root_name' => $this->helper->getEntityClass(),
0 ignored issues
show
Documentation Bug introduced by
The method getEntityClass does not exist on object<Pgs\RestfonyBundl...\BundleStructureHelper>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
63 2
            'properties' => $this->getPropertiesFromMetadata($entityNameLower, $metadata),
64 2
            'relations' => $this->getRelationsFromMetadata($entityNameLower, $metadata),
0 ignored issues
show
Unused Code introduced by
The call to DoctrineSerializationCon...RelationsFromMetadata() has too many arguments starting with $metadata.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
65
        ];
66
67 2
        $this->writeYamlToFile($file, $data);
68
69 2
        foreach ($metadata->getAssociationMappings() as $association) {
70 2
            if ($association['targetEntity']) {
71 2
                $this->generateForEntity($association['targetEntity'], dirname($file), $entityNameLower);
72
            }
73
        }
74 2
    }
75
76 2
    protected function canWriteToFile($file, $forceOverwrite)
77
    {
78 2
        return !file_exists($file) || $forceOverwrite;
79
    }
80
81 1
    protected function writeYamlToFile($filePath, array $data)
82
    {
83 1
        $yaml = Yaml::dump($data, 4);
84 1
        file_put_contents($filePath, $yaml);
85 1
    }
86
87
    /**
88
     * @param string $targetClass
89
     * @param string $dirPath
90
     * @param string $entityNameLower
91
     */
92 2
    private function generateForEntity($targetClass, $dirPath, $entityNameLower)
93
    {
94 2
        $targetClassName = basename($targetClass);
95
96 2
        $targetPath = $dirPath . '/Entity.' . $targetClassName . '.yml';
97 2
        $targetData = $this->getYamlFileContent($targetPath);
98
99 2
        if (isset($targetData[$targetClass])) {
100 1
            foreach ($targetData[$targetClass]['properties'] as &$property) {
101 1
                $property['groups'] = array_merge(
102 1
                    $property['groups'],
103 1
                    $this->getGroupsFromMetadata($entityNameLower)
104
                );
105
            }
106
        }
107
108 2
        if (!empty($targetData)) {
109 1
            $this->writeYamlToFile($targetPath, $targetData);
110
        }
111 2
    }
112
113 1
    protected function getYamlFileContent($filePath)
114
    {
115 1
        return file_exists($filePath) ? Yaml::parse($filePath) : [];
116
    }
117
118
    /**
119
     * Returns an array of fields. Fields can be both column fields and
120
     * association fields.
121
     *
122
     * @param $entityName
123
     * @param ClassMetadataInfo $metadata
124
     *
125
     * @return array $fields
126
     */
127 2
    protected function getPropertiesFromMetadata($entityName, ClassMetadataInfo $metadata)
128
    {
129 2
        $fields = array_merge($metadata->fieldMappings, $metadata->getAssociationMappings());
130
131 2
        foreach ($metadata->getAssociationMappings() as $fieldName => $relation) {
132
            $multiTypes = array(
133 2
                ClassMetadataInfo::ONE_TO_MANY,
134 2
                ClassMetadataInfo::MANY_TO_MANY,
135
            );
136 2 View Code Duplication
            if (in_array($relation['type'], $multiTypes)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137 2
                $fields[$fieldName]['relatedType'] = 'collection';
138
            } else {
139 2
                $fields[$fieldName]['relatedType'] = 'entity';
140
            }
141
        }
142
143 2
        $result = [];
144
145 2
        foreach ($fields as $fieldName => $field) {
146
            $item = [
147 2
                'expose' => true,
148 2
                'groups' => $this->getGroupsFromMetadata($entityName),
149
            ];
150 2
            if (!empty($field['id'])) {
151 2
                $item['xml_attribute'] = true;
152
            }
153 2
            if ($field['type'] === 'date') {
154 2
                $item['type'] = "DateTime<'Y-m-d'>";
155
            }
156 2
            $result[$fieldName] = $item;
157
        }
158
159 2
        return $result;
160
    }
161
162 2
    protected function getGroupsFromMetadata($entityName)
163
    {
164 2
        $result = [];
165
166 2
        foreach ($this->groupPrefixes as $prefix) {
167 2
            foreach ($this->groupSuffixes as $suffix) {
168 2
                $result[] = $prefix.$entityName.$suffix;
169
            }
170
        }
171
172 2
        return $result;
173
    }
174
175 2
    private function getRelationsFromMetadata($entityName)
176
    {
177 2
        $result = [];
178
179 2
        $groups = [];
180 2
        foreach ($this->excludedRelationPrefixSuffixPairs as $pair) {
181 2
            $groups[] = $pair[0] . $entityName . $pair[1];
182
        }
183
184 2
        $result[] = [
185 2
            'rel' => 'self',
186 2
            'href' => "expr('/api/v1/products/' ~ object.getId())",
187
            'exclusion' => [
188 2
                'groups' => $groups,
189
            ],
190
        ];
191
192 2
        return $result;
193
    }
194
}
195