Completed
Push — master ( aba493...5356ed )
by Ruud
315:38 queued 305:00
created

NodeBundle/Helper/Services/PageCreatorService.php (1 issue)

Check for possible nulls passed with expressions.

Bug Minor

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\NodeBundle\Helper\Services;
4
5
use Doctrine\ORM\EntityManager;
6
use Doctrine\ORM\ORMException;
7
use Kunstmaan\AdminBundle\Repository\UserRepository;
8
use Kunstmaan\NodeBundle\Entity\HasNodeInterface;
9
use Kunstmaan\NodeBundle\Entity\Node;
10
use Kunstmaan\NodeBundle\Repository\NodeRepository;
11
use Kunstmaan\PagePartBundle\Helper\HasPagePartsInterface;
12
use Kunstmaan\SeoBundle\Repository\SeoRepository;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
15
/**
16
 * Service to create new pages.
17
 */
18
class PageCreatorService
19
{
20
    /**
21
     * @var EntityManager
22
     */
23
    protected $entityManager;
24
25
    /**
26
     * @var ACLPermissionCreatorService
27
     */
28
    protected $aclPermissionCreatorService;
29
30
    /**
31
     * @var string
32
     */
33
    protected $userEntityClass;
34
35
    public function setEntityManager($entityManager)
36
    {
37
        $this->entityManager = $entityManager;
38
    }
39
40
    public function setACLPermissionCreatorService($aclPermissionCreatorService)
41
    {
42
        $this->aclPermissionCreatorService = $aclPermissionCreatorService;
43
    }
44
45
    public function setUserEntityClass($userEntityClass)
46
    {
47
        $this->userEntityClass = $userEntityClass;
48
    }
49
50
    /**
51
     * Sets the Container. This is still here for backwards compatibility.
52
     *
53
     * The ContainerAwareInterface has been removed so the container won't be injected automatically.
54
     * This function is just there for code that calls it manually.
55
     *
56
     * @param ContainerInterface $container a ContainerInterface instance
57
     *
58
     * @api
59
     */
60
    public function setContainer(ContainerInterface $container = null)
61
    {
62
        $this->setEntityManager($container->get('doctrine.orm.entity_manager'));
63
        $this->setACLPermissionCreatorService($container->get('kunstmaan_node.acl_permission_creator_service'));
64
        $this->setUserEntityClass($container->getParameter('fos_user.model.user.class'));
65
    }
66
67
    /**
68
     * @param HasNodeInterface $pageTypeInstance the page
69
     * @param array            $translations     Containing arrays. Sample:
70
     *                                           [
71
     *                                           [   "language" => "nl",
72
     *                                           "callback" => function($page, $translation) {
73
     *                                           $translation->setTitle('NL titel');
74
     *                                           }
75
     *                                           ],
76
     *                                           [   "language" => "fr",
77
     *                                           "callback" => function($page, $translation) {
78
     *                                           $translation->setTitle('FR titel');
79
     *                                           }
80
     *                                           ]
81
     *                                           ]
82
     *                                           Perhaps it's cleaner when you create one array and append another array for each language.
83
     * @param array            $options          Possible options:
84
     *                                           parent: type node, nodetransation or page.
85
     *                                           page_internal_name: string. name the page will have in the database.
86
     *                                           set_online: bool. if true the page will be set as online after creation.
87
     *                                           hidden_from_nav: bool. if true the page will not be show in the navigation
88
     *                                           creator: username
89
     *
90
     * Automatically calls the ACL + sets the slugs to empty when the page is an Abstract node.
91
     *
92
     * @return Node the new node for the page
93
     *
94
     * @throws \InvalidArgumentException
95
     */
96
    public function createPage(HasNodeInterface $pageTypeInstance, array $translations, array $options = array())
97
    {
98
        if (\is_null($options)) {
99
            $options = array();
100
        }
101
102
        if (\is_null($translations) || (\count($translations) == 0)) {
103
            throw new \InvalidArgumentException('There has to be at least 1 translation in the translations array');
104
        }
105
106
        $em = $this->entityManager;
107
108
        /** @var NodeRepository $nodeRepo */
109
        $nodeRepo = $em->getRepository('KunstmaanNodeBundle:Node');
110
        /** @var UserRepository $userRepo */
111
        $userRepo = $em->getRepository($this->userEntityClass);
112
        /* @var SeoRepository $seoRepo */
113
        try {
114
            $seoRepo = $em->getRepository('KunstmaanSeoBundle:Seo');
115
        } catch (ORMException $e) {
116
            $seoRepo = null;
117
        }
118
119
        $pagecreator = \array_key_exists('creator', $options) ? $options['creator'] : 'pagecreator';
120
121
        if ($pagecreator instanceof $this->userEntityClass) {
122
            $creator = $pagecreator;
123
        } else {
124
            $creator = $userRepo->findOneBy(array('username' => $pagecreator));
125
        }
126
127
        $parent = isset($options['parent']) ? $options['parent'] : null;
128
129
        $pageInternalName = isset($options['page_internal_name']) ? $options['page_internal_name'] : null;
130
131
        $setOnline = isset($options['set_online']) ? $options['set_online'] : false;
132
133
        // We need to get the language of the first translation so we can create the rootnode.
134
        // This will also create a translationnode for that language attached to the rootnode.
135
        $first = true;
136
        $rootNode = null;
137
138
        /* @var \Kunstmaan\NodeBundle\Repository\NodeTranslationRepository $nodeTranslationRepo*/
139
        $nodeTranslationRepo = $em->getRepository('KunstmaanNodeBundle:NodeTranslation');
140
141
        foreach ($translations as $translation) {
142
            $language = $translation['language'];
143
            $callback = $translation['callback'];
144
145
            $translationNode = null;
146
            if ($first) {
147
                $first = false;
148
149
                $em->persist($pageTypeInstance);
150
                $em->flush($pageTypeInstance);
151
152
                // Fetch the translation instead of creating it.
153
                // This returns the rootnode.
154
                $rootNode = $nodeRepo->createNodeFor($pageTypeInstance, $language, $creator, $pageInternalName);
155
156
                if (\array_key_exists('hidden_from_nav', $options)) {
157
                    $rootNode->setHiddenFromNav($options['hidden_from_nav']);
158
                }
159
160
                if (!\is_null($parent)) {
161
                    if ($parent instanceof HasPagePartsInterface) {
162
                        $parent = $nodeRepo->getNodeFor($parent);
163
                    }
164
                    $rootNode->setParent($parent);
165
                }
166
167
                $em->persist($rootNode);
168
                $em->flush($rootNode);
169
170
                $translationNode = $rootNode->getNodeTranslation($language, true);
171
            } else {
172
                // Clone the $pageTypeInstance.
173
                $pageTypeInstance = clone $pageTypeInstance;
174
175
                $em->persist($pageTypeInstance);
176
                $em->flush($pageTypeInstance);
177
178
                // Create the translationnode.
179
                $translationNode = $nodeTranslationRepo->createNodeTranslationFor($pageTypeInstance, $language, $rootNode, $creator);
180
            }
181
182
            // Make SEO.
183
            $seo = null;
184
185
            if (!\is_null($seoRepo)) {
186
                $seo = $seoRepo->findOrCreateFor($pageTypeInstance);
187
            }
188
189
            $callback($pageTypeInstance, $translationNode, $seo);
190
191
            // Overwrite the page title with the translated title
192
            $pageTypeInstance->setTitle($translationNode->getTitle());
193
            $em->persist($pageTypeInstance);
194
            $em->persist($translationNode);
195
            $em->flush($pageTypeInstance);
196
            $em->flush($translationNode);
197
198
            $translationNode->setOnline($setOnline);
199
200
            if (!\is_null($seo)) {
201
                $em->persist($seo);
202
                $em->flush($seo);
203
            }
204
205
            $em->persist($translationNode);
206
            $em->flush($translationNode);
207
        }
208
209
        // ACL
210
        $this->aclPermissionCreatorService->createPermission($rootNode);
0 ignored issues
show
It seems like $rootNode defined by null on line 136 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...
211
212
        return $rootNode;
213
    }
214
}
215