Completed
Push — master ( 770316...74fc07 )
by Jeroen
09:08 queued 02:44
created

Kunstmaan/FixturesBundle/Builder/PageBuilder.php (4 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\FixturesBundle\Builder;
4
5
use Doctrine\ORM\EntityManager;
6
use Kunstmaan\FixturesBundle\Loader\Fixture;
7
use Kunstmaan\FixturesBundle\Populator\Populator;
8
use Kunstmaan\NodeBundle\Entity\HasNodeInterface;
9
use Kunstmaan\NodeBundle\Entity\Node;
10
use Kunstmaan\NodeBundle\Entity\NodeTranslation;
11
use Kunstmaan\NodeBundle\Entity\NodeVersion;
12
use Kunstmaan\NodeBundle\Entity\StructureNode;
13
use Kunstmaan\NodeBundle\Helper\PagesConfiguration;
14
use Kunstmaan\NodeBundle\Helper\Services\ACLPermissionCreatorService;
15
use Kunstmaan\PagePartBundle\Entity\PageTemplateConfiguration;
16
use Kunstmaan\UtilitiesBundle\Helper\ClassLookup;
17
use Kunstmaan\UtilitiesBundle\Helper\Slugifier;
18
19
class PageBuilder implements BuilderInterface
20
{
21
    private $manager;
22
23
    private $userRepo;
24
25
    private $nodeRepo;
26
27
    private $nodeTranslationRepo;
28
29
    private $aclPermissionCreatorService;
30
31
    private $populator;
32
33
    private $slugifier;
34
35
    /**
36
     * @var PagesConfiguration
37
     */
38
    private $pagesConfiguration;
39
40
    public function __construct(
41
        EntityManager $em,
42
        ACLPermissionCreatorService $aclPermissionCreatorService,
43
        Populator $populator,
44
        Slugifier $slugifier,
45
        PagesConfiguration $pagesConfiguration,
46
        string $userClass
47
    ) {
48
        $this->manager = $em;
49
        $this->nodeRepo = $em->getRepository('KunstmaanNodeBundle:Node');
50
        $this->nodeTranslationRepo = $em->getRepository('KunstmaanNodeBundle:NodeTranslation');
51
        $this->userRepo = $em->getRepository($userClass);
52
        $this->aclPermissionCreatorService = $aclPermissionCreatorService;
53
        $this->populator = $populator;
54
        $this->slugifier = $slugifier;
55
        $this->pagesConfiguration = $pagesConfiguration;
56
    }
57
58
    public function canBuild(Fixture $fixture)
59
    {
60
        if ($fixture->getEntity() instanceof HasNodeInterface) {
61
            return true;
62
        }
63
64
        return false;
65
    }
66
67
    public function preBuild(Fixture $fixture)
68
    {
69
        return;
70
    }
71
72
    public function postBuild(Fixture $fixture)
73
    {
74
        $entity = $fixture->getEntity();
75
        $fixtureParams = $fixture->getParameters();
76
        $translations = $fixture->getTranslations();
77 View Code Duplication
        if (empty($translations)) {
0 ignored issues
show
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...
78
            throw new \Exception('No translations detected for page fixture ' . $fixture->getName() . ' (' . $fixture->getClass() . ')');
79
        }
80
81
        $internalName = array_key_exists('page_internal_name', $fixtureParams) ?
82
            $fixtureParams['page_internal_name'] : null;
83
84
        $rootNode = null;
85
        foreach ($fixture->getTranslations() as $language => $data) {
86
            if ($rootNode === null) {
87
                $page = $entity;
88
                $rootNode = $this->createRootNode($page, $language, $internalName, $fixtureParams);
89
                $this->manager->persist($rootNode);
90
            } else {
91
                $cloned = clone $entity;
92
                $page = $cloned;
93
                $this->manager->persist($page);
94
            }
95
96
            // Create the translationNode.
97
            $translationNode = $this->createTranslationNode($rootNode, $language, $page);
98
            if (!$page instanceof StructureNode) {
99
                $translationNode->setOnline(isset($fixtureParams['set_online']) ? $fixtureParams['set_online'] : true);
100
            }
101
102
            $fixture->addAdditional($fixture->getName() . '_' . $language, $page);
103
            $fixture->addAdditional('translationNode_' . $language, $translationNode);
104
            $fixture->addAdditional('nodeVersion_' . $language, $translationNode->getPublicNodeVersion());
105
            $fixture->addAdditional('rootNode', $rootNode);
106
107
            $this->populator->populate($translationNode, $data);
108
            $this->populator->populate($page, $data);
109 View Code Duplication
            if ($translationNode->getSlug() === null && $rootNode->getParent() !== null) {
110
                $translationNode->setSlug($this->slugifier->slugify($translationNode->getTitle()));
111
            }
112
            $this->ensureUniqueUrl($translationNode, $page);
113
114
            $this->manager->persist($translationNode);
115
            $rootNode->addNodeTranslation($translationNode);
116
        }
117
118
        $this->manager->flush();
119
        $this->aclPermissionCreatorService->createPermission($rootNode);
0 ignored issues
show
It seems like $rootNode defined by null on line 84 can be null; however, Kunstmaan\NodeBundle\Hel...ice::createPermission() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
120
    }
121
122
    public function postFlushBuild(Fixture $fixture)
123
    {
124
        $entities = $fixture->getAdditionalEntities();
125
        $fixtureParams = $fixture->getParameters();
126
127
        foreach ($fixture->getTranslations() as $language => $data) {
128
            /** @var HasNodeInterface $page */
129
            $page = $entities[$fixture->getName() . '_' . $language];
130
            /** @var NodeTranslation $translationNode */
131
            $translationNode = $entities['translationNode_' . $language];
132
133
            $pagecreator = array_key_exists('creator', $fixtureParams) ? $fixtureParams['creator'] : 'pagecreator';
134
            $creator = $this->userRepo->findOneBy(array('username' => $pagecreator));
135
136
            $nodeVersion = new NodeVersion();
137
            $nodeVersion->setNodeTranslation($translationNode);
138
            $nodeVersion->setType('public');
139
            $nodeVersion->setOwner($creator);
0 ignored issues
show
$creator is of type object|null, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
140
            $nodeVersion->setRef($page);
141
142
            $translationNode->setPublicNodeVersion($nodeVersion);
143
144
            if (isset($fixtureParams['template'])) {
145
                $pageTemplateConfiguration = new PageTemplateConfiguration();
146
                $pageTemplateConfiguration->setPageId($page->getId());
147
                $pageTemplateConfiguration->setPageEntityName(ClassLookup::getClass($page));
148
                $pageTemplateConfiguration->setPageTemplate($fixtureParams['template']);
149
                $this->manager->persist($pageTemplateConfiguration);
150
            }
151
152
            $this->manager->persist($nodeVersion);
153
            $this->manager->persist($translationNode);
154
        }
155
        $this->manager->flush();
156
    }
157
158
    private function getParentNode($params, $language)
0 ignored issues
show
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
159
    {
160
        if (!isset($params['parent'])) {
161
            return;
162
        }
163
164
        $parent = $params['parent'];
165
        if ($parent instanceof Fixture) {
166
            $additionals = $parent->getAdditionalEntities();
167
            $parent = $additionals['rootNode'];
168
        } elseif (is_string($parent)) {
169
            $nodes = $this->nodeRepo->getNodesByInternalName($parent, $language, false, true);
170
            if (count($nodes) > 0) {
171
                $parent = $nodes[0];
172
            }
173
        }
174
175
        return $parent;
176
    }
177
178
    private function createRootNode($page, $language, $internalName, $fixtureParams)
179
    {
180
        $rootNode = new Node();
181
        $rootNode->setRef($page);
182
        $rootNode->setDeleted(false);
183
        $rootNode->setInternalName($internalName);
184
        $rootNode->setHiddenFromNav(
185
            isset($fixtureParams['hidden_from_nav']) ? $fixtureParams['hidden_from_nav'] : false
186
        );
187
        $parent = $this->getParentNode($fixtureParams, $language);
188
189
        if ($parent instanceof Node) {
190
            $rootNode->setParent($parent);
191
192
            if (!$this->canHaveChild($parent->getRefEntityName(), get_class($page))) {
193
                throw new \Exception(
194
                    sprintf('A %s can\'t have a %s as child. Forgot to add in allowed_children or getPossibleChildTypes?', $parent->getRefEntityName(), get_class($page))
195
                );
196
            }
197
        }
198
199
        return $rootNode;
200
    }
201
202
    private function createTranslationNode(Node $rootNode, $language, HasNodeInterface $page)
203
    {
204
        $translationNode = new NodeTranslation();
205
        $translationNode
206
            ->setNode($rootNode)
207
            ->setLang($language)
208
            ->setTitle($page->getTitle())
209
            ->setOnline(false)
210
            ->setWeight(0);
211
212
        return $translationNode;
213
    }
214
215
    private function ensureUniqueUrl(NodeTranslation $translation, HasNodeInterface $page)
216
    {
217
        if ($page instanceof StructureNode) {
218
            $translation->setSlug('');
219
            $translation->setUrl($translation->getFullSlug());
220
221
            return $translation;
222
        }
223
224
        $translation->setUrl($translation->getFullSlug());
225
226
        // Find all translations with this new URL, whose nodes are not deleted.
227
        $translationWithSameUrl = $this->nodeTranslationRepo->getNodeTranslationForUrl($translation->getUrl(), $translation->getLang(), false, $translation);
228
229
        if ($translationWithSameUrl instanceof NodeTranslation) {
230
            $translation->setSlug($this->slugifier->slugify($this->incrementString($translation->getSlug())));
231
            $this->ensureUniqueUrl($translation, $page);
232
        }
233
234
        return $translation;
235
    }
236
237 View Code Duplication
    private function incrementString($string, $append = '-v')
238
    {
239
        $finalDigitGrabberRegex = '/\d+$/';
240
        $matches = array();
241
242
        preg_match($finalDigitGrabberRegex, $string, $matches);
243
244
        if (count($matches) > 0) {
245
            $digit = (int) $matches[0];
246
            ++$digit;
247
248
            // Replace the integer with the new digit.
249
            return preg_replace($finalDigitGrabberRegex, $digit, $string);
250
        } else {
251
            return $string . $append . '1';
252
        }
253
    }
254
255
    /**
256
     * @param string $parentPageClass
257
     * @param string $childPageClass
258
     *
259
     * @return bool
260
     */
261
    private function canHaveChild($parentPageClass, $childPageClass)
262
    {
263
        $childTypes = $this->pagesConfiguration->getPossibleChildTypes($parentPageClass);
264
265
        foreach ($childTypes as $childType) {
266
            if ($childType['class'] == $childPageClass) {
267
                return true;
268
            }
269
        }
270
271
        return false;
272
    }
273
}
274