Passed
Push — master ( c39fb6...9e9a0d )
by Rafael
04:42
created

GraphQLHelperTrait.php$0 ➔ flattenParameters()   C

Complexity

Conditions 7

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7.0178

Importance

Changes 0
Metric Value
cc 7
dl 0
loc 23
ccs 13
cts 14
cp 0.9286
crap 7.0178
rs 5.5
c 0
b 0
f 0
1
<?php
2
/*******************************************************************************
3
 *  This file is part of the GraphQL Bundle package.
4
 *
5
 *  (c) YnloUltratech <[email protected]>
6
 *
7
 *  For the full copyright and license information, please view the LICENSE
8
 *  file that was distributed with this source code.
9
 ******************************************************************************/
10
11
namespace Ynlo\GraphQLBundle\Test;
12
13
use Doctrine\Common\Util\Inflector;
14
use Symfony\Component\BrowserKit\Client;
15
use Symfony\Component\HttpFoundation\Request;
16
use Ynlo\GraphQLBundle\Model\ID;
17
18
/**
19
 * @method Client getClient()
20
 */
21
trait GraphQLHelperTrait
22
{
23
    private static $endpoint;
24
25
    private static $query;
26
27
    /**
28
     * @param string $endpoint
29
     */
30
    protected static function endpoint($endpoint)
31
    {
32
        self::$endpoint = $endpoint;
33
    }
34
35
    /**
36
     * @param string     $name
37
     * @param array      $parameters (optional)
38
     * @param array|null $expected
39
     */
40 14
    protected static function query($name, array $parameters, array $expected = null)
41
    {
42 14
        if (null === $expected) {
43
            $expected = $parameters;
44
            $parameters = [];
45
        }
46 14
        self::graphqlQuery('query', $name, $parameters, $expected);
47 14
    }
48
49
    /**
50
     * @param string $name
51
     * @param array  $parameters
52
     * @param array  $expected
53
     */
54 7
    protected static function mutation($name, array $parameters = [], array $expected = [])
55
    {
56 7
        self::graphqlQuery('mutation', $name, $parameters, $expected);
57 7
    }
58
59
60
    /**
61
     * @param string $nodeType
62
     * @param string $databaseId
63
     *
64
     * @return string
65
     */
66 8
    protected static function encodeID($nodeType, $databaseId)
67
    {
68 8
        return ID::encode($nodeType, $databaseId);
69
    }
70
71
    /**
72
     * @param string $globalID
73
     *
74
     * @return ID
75
     */
76
    protected static function decodeID($globalID):ID
77
    {
78
        return ID::createFromString($globalID);
79
    }
80
81
    /**
82
     * @param string $value
83
     *
84
     * @return object
85
     */
86
    protected static function literalValue($value)
87
    {
88
        return new class ($value)
89
        {
90
            private $value;
91
92 2
            public function __construct($value)
93
            {
94 2
                $this->value = (string) $value;
95 2
            }
96
97 2
            public function __toString()
98
            {
99 2
                return $this->value;
100
            }
101
        };
102
    }
103
104
    /**
105
     * debugQuery
106
     */
107
    protected static function debugQuery()
108
    {
109
        print_r(self::$query);
110
    }
111
112
    /**
113
     * @param string $type
114
     * @param string $name
115
     * @param array  $parameters
116
     * @param array  $expected
117
     */
118 21
    private static function graphqlQuery($type, $name, array $parameters = [], array $expected = [])
119
    {
120 21
        $flattenQuery = self::flattenQuery($name, $parameters, $expected);
121 21
        if (strpos($name, '.') !== false) {
122 19
            $name = Inflector::camelize(str_replace('.', '_', $name));
123
        }
124
        $query =
125
            <<<GrahpQL
126 21
$type $name{
127 21
  $flattenQuery
128
}
129
GrahpQL;
130
131 21
        $body = ['query' => $query];
132 21
        self::$query = $query;
133 21
        self::getClient()->request(Request::METHOD_POST, self::$endpoint, [], [], [], json_encode($body));
0 ignored issues
show
Bug Best Practice introduced by
The method Ynlo\GraphQLBundle\Test\...elperTrait::getClient() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

133
        self::/** @scrutinizer ignore-call */ 
134
              getClient()->request(Request::METHOD_POST, self::$endpoint, [], [], [], json_encode($body));
Loading history...
134 21
    }
135
136
    /**
137
     * @param string $name
138
     * @param array  $parameters
139
     * @param array  $expected
140
     *
141
     * @return string
142
     */
143 21
    private static function flattenQuery($name, array $parameters = [], array $expected = [])
144
    {
145 21
        $expectedStr = self::flattenExpectation($expected);
146
147
        //namespaced query
148 21
        if (strpos($name, '.') !== false) {
149 19
            $namespace = explode('.', $name);
150
151 19
            $name = array_reverse($namespace)[0];
152 19
            array_pop($namespace);
153 19
            $query = '{child}';
154 19
            foreach ($namespace as $path) {
155
                $content = <<<GrahpQL
156 19
$path {
157
    {child}
158
}
159
GrahpQL;
160 19
                $query = str_replace('{child}', $content, $query);
161
            }
162
163 19
            return str_replace('{child}', self::flattenQuery($name, $parameters, $expected), $query);
164
        }
165
166
167 21
        $paramsStr = null;
168 21
        if ($parameters) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parameters of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
169 21
            $paramsStr = self::flattenParameters($parameters);
170
        }
171
172
        return <<<GrahpQL
173 21
  $name$paramsStr{
174 21
    $expectedStr
175
  }
176
GrahpQL;
177
    }
178
179
    /**
180
     * @param array $parameters
181
     * @param array $wrappers
182
     *
183
     * @return string
184
     */
185 21
    private static function flattenParameters(array $parameters, $wrappers = ['(', ')'])
186
    {
187 21
        foreach ($parameters as $key => &$value) {
188 21
            if (\is_string($value)) {
189 17
                $value = "\"$value\"";
190
            }
191 21
            if (\is_bool($value)) {
192
                $value = $value ? 'true' : 'false';
193
            }
194 21
            if (\is_array($value)) {
195 17
                if (array_key_exists(0, $value)) {
196 4
                    $value = json_encode($value);
197
                } else {
198 14
                    $value = self::flattenParameters($value, ['{', '}']);
199
                }
200
            }
201 21
            $value = "$key: $value";
202
        }
203 21
        unset($value);
204
205 21
        list($start, $end) = $wrappers;
206
207 21
        return "$start ".implode(', ', $parameters)." $end";
208
    }
209
210
    /**
211
     * @param array $expectation
212
     *
213
     * @return string
214
     */
215 21
    private static function flattenExpectation(array $expectation)
216
    {
217 21
        $expectNormalized = [];
218 21
        foreach ($expectation as $path => $value) {
219 21
            if (\is_array($value)) {
220 18
                if (isset($value[0], $value[1])
221 18
                    && is_array($value[0])
222 18
                    && is_array($value[1])
223
                ) {
224 3
                    $value = self::flattenQuery($path, $value[0], $value[1]);
225
                } else {
226 18
                    $value = $path." {\n\t\t".self::flattenExpectation($value)."\n\t}";
227
                }
228
            }
229 21
            $expectNormalized[] = $value;
230
        }
231
232 21
        return implode("\n\t", $expectNormalized);
233
    }
234
}
235