Failed Conditions
Push — master ( 4438ef...2738ac )
by Adrien
02:29
created

AbstractServer::createServer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Testing\Api;
6
7
use Ecodev\Felix\Api\Server;
8
use Ecodev\Felix\Testing\Traits\TestWithTransaction;
9
use Exception;
10
use GraphQL\Executor\ExecutionResult;
11
use GraphQL\Type\Schema;
12
use Laminas\Diactoros\ServerRequest;
13
use Mezzio\Session\Session;
14
use Mezzio\Session\SessionMiddleware;
15
use PHPUnit\Framework\TestCase;
16
17
abstract class AbstractServer extends TestCase
18
{
19
    use TestWithTransaction;
20
21
    /**
22
     * Should get user and call User::setCurrent()
23
     */
24
    abstract protected function setCurrentUser(?string $user): void;
25
26
    abstract protected function createSchema(): Schema;
27
28
    protected function createServer(bool $debug): Server
29
    {
30
        return new Server($this->createSchema(), $debug);
31
    }
32
33
    public function testSchemaIsValid(): void
34
    {
35
        $schema = $this->createSchema();
36
        $schema->assertValid();
37
38
        self::assertTrue(true, 'schema passes validation');
39
    }
40
41
    /**
42
     * @dataProvider providerQuery
43
     */
44
    public function testQuery(?string $user, ServerRequest $request, array $expected, ?callable $dataPreparator = null): void
45
    {
46
        $this->setCurrentUser($user);
47
48
        if ($dataPreparator) {
49
            $dataPreparator(_em()->getConnection());
50
        }
51
52
        // Use this flag to easily debug API test issues
53
        /** @var bool $debug */
54
        $debug = false;
55
56
        // Configure server
57
        $server = $this->createServer($debug);
58
59
        // Execute query
60
        $result = $server->execute($request);
61
62
        $actual = $this->resultToArray($result, $debug);
63
64
        if ($debug) {
0 ignored issues
show
introduced by
The condition $debug is always false.
Loading history...
65
            ve($actual);
66
            unset($actual['errors'][0]['trace']);
67
        }
68
69
        self::assertEquals($expected, $actual);
70
    }
71
72
    public function providerQuery(): array
73
    {
74
        $data = [];
75
        $files = glob('tests/data/query/*.php');
76
        if ($files === false) {
77
            throw new Exception('Could not find any queries to test server');
78
        }
79
80
        foreach ($files as $file) {
81
            $name = str_replace('-', ' ', basename($file, '.php'));
82
            $user = preg_replace('/\d/', '', explode(' ', $name)[0]);
83
            if ($user === 'anonymous') {
84
                $user = null;
85
            }
86
87
            $args = require $file;
88
89
            // Convert arg into request
90
            $request = new ServerRequest();
91
            $args[0] = $request
92
                ->withParsedBody($args[0])
93
                ->withAttribute(SessionMiddleware::SESSION_ATTRIBUTE, new Session([]))
94
                ->withMethod('POST')
95
                ->withHeader('content-type', ['application/json']);
96
97
            array_unshift($args, $user);
98
            $data[$name] = $args;
99
        }
100
101
        return $data;
102
    }
103
104
    /**
105
     * @param ExecutionResult|ExecutionResult[] $result
106
     * @param bool $debug
107
     *
108
     * @return array
109
     */
110
    private function resultToArray($result, bool $debug): array
111
    {
112
        if (is_array($result)) {
113
            foreach ($result as &$one) {
114
                $one = $this->oneResultToArray($one, $debug);
115
            }
116
        } else {
117
            $result = $this->oneResultToArray($result, $debug);
118
        }
119
120
        return $result;
121
    }
122
123
    private function oneResultToArray(ExecutionResult $result, bool $debug): array
124
    {
125
        $result = $result->toArray();
126
        if ($debug) {
127
            ve($result);
128
            unset($result['errors'][0]['trace']);
129
        }
130
131
        return $result;
132
    }
133
}
134