Completed
Push — master ( 9e1211...19df0f )
by Benjamin
02:32
created

BlockHelper   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 63
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B loadBlock() 0 34 5
A getContentTypeFromNodeElementClass() 0 8 3
1
<?php
2
3
namespace Alpixel\Bundle\CMSBundle\Helper;
4
5
use Alpixel\Bundle\CMSBundle\Entity\Block;
6
use Alpixel\Bundle\CMSBundle\Entity\Node;
7
use Doctrine\ORM\EntityManager;
8
use Symfony\Component\HttpFoundation\RequestStack;
9
10
class BlockHelper
11
{
12
    protected $entityManager;
13
    protected $blocks;
14
    protected $request;
15
16
    public function __construct(RequestStack $requestStack, EntityManager $entityManager, $blocks)
17
    {
18
        $this->request = $requestStack->getMasterRequest();
19
        $this->entityManager = $entityManager;
20
        $this->blocks = $blocks;
21
    }
22
23
    /**
24
     * @param $blockType
25
     * @param null $locale
26
     * @return Block|null
27
     */
28
    public function loadBlock($blockType, $locale = null)
29
    {
30
        if (!isset($this->blocks[$blockType])) {
31
            return null;
32
        }
33
34
        if ($locale === null) {
35
            $locale = $this->request->getLocale();
36
        }
37
38
        $block = $this
39
            ->entityManager
40
            ->getRepository('AlpixelCMSBundle:Block')
41
            ->findBlock($blockType, $locale);
42
43
        if ($block === null) {
44
            $blockConf = $this->blocks[$blockType];
45
46
            $block = new $blockConf['class'];
47
            $block->setName($blockConf['title']);
48
49
            foreach ($blockConf['default'] as $key => $value) {
50
                $block->{$key} = $value;
51
            }
52
53
            $block->setLocale($locale);
54
            $block->setSlug($blockType);
55
56
            $this->entityManager->persist($block);
57
            $this->entityManager->flush();
58
        }
59
60
        return $block;
61
    }
62
63
64
    public function getContentTypeFromNodeElementClass(Block $object)
65
    {
66
        foreach ($this->blocks as $block) {
67
            if ($block['class'] == get_class($object)) {
68
                return $block;
69
            }
70
        }
71
    }
72
}
73