Completed
Push — master ( cb2703...d9d040 )
by Tobias
12:13
created

TranslationExtension::getNodeVisitors()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 0
crap 2
1
<?php
2
3
/*
4
 * This file is part of the PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Translation\Bundle\Twig;
13
14
use Symfony\Component\Translation\TranslatorInterface;
15
use Translation\Bundle\Twig\Visitor\DefaultApplyingNodeVisitor;
16
use Translation\Bundle\Twig\Visitor\NormalizingNodeVisitor;
17
use Translation\Bundle\Twig\Visitor\RemovingNodeVisitor;
18
19
/**
20
 * @author Johannes M. Schmitt <[email protected]>
21
 * @author Tobias Nyholm <[email protected]>
22
 */
23
final class TranslationExtension extends \Twig_Extension
24
{
25
    /**
26
     * @var TranslatorInterface
27
     */
28
    private $translator;
29
30
    /**
31
     * @var bool
32
     */
33
    private $debug;
34
35
    /**
36
     * @param TranslatorInterface $translator
37
     * @param bool                $debug
38
     */
39 11
    public function __construct(TranslatorInterface $translator, $debug = false)
40
    {
41 11
        $this->translator = $translator;
42 11
        $this->debug = $debug;
43 11
    }
44
45
    /**
46
     * @return array
47
     */
48 8
    public function getFilters()
49
    {
50
        return [
51 8
            new \Twig_SimpleFilter('desc', [$this, 'desc']),
52 8
            new \Twig_SimpleFilter('meaning', [$this, 'meaning']),
53
        ];
54
    }
55
56
    /**
57
     * @return array
58
     */
59 8
    public function getNodeVisitors()
60
    {
61
        $visitors = [
62 8
            new NormalizingNodeVisitor(),
63 8
            new RemovingNodeVisitor(),
64
        ];
65
66 8
        if ($this->debug) {
67 6
            $visitors[] = new DefaultApplyingNodeVisitor();
68
        }
69
70 8
        return $visitors;
71
    }
72
73
    /**
74
     * @param string      $message
75
     * @param string      $defaultMessage
76
     * @param int         $count
77
     * @param array       $arguments
78
     * @param null|string $domain
79
     * @param null|string $locale
80
     *
81
     * @return string
82
     */
83
    public function transchoiceWithDefault($message, $defaultMessage, $count, array $arguments = [], $domain = null, $locale = null)
84
    {
85
        if (null === $domain) {
86
            $domain = 'messages';
87
        }
88
89
        if (false === $this->translator->getCatalogue($locale)->defines($message, $domain)) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Translation\TranslatorInterface as the method getCatalogue() does only exist in the following implementations of said interface: Symfony\Bundle\Framework...slatorWithInvalidLocale, Symfony\Bundle\Framework...\Translation\Translator, Symfony\Component\Transl...DataCollectorTranslator, Symfony\Component\Translation\LoggingTranslator, Symfony\Component\Translation\Translator, Translation\Bundle\Trans...r\EditInPlaceTranslator, Translation\Bundle\Translator\FallbackTranslator.

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...
90
            return $this->translator->transChoice($defaultMessage, $count, array_merge(['%count%' => $count], $arguments), $domain, $locale);
91
        }
92
93
        return $this->translator->transChoice($message, $count, array_merge(['%count%' => $count], $arguments), $domain, $locale);
94
    }
95
96
    /**
97
     * @param $v
98
     *
99
     * @return mixed
100
     */
101
    public function desc($v)
102
    {
103
        return $v;
104
    }
105
106
    /**
107
     * @param $v
108
     *
109
     * @return mixed
110
     */
111
    public function meaning($v)
112
    {
113
        return $v;
114
    }
115
116
    public function getName()
117
    {
118
        return 'php-translation';
119
    }
120
}
121