TwigFormulaLoader::load()   A
last analyzed

Complexity

Conditions 3
Paths 5

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 15
ccs 0
cts 13
cp 0
rs 9.4285
cc 3
eloc 9
nc 5
nop 1
crap 12
1
<?php
2
namespace Boekkooi\Bundle\TwigJackBundle\Assetic;
3
4
use Assetic\Extension\Twig\AsseticFilterFunction;
5
use Assetic\Extension\Twig\AsseticNode;
6
use Assetic\Factory\Loader\FormulaLoaderInterface;
7
use Assetic\Factory\Resource\ResourceInterface;
8
use Psr\Log\LoggerInterface;
9
10
/**
11
 * @author Warnar Boekkooi <[email protected]>
12
 */
13
class TwigFormulaLoader implements FormulaLoaderInterface
14
{
15
    private $twig;
16
    private $logger;
17
18
    public function __construct(\Twig_Environment $twig, LoggerInterface $logger = null)
19
    {
20
        $this->twig = $twig;
21
        $this->logger = $logger;
22
    }
23
24
    public function load(ResourceInterface $resource)
25
    {
26
        try {
27
            $tokens = $this->twig->tokenize($resource->getContent(), (string) $resource);
28
            $nodes  = $this->twig->parse($tokens);
29
        } catch (\Exception $e) {
30
            if ($this->logger) {
31
                $this->logger->error(sprintf('The template "%s" contains an error: %s', $resource, $e->getMessage()));
32
            }
33
34
            return array();
35
        }
36
37
        return $this->loadNode($nodes);
0 ignored issues
show
Bug introduced by
It seems like $nodes defined by $this->twig->parse($tokens) on line 28 can be null; however, Boekkooi\Bundle\TwigJack...rmulaLoader::loadNode() 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...
38
    }
39
40
    /**
41
     * Loads assets from the supplied node.
42
     *
43
     * @param \Twig_Node $node
44
     *
45
     * @return array An array of asset formulae indexed by name
46
     */
47
    private function loadNode(\Twig_Node $node)
48
    {
49
        $formulae = array();
50
51
        if ($node instanceof AsseticNode) {
52
            $formulae[$node->getAttribute('name')] = array(
53
                $node->getAttribute('inputs'),
54
                $node->getAttribute('filters'),
55
                array(
56
                    'output'  => $node->getAttribute('asset')->getTargetPath(),
57
                    'name'    => $node->getAttribute('name'),
58
                    'debug'   => $node->getAttribute('debug'),
59
                    'combine' => $node->getAttribute('combine'),
60
                    'vars'    => $node->getAttribute('vars'),
61
                ),
62
            );
63
        } elseif ($node instanceof \Twig_Node_Expression_Function) {
64
            $name = version_compare(\Twig_Environment::VERSION, '1.2.0-DEV', '<')
65
                ? $node->getNode('name')->getAttribute('name')
66
                : $node->getAttribute('name');
67
68
            if ($this->twig->getFunction($name) instanceof AsseticFilterFunction) {
69
                $arguments = array();
70
                foreach ($node->getNode('arguments') as $argument) {
71
                    $arguments[] = eval('return '.$this->twig->compile($argument).';');
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
72
                }
73
74
                /** @var \Assetic\Extension\Twig\AsseticFilterInvoker $invoker */
75
                $invoker = $this->twig->getExtension('assetic')->getFilterInvoker($name);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Twig_ExtensionInterface as the method getFilterInvoker() does only exist in the following implementations of said interface: Assetic\Extension\Twig\AsseticExtension, Symfony\Bundle\AsseticBundle\Twig\AsseticExtension.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
76
77
                $inputs  = isset($arguments[0]) ? (array) $arguments[0] : array();
78
                $filters = $invoker->getFilters();
79
                $options = array_replace($invoker->getOptions(), isset($arguments[1]) ? $arguments[1] : array());
80
81
                if (!isset($options['name'])) {
82
                    $options['name'] = $invoker->getFactory()->generateAssetName($inputs, $filters, $options);
83
                }
84
85
                $formulae[$options['name']] = array($inputs, $filters, $options);
86
            }
87
        }
88
89
        foreach ($node as $child) {
90
            if ($child instanceof \Twig_Node) {
91
                $formulae += $this->loadNode($child);
92
            }
93
        }
94
95
        if ($node->hasAttribute('embedded_templates')) {
96
            foreach ($node->getAttribute('embedded_templates') as $child) {
97
                $formulae += $this->loadNode($child);
98
            }
99
        }
100
101
        // We need to also check the parent since else it won't get parsed
102
        if ($node->hasNode('parent') && $node->getNode('parent') instanceof \Twig_Node_Expression_Constant) {
103
            $parent = $node->getNode('parent')->getAttribute('value');
104
            if ($parent[0] === '!') {
105
                $source = $this->twig->getLoader()->getSource($parent);
106
                $tokens = $this->twig->tokenize($source, $parent);
107
                $nodes  = $this->twig->parse($tokens);
108
109
                $formulae += $this->loadNode($nodes);
0 ignored issues
show
Bug introduced by
It seems like $nodes defined by $this->twig->parse($tokens) on line 107 can be null; however, Boekkooi\Bundle\TwigJack...rmulaLoader::loadNode() 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...
110
            }
111
        }
112
113
        return $formulae;
114
    }
115
}
116