Completed
Push — master ( 91fdab...75a7b9 )
by
unknown
13:37
created

PageCreatorService::setContainer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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
36
    public function setEntityManager($entityManager)
37
    {
38
        $this->entityManager = $entityManager;
39
    }
40
41
    public function setACLPermissionCreatorService($aclPermissionCreatorService)
42
    {
43
        $this->aclPermissionCreatorService = $aclPermissionCreatorService;
44
    }
45
46
    public function setUserEntityClass($userEntityClass)
47
    {
48
        $this->userEntityClass = $userEntityClass;
49
    }
50
51
    /**
52
     * Sets the Container. This is still here for backwards compatibility.
53
     *
54
     * The ContainerAwareInterface has been removed so the container won't be injected automatically.
55
     * This function is just there for code that calls it manually.
56
     *
57
     * @param ContainerInterface $container A ContainerInterface instance.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $container not be null|ContainerInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
58
     *
59
     * @api
60
     */
61
    public function setContainer(ContainerInterface $container = null)
62
    {
63
        $this->setEntityManager($container->get('doctrine.orm.entity_manager'));
0 ignored issues
show
Bug introduced by
It seems like $container is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
64
        $this->setACLPermissionCreatorService($container->get('kunstmaan_node.acl_permission_creator_service'));
65
        $this->setUserEntityClass($container->getParameter('fos_user.model.user.class'));
66
    }
67
68
    /**
69
     * @param HasNodeInterface $pageTypeInstance The page.
70
     * @param array            $translations     Containing arrays. Sample:
71
     * [
72
     *  [   "language" => "nl",
73
     *      "callback" => function($page, $translation) {
74
     *          $translation->setTitle('NL titel');
75
     *      }
76
     *  ],
77
     *  [   "language" => "fr",
78
     *      "callback" => function($page, $translation) {
79
     *          $translation->setTitle('FR titel');
80
     *      }
81
     *  ]
82
     * ]
83
     * Perhaps it's cleaner when you create one array and append another array for each language.
84
     *
85
     * @param array            $options          Possible options:
86
     *      parent: type node, nodetransation or page.
87
     *      page_internal_name: string. name the page will have in the database.
88
     *      set_online: bool. if true the page will be set as online after creation.
89
     *      hidden_from_nav: bool. if true the page will not be show in the navigation
90
     *      creator: username
91
     *
92
     * Automatically calls the ACL + sets the slugs to empty when the page is an Abstract node.
93
     *
94
     * @return Node The new node for the page.
0 ignored issues
show
Documentation introduced by
Should the return type not be Node|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
95
     *
96
     * @throws \InvalidArgumentException
97
     */
98
    public function createPage(HasNodeInterface $pageTypeInstance, array $translations, array $options = array())
99
    {
100
        if (is_null($options)) {
101
            $options = array();
102
        }
103
104
        if (is_null($translations) || (count($translations) == 0)) {
105
            throw new \InvalidArgumentException('There has to be at least 1 translation in the translations array');
106
        }
107
108
        $em = $this->entityManager;
109
110
        /** @var NodeRepository $nodeRepo */
111
        $nodeRepo = $em->getRepository('KunstmaanNodeBundle:Node');
112
        /** @var $userRepo UserRepository */
113
        $userRepo = $em->getRepository($this->userEntityClass);
114
        /** @var $seoRepo SeoRepository */
115
        try {
116
            $seoRepo = $em->getRepository('KunstmaanSeoBundle:Seo');
117
        } catch (ORMException $e) {
118
            $seoRepo = null;
119
        }
120
121
        $pagecreator = array_key_exists('creator', $options) ? $options['creator'] : 'pagecreator';
122
        $creator     = $userRepo->findOneBy(array('username' => $pagecreator));
123
124
        $parent = isset($options['parent']) ? $options['parent'] : null;
125
126
        $pageInternalName = isset($options['page_internal_name']) ? $options['page_internal_name'] : null;
127
128
        $setOnline = isset($options['set_online']) ? $options['set_online'] : false;
129
130
        // We need to get the language of the first translation so we can create the rootnode.
131
        // This will also create a translationnode for that language attached to the rootnode.
132
        $first    = true;
133
        $rootNode = null;
134
135
        /* @var \Kunstmaan\NodeBundle\Repository\NodeTranslationRepository $nodeTranslationRepo*/
136
        $nodeTranslationRepo = $em->getRepository('KunstmaanNodeBundle:NodeTranslation');
137
138
        foreach ($translations as $translation) {
139
            $language = $translation['language'];
140
            $callback = $translation['callback'];
141
142
            $translationNode = null;
0 ignored issues
show
Unused Code introduced by
$translationNode is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
143
            if ($first) {
144
                $first = false;
145
146
                $em->persist($pageTypeInstance);
147
                $em->flush($pageTypeInstance);
148
149
                // Fetch the translation instead of creating it.
150
                // This returns the rootnode.
151
                $rootNode = $nodeRepo->createNodeFor($pageTypeInstance, $language, $creator, $pageInternalName);
0 ignored issues
show
Documentation introduced by
$creator is of type object|null, but the function expects a object<Kunstmaan\AdminBundle\Entity\BaseUser>.

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