Completed
Push — master ( ba8ed9...770316 )
by Jeroen
06:11
created

ConfigBundle/Twig/ConfigTwigExtension.php (1 issue)

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\ConfigBundle\Twig;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Kunstmaan\ConfigBundle\Entity\AbstractConfig;
7
use Twig_Extension;
8
9
/**
10
 * Extension to fetch config
11
 */
12
class ConfigTwigExtension extends Twig_Extension
13
{
14
    /**
15
     * @var EntityManagerInterface
16
     */
17
    private $em;
18
19
    /**
20
     * @var array
21
     */
22
    private $configuration;
23
24
    /**
25
     * @var array
26
     */
27
    private $configs = array();
28
29
    /**
30
     * @param \Doctrine\ORM\EntityManagerInterface $em
31
     */
32
    public function __construct(EntityManagerInterface $em, $configuration)
33
    {
34
        $this->em = $em;
35
        $this->configuration = $configuration;
36
    }
37
38
    /**
39
     * Returns a list of functions to add to the existing list.
40
     *
41
     * @return array An array of functions
0 ignored issues
show
Consider making the return type a bit more specific; maybe use \Twig_SimpleFunction[].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
42
     */
43
    public function getFunctions()
44
    {
45
        return array(
46
            new \Twig_SimpleFunction(
47
                'get_config_by_internal_name', array($this, 'getConfigByInternalName')
48
            ),
49
        );
50
    }
51
52
    /**
53
     * @param string $internalName Internal name of the site config entity
54
     *
55
     * @return AbstractConfig
56
     */
57
    public function getConfigByInternalName($internalName)
58
    {
59
        if (\in_array($internalName, $this->configs)) {
60
            return $this->configs[$internalName];
61
        }
62
63
        foreach ($this->configuration['entities'] as $class) {
64
            $entity = new $class();
65
66
            if ($entity->getInternalName() == $internalName) {
67
                $repo = $this->em->getRepository($class);
68
                $config = $repo->findOneBy(array());
69
70
                $this->configs[$internalName] = $config;
71
72
                return $config;
73
            }
74
        }
75
76
        return null;
77
    }
78
}
79