GridApiContext::decode()   C
last analyzed

Complexity

Conditions 8
Paths 10

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
rs 5.7377
cc 8
eloc 15
nc 10
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Lug package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Lug\Bundle\GridBundle\Behat\Context;
13
14
use Behat\Behat\Context\Context;
15
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
16
use Lug\Component\Behat\Extension\Api\Context\ApiContext;
17
use Symfony\Component\Serializer\Encoder\ChainDecoder;
18
use Symfony\Component\Serializer\Encoder\DecoderInterface;
19
use Symfony\Component\Serializer\Encoder\JsonDecode;
20
use Symfony\Component\Serializer\Encoder\XmlEncoder;
21
22
/**
23
 * @author GeLo <[email protected]>
24
 */
25
class GridApiContext implements Context
26
{
27
    /**
28
     * @var ApiContext
29
     */
30
    private $apiContext;
31
32
    /**
33
     * @var DecoderInterface
34
     */
35
    private $decoder;
36
37
    /**
38
     * @BeforeScenario
39
     */
40
    public function init(BeforeScenarioScope $scope)
41
    {
42
        $this->apiContext = $scope->getEnvironment()->getContext(ApiContext::class);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Testwork\Environment\Environment as the method getContext() does only exist in the following implementations of said interface: Behat\Behat\Context\Envi...lizedContextEnvironment.

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...
43
44
        $this->decoder = new ChainDecoder([
45
            new JsonDecode(true),
46
            new XmlEncoder('result'),
47
        ]);
48
    }
49
50
    /**
51
     * @param string $property
52
     * @param string $sort
53
     * @param string $format
54
     *
55
     * @Given the ":format" response should be sorted by ":property" ":sort"
56
     */
57
    public function assertSorting($property, $sort, $format)
58
    {
59
        $data = $sortedData = $this->decodeByProperty($property, $format);
60
61
        array_multisort($sortedData, $sort === 'ASC' ? SORT_ASC : SORT_DESC, SORT_STRING | SORT_FLAG_CASE);
62
63
        \PHPUnit_Framework_Assert::assertSame(
64
            $sortedData,
65
            $data,
66
            sprintf(
67
                'The sorting does not match for the property "%s". Expected "%s", got "%s".',
68
                $property,
69
                json_encode($sortedData),
70
                json_encode($data)
71
            )
72
        );
73
    }
74
75
    /**
76
     * @param string $property
77
     * @param string $values
78
     * @param string $format
79
     *
80
     * @Given the ":format" response should be filtered by ":property" ":values"
81
     */
82
    public function assertResponseFiltering($property, $values, $format)
83
    {
84
        \PHPUnit_Framework_Assert::assertSame(
85
            $expected = !empty($values) ? array_map('trim', explode(';', $values)) : [],
86
            $data = $this->decodeByProperty($property, $format),
87
            sprintf(
88
                'The filtering does not match for the property "%s". Expected "%s", got "%s".',
89
                $property,
90
                json_encode($expected),
91
                json_encode($data)
92
            )
93
        );
94
    }
95
96
    /**
97
     * @param string $property
98
     * @param string $format
99
     *
100
     * @return mixed[]
101
     */
102
    private function decodeByProperty($property, $format)
103
    {
104
        return array_map(function ($entry) use ($property) {
105
            \PHPUnit_Framework_Assert::assertInternalType('array', $entry);
106
            \PHPUnit_Framework_Assert::assertArrayHasKey($property, $entry);
107
108
            return $entry[$property];
109
        }, $this->decode($format));
110
    }
111
112
    /**
113
     * @param $format
114
     *
115
     * @return array|mixed
116
     */
117
    private function decode($format)
118
    {
119
        $data = $this->decoder->decode((string) $this->apiContext->getResponse()->getBody(), $format);
120
121
        if ($format === 'json' && isset($data['_embedded']['items'])) {
122
            $data = $data['_embedded']['items'];
123
        }
124
125
        if ($format === 'xml') {
126
            if (!empty($data) && isset($data['entry'])) {
127
                if (is_int(key($data['entry']))) {
128
                    $data = $data['entry'];
129
                } elseif (isset($data['entry']['@rel'])) {
130
                    $data = array_pop($data['entry']);
131
                } else {
132
                    $data = [$data['entry']];
133
                }
134
            } else {
135
                $data = [];
136
            }
137
        }
138
139
        return $data;
140
    }
141
}
142