Completed
Push — master ( 1de9b7...830752 )
by Kristof
38:46 queued 24:09
created

NodeBundle/Helper/Services/PageCreatorService.php (2 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\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 $userRepo UserRepository */
111
        $userRepo = $em->getRepository($this->userEntityClass);
112
        /* @var $seoRepo SeoRepository */
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
        $creator = $userRepo->findOneBy(array('username' => $pagecreator));
121
122
        $parent = isset($options['parent']) ? $options['parent'] : null;
123
124
        $pageInternalName = isset($options['page_internal_name']) ? $options['page_internal_name'] : null;
125
126
        $setOnline = isset($options['set_online']) ? $options['set_online'] : false;
127
128
        // We need to get the language of the first translation so we can create the rootnode.
129
        // This will also create a translationnode for that language attached to the rootnode.
130
        $first = true;
131
        $rootNode = null;
132
133
        /* @var \Kunstmaan\NodeBundle\Repository\NodeTranslationRepository $nodeTranslationRepo*/
134
        $nodeTranslationRepo = $em->getRepository('KunstmaanNodeBundle:NodeTranslation');
135
136
        foreach ($translations as $translation) {
137
            $language = $translation['language'];
138
            $callback = $translation['callback'];
139
140
            $translationNode = null;
141
            if ($first) {
142
                $first = false;
143
144
                $em->persist($pageTypeInstance);
145
                $em->flush($pageTypeInstance);
146
147
                // Fetch the translation instead of creating it.
148
                // This returns the rootnode.
149
                $rootNode = $nodeRepo->createNodeFor($pageTypeInstance, $language, $creator, $pageInternalName);
150
151
                if (array_key_exists('hidden_from_nav', $options)) {
152
                    $rootNode->setHiddenFromNav($options['hidden_from_nav']);
153
                }
154
155
                if (!is_null($parent)) {
156
                    if ($parent instanceof HasPagePartsInterface) {
157
                        $parent = $nodeRepo->getNodeFor($parent);
0 ignored issues
show
$parent is of type object<Kunstmaan\PagePar...\HasPagePartsInterface>, but the function expects a object<Kunstmaan\NodeBun...ntity\HasNodeInterface>.

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...
158
                    }
159
                    $rootNode->setParent($parent);
160
                }
161
162
                $em->persist($rootNode);
163
                $em->flush($rootNode);
164
165
                $translationNode = $rootNode->getNodeTranslation($language, true);
166
            } else {
167
                // Clone the $pageTypeInstance.
168
                $pageTypeInstance = clone $pageTypeInstance;
169
170
                $em->persist($pageTypeInstance);
171
                $em->flush($pageTypeInstance);
172
173
                // Create the translationnode.
174
                $translationNode = $nodeTranslationRepo->createNodeTranslationFor($pageTypeInstance, $language, $rootNode, $creator);
175
            }
176
177
            // Make SEO.
178
            $seo = null;
179
180
            if (!is_null($seoRepo)) {
181
                $seo = $seoRepo->findOrCreateFor($pageTypeInstance);
182
            }
183
184
            $callback($pageTypeInstance, $translationNode, $seo);
185
186
            // Overwrite the page title with the translated title
187
            $pageTypeInstance->setTitle($translationNode->getTitle());
188
            $em->persist($pageTypeInstance);
189
            $em->persist($translationNode);
190
            $em->flush($pageTypeInstance);
191
            $em->flush($translationNode);
192
193
            $translationNode->setOnline($setOnline);
194
195
            if (!is_null($seo)) {
196
                $em->persist($seo);
197
                $em->flush($seo);
198
            }
199
200
            $em->persist($translationNode);
201
            $em->flush($translationNode);
202
        }
203
204
        // ACL
205
        $this->aclPermissionCreatorService->createPermission($rootNode);
0 ignored issues
show
It seems like $rootNode defined by null on line 131 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...
206
207
        return $rootNode;
208
    }
209
}
210