GraphQLTypeGeneratorTest::getTDBMService()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 0
1
<?php
2
3
namespace TheCodingMachine\Tdbm\GraphQL;
4
5
use Doctrine\Common\Cache\ArrayCache;
6
use Doctrine\DBAL\Connection;
7
use Doctrine\DBAL\DriverManager;
8
use TheCodingMachine\TDBM\Configuration;
9
use TheCodingMachine\Tdbm\GraphQL\Fixtures\TestSchema;
10
use TheCodingMachine\Tdbm\GraphQL\Registry\EmptyContainer;
11
use TheCodingMachine\Tdbm\GraphQL\Registry\Registry;
12
use TheCodingMachine\Tdbm\GraphQL\Tests\Beans\Country;
13
use TheCodingMachine\Tdbm\GraphQL\Tests\DAOs\CountryDao;
14
use TheCodingMachine\Tdbm\GraphQL\Tests\DAOs\UserDao;
15
use TheCodingMachine\Tdbm\GraphQL\Tests\GraphQL\CountryType;
16
use TheCodingMachine\Tdbm\GraphQL\Tests\GraphQL\Generated\AbstractCountryType;
17
use TheCodingMachine\Tdbm\GraphQL\Tests\GraphQL\Generated\AbstractUserType;
18
use TheCodingMachine\Tdbm\GraphQL\Tests\GraphQL\TdbmGraphQLTypeMapper;
19
use TheCodingMachine\TDBM\TDBMService;
20
use TheCodingMachine\TDBM\Utils\DefaultNamingStrategy as TdbmDefaultNamingStrategy;
21
use PHPUnit\Framework\TestCase;
22
use Youshido\GraphQL\Execution\Context\ExecutionContext;
23
use Youshido\GraphQL\Execution\Processor;
24
use Youshido\GraphQL\Execution\ResolveInfo;
25
use Youshido\GraphQL\Schema\Schema;
26
use Youshido\GraphQL\Type\Scalar\StringType;
27
28
class GraphQLTypeGeneratorTest extends TestCase
29
{
30
    private static function getAdminConnectionParams(): array
31
    {
32
        return array(
33
            'user' => $GLOBALS['db_username'],
34
            'password' => $GLOBALS['db_password'],
35
            'host' => $GLOBALS['db_host'],
36
            'port' => $GLOBALS['db_port'],
37
            'driver' => $GLOBALS['db_driver'],
38
        );
39
    }
40
41
    private static function getConnectionParams(): array
42
    {
43
        $adminParams = self::getAdminConnectionParams();
44
        $adminParams['dbname'] = $GLOBALS['db_name'];
45
        return $adminParams;
46
    }
47
48
    public static function setUpBeforeClass()
49
    {
50
        $config = new \Doctrine\DBAL\Configuration();
51
52
        $adminConn = DriverManager::getConnection(self::getAdminConnectionParams(), $config);
53
        $adminConn->getSchemaManager()->dropAndCreateDatabase($GLOBALS['db_name']);
54
55
        $conn = DriverManager::getConnection(self::getConnectionParams(), $config);
56
57
        self::loadSqlFile($conn, __DIR__.'/sql/graphqlunittest.sql');
58
    }
59
60
    protected static function loadSqlFile(Connection $connection, $sqlFile)
61
    {
62
        $sql = file_get_contents($sqlFile);
63
64
        $stmt = $connection->prepare($sql);
65
        $stmt->execute();
66
    }
67
68
    protected static function getTDBMService() : TDBMService
69
    {
70
        $config = new \Doctrine\DBAL\Configuration();
71
        $connection = DriverManager::getConnection(self::getConnectionParams(), $config);
72
        $configuration = new Configuration('TheCodingMachine\\Tdbm\\GraphQL\\Tests\\Beans', 'TheCodingMachine\\Tdbm\\GraphQL\\Tests\\DAOs', $connection, new TdbmDefaultNamingStrategy(), new ArrayCache(), null, null, [
73
            new GraphQLTypeGenerator('TheCodingMachine\\Tdbm\\GraphQL\\Tests\\GraphQL')
74
        ]);
75
76
        return new TDBMService($configuration);
77
    }
78
79
    public function testGenerate()
80
    {
81
        $this->recursiveDelete(__DIR__.'/../src/Tests/GraphQL/');
82
83
        $tdbmService = self::getTDBMService();
84
        $tdbmService->generateAllDaosAndBeans();
85
86
        $this->assertFileExists(__DIR__.'/../src/Tests/GraphQL/UserType.php');
87
        $this->assertFileExists(__DIR__.'/../src/Tests/GraphQL/Generated/AbstractUserType.php');
88
        $this->assertFileExists(__DIR__.'/../src/Tests/GraphQL/TdbmGraphQLTypeMapper.php');
89
90
        $this->assertTrue(class_exists(AbstractCountryType::class));
91
        $abstractCountryType = new \ReflectionClass(AbstractCountryType::class);
92
        $this->assertNotNull($abstractCountryType->getMethod('getUsersField'));
93
        $abstractUserType = new \ReflectionClass(AbstractUserType::class);
94
        $this->assertNotNull($abstractUserType->getMethod('getRolesField'));
95
96
        $tdbmGraphQLTypeMapper = new \ReflectionClass(TdbmGraphQLTypeMapper::class);
97
        $this->assertNotNull($tdbmGraphQLTypeMapper->getMethod('mapClassToType'));
98
    }
99
100
    /**
101
     * @depends testGenerate
102
     */
103
    public function testQuery()
104
    {
105
        $tdbmService = self::getTDBMService();
106
        $userDao = new UserDao($tdbmService);
107
        $registry = new Registry(new EmptyContainer());
0 ignored issues
show
Deprecated Code introduced by
The class TheCodingMachine\Tdbm\GraphQL\Registry\Registry has been deprecated with message: Use TheCodingMachine\GraphQL\Controllers\Registry instead

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
108
        $processor = new Processor(new TestSchema($registry, $userDao));
109
110
        $introspectionQuery = <<<EOF
111
{
112
  __schema {
113
    queryType {
114
      name
115
    }
116
  }
117
}
118
EOF;
119
120
121
        $response = $processor->processPayload($introspectionQuery, [])->getResponseData();
122
        $this->assertTrue(isset($response['data']['__schema']['queryType']['name']));
123
124
        $introspectionQuery2 = <<<EOF
125
{
126
  __type(name: "User") {
127
    name
128
    kind
129
    fields {
130
      name
131
      type {
132
        name
133
        kind
134
      }
135
    }
136
  }
137
}
138
EOF;
139
140
        $response = $processor->processPayload($introspectionQuery2, [])->getResponseData();
141
        $this->assertSame('User', $response['data']['__type']['name']);
142
        $this->assertSame('OBJECT', $response['data']['__type']['kind']);
143
        $this->assertSame('id', $response['data']['__type']['fields'][0]['name']);
144
        $this->assertSame('ID', $response['data']['__type']['fields'][0]['type']['name']);
145
        $this->assertSame('SCALAR', $response['data']['__type']['fields'][0]['type']['kind']);
146
147
        $found = false;
148
        foreach ($response['data']['__type']['fields'] as $field) {
149
            if ($field['name'] === 'roles') {
150
                $found = true;
151
            }
152
        }
153
        $this->assertTrue($found, 'Failed asserting the roles field is found in user type.');
154
155
        $introspectionQuery3 = <<<EOF
156
{
157
  users {
158
    id,
159
    name,
160
    roles {
161
      name
162
    }
163
  }
164
}
165
EOF;
166
        $response = $processor->processPayload($introspectionQuery3, [])->getResponseData();
167
        $this->assertSame('John Smith', $response['data']['users'][0]['name']);
168
        $this->assertSame('Admins', $response['data']['users'][0]['roles'][0]['name']);
169
    }
170
171
    /**
172
     * Delete a file or recursively delete a directory.
173
     *
174
     * @param string $str Path to file or directory
175
     * @return bool
176
     */
177
    private function recursiveDelete(string $str) : bool
178
    {
179
        if (is_file($str)) {
180
            return @unlink($str);
181
        } elseif (is_dir($str)) {
182
            $scan = glob(rtrim($str, '/') . '/*');
183
            foreach ($scan as $index => $path) {
184
                $this->recursiveDelete($path);
185
            }
186
187
            return @rmdir($str);
188
        }
189
        return false;
190
    }
191
192
    public function testResultIteratorType()
193
    {
194
        $type = new ResultIteratorType(new CountryType(new Registry(new EmptyContainer())));
0 ignored issues
show
Deprecated Code introduced by
The class TheCodingMachine\Tdbm\GraphQL\Registry\Registry has been deprecated with message: Use TheCodingMachine\GraphQL\Controllers\Registry instead

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
195
196
        $tdbmService = self::getTDBMService();
197
        $countryDao = new CountryDao($tdbmService);
198
199
        $countries = $countryDao->findAll();
200
201
        $countField = $type->getField('count');
202
        $resolveInfo = $this->getMockBuilder(ResolveInfo::class)->disableOriginalConstructor()->getMock();
203
        $this->assertEquals(3, $countField->resolve($countries, [], $resolveInfo));
204
205
        $itemsField = $type->getField('items');
206
        $result = $itemsField->resolve($countries, [], $resolveInfo);
207
        $this->assertCount(3, $result);
208
        $this->assertInstanceOf(Country::class, $result[0]);
209
210
        $result = $itemsField->resolve($countries, ['order'=>'label'], $resolveInfo);
211
        $this->assertEquals('Jamaica', $result[1]->getLabel());
212
213
        $result = $itemsField->resolve($countries, ['offset'=>1, 'limit'=>1], $resolveInfo);
214
        $this->assertCount(1, $result);
215
216
        $this->expectException(GraphQLException::class);
217
        $result = $itemsField->resolve($countries, ['offset'=>1], $resolveInfo);
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
218
    }
219
}
220