Completed
Push — EZP-31644 ( 47e85b )
by
unknown
17:57
created

testRendererControllerReferenceWithCompoundMatcher()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 48

Duplication

Lines 9
Ratio 18.75 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 9
loc 48
rs 9.1344
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
5
 * @license For full copyright and license information view LICENSE file distributed with this source code.
6
 */
7
namespace eZ\Bundle\EzPublishCoreBundle\Tests\Fragment;
8
9
use eZ\Bundle\EzPublishCoreBundle\Fragment\DecoratedFragmentRenderer;
10
use eZ\Publish\Core\MVC\Symfony\Component\Serializer\SerializerTrait;
11
use eZ\Publish\Core\MVC\Symfony\SiteAccess;
12
use PHPUnit\Framework\TestCase;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpKernel\Controller\ControllerReference;
15
use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
16
use Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer;
17
18
class DecoratedFragmentRendererTest extends TestCase
19
{
20
    use SerializerTrait;
21
22
    /** @var \PHPUnit\Framework\MockObject\MockObject */
23
    protected $innerRenderer;
24
25
    protected function setUp()
26
    {
27
        parent::setUp();
28
        $this->innerRenderer = $this->createMock(FragmentRendererInterface::class);
29
    }
30
31
    public function testSetFragmentPathNotRoutableRenderer()
32
    {
33
        $matcher = $this->createMock(SiteAccess\URILexer::class);
34
        $siteAccess = new SiteAccess('test', 'test', $matcher);
35
        $matcher
36
            ->expects($this->never())
37
            ->method('analyseLink');
38
39
        $renderer = new DecoratedFragmentRenderer($this->innerRenderer);
40
        $renderer->setSiteAccess($siteAccess);
41
        $renderer->setFragmentPath('foo');
42
    }
43
44
    public function testSetFragmentPath()
45
    {
46
        $matcher = $this->createMock(SiteAccess\URILexer::class);
47
        $siteAccess = new SiteAccess('test', 'test', $matcher);
48
        $matcher
49
            ->expects($this->once())
50
            ->method('analyseLink')
51
            ->with('/foo')
52
            ->will($this->returnValue('/bar/foo'));
53
54
        $innerRenderer = $this->createMock(RoutableFragmentRenderer::class);
55
        $innerRenderer
56
            ->expects($this->once())
57
            ->method('setFragmentPath')
58
            ->with('/bar/foo');
59
        $renderer = new DecoratedFragmentRenderer($innerRenderer);
60
        $renderer->setSiteAccess($siteAccess);
61
        $renderer->setFragmentPath('/foo');
62
    }
63
64
    public function testGetName()
65
    {
66
        $name = 'test';
67
        $this->innerRenderer
68
            ->expects($this->once())
69
            ->method('getName')
70
            ->will($this->returnValue($name));
71
72
        $renderer = new DecoratedFragmentRenderer($this->innerRenderer);
73
        $this->assertSame($name, $renderer->getName());
74
    }
75
76
    public function testRendererAbsoluteUrl()
77
    {
78
        $url = 'http://phoenix-rises.fm/foo/bar';
79
        $request = new Request();
80
        $options = ['foo' => 'bar'];
81
        $expectedReturn = '/_fragment?foo=bar';
82
        $this->innerRenderer
83
            ->expects($this->once())
84
            ->method('render')
85
            ->with($url, $request, $options)
86
            ->will($this->returnValue($expectedReturn));
87
88
        $renderer = new DecoratedFragmentRenderer($this->innerRenderer);
89
        $this->assertSame($expectedReturn, $renderer->render($url, $request, $options));
90
    }
91
92
    public function testRendererControllerReference()
93
    {
94
        $reference = new ControllerReference('FooBundle:bar:baz');
95
        $matcher = new SiteAccess\Matcher\URIElement(1);
96
        $siteAccess = new SiteAccess(
97
            'test',
98
            'test',
99
            $matcher
100
        );
101
        $request = new Request();
102
        $request->attributes->set('siteaccess', $siteAccess);
103
        $options = ['foo' => 'bar'];
104
        $expectedReturn = '/_fragment?foo=bar';
105
        $this->innerRenderer
106
            ->expects($this->once())
107
            ->method('render')
108
            ->with($reference, $request, $options)
109
            ->will($this->returnValue($expectedReturn));
110
111
        $renderer = new DecoratedFragmentRenderer($this->innerRenderer);
112
        $this->assertSame($expectedReturn, $renderer->render($reference, $request, $options));
113
        $this->assertTrue(isset($reference->attributes['serialized_siteaccess']));
114
        $serializedSiteAccess = json_encode($siteAccess);
115
        $this->assertSame($serializedSiteAccess, $reference->attributes['serialized_siteaccess']);
116
        $this->assertTrue(isset($reference->attributes['serialized_siteaccess_matcher']));
117
        $this->assertSame(
118
            $this->getSerializer()->serialize(
119
                $siteAccess->matcher,
120
                'json'
121
            ),
122
            $reference->attributes['serialized_siteaccess_matcher']
123
        );
124
    }
125
126
    public function testRendererControllerReferenceWithCompoundMatcher()
127
    {
128
        $reference = new ControllerReference('FooBundle:bar:baz');
129
        $compoundMatcher = new SiteAccess\Matcher\Compound\LogicalAnd([]);
130
        $subMatchers = [
131
            'Map\URI' => new SiteAccess\Matcher\Map\URI([]),
132
            'Map\Host' => new SiteAccess\Matcher\Map\Host([]),
133
        ];
134
        $compoundMatcher->setSubMatchers($subMatchers);
135
        $siteAccess = new SiteAccess(
136
            'test',
137
            'test',
138
            $compoundMatcher
139
        );
140
        $request = new Request();
141
        $request->attributes->set('siteaccess', $siteAccess);
142
        $options = ['foo' => 'bar'];
143
        $expectedReturn = '/_fragment?foo=bar';
144
        $this->innerRenderer
145
            ->expects($this->once())
146
            ->method('render')
147
            ->with($reference, $request, $options)
148
            ->will($this->returnValue($expectedReturn));
149
150
        $renderer = new DecoratedFragmentRenderer($this->innerRenderer);
151
        $this->assertSame($expectedReturn, $renderer->render($reference, $request, $options));
152
        $this->assertTrue(isset($reference->attributes['serialized_siteaccess']));
153
        $serializedSiteAccess = json_encode($siteAccess);
154
        $this->assertSame($serializedSiteAccess, $reference->attributes['serialized_siteaccess']);
155
        $this->assertTrue(isset($reference->attributes['serialized_siteaccess_matcher']));
156
        $this->assertSame(
157
            $this->getSerializer()->serialize(
158
                $siteAccess->matcher,
159
                'json'
160
            ),
161
            $reference->attributes['serialized_siteaccess_matcher']
162
        );
163
        $this->assertTrue(isset($reference->attributes['serialized_siteaccess_sub_matchers']));
164 View Code Duplication
        foreach ($siteAccess->matcher->getSubMatchers() as $subMatcher) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface eZ\Publish\Core\MVC\Symfony\SiteAccess\Matcher as the method getSubMatchers() does only exist in the following implementations of said interface: eZ\Publish\Core\MVC\Symf...Access\Matcher\Compound, eZ\Publish\Core\MVC\Symf...her\Compound\LogicalAnd, eZ\Publish\Core\MVC\Symf...cher\Compound\LogicalOr.

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...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
165
            $this->assertSame(
166
                $this->getSerializer()->serialize(
167
                    $subMatcher,
168
                    'json'
169
                ),
170
                $reference->attributes['serialized_siteaccess_sub_matchers'][get_class($subMatcher)]
171
            );
172
        }
173
    }
174
}
175