Passed
Push — master ( 07cec0...cc31a6 )
by Rafael
05:55
created

SchemaCompiler   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 95.24%

Importance

Changes 0
Metric Value
wmc 9
dl 0
loc 46
ccs 20
cts 21
cp 0.9524
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
C compile() 0 35 8
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\Schema;
12
13
use GraphQL\Type\Schema;
14
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
15
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
16
use Ynlo\GraphQLBundle\Definition\Registry\DefinitionRegistry;
17
use Ynlo\GraphQLBundle\Type\Registry\TypeRegistry;
18
19
/**
20
 * GraphQL Schema compiler
21
 *
22
 * Compile all definitions into graphql-php schema
23
 */
24
class SchemaCompiler implements ContainerAwareInterface
25
{
26
    use ContainerAwareTrait;
27
28
    protected $registry;
29
30 22
    public function __construct(DefinitionRegistry $registry)
31
    {
32 22
        $this->registry = $registry;
33 22
    }
34
35 22
    public function compile($name): Schema
36
    {
37 22
        $endpoint = $this->registry->getEndpoint($name);
38 22
        TypeRegistry::setUp($this->container, $endpoint);
39
40
        //automatically create all interface implementors
41
        //to avoid empty interfaces
42 22
        foreach ($endpoint->allInterfaces() as $type) {
43 22
            foreach ($type->getImplementors() as $implementor) {
44 22
                if (!TypeRegistry::has($implementor)) {
45 22
                    TypeRegistry::create($implementor);
46
                }
47
            }
48
        }
49
50
        $config = [
51 22
            'types' => TypeRegistry::all(),
52 22
            'typeLoader' => function ($name) {
53 22
                return TypeRegistry::get($name);
54 22
            },
55
        ];
56
57 22
        if ($endpoint->allQueries()) {
58 22
            $config['query'] = TypeRegistry::get('Query');
59
        }
60
61 22
        if ($endpoint->allMutations()) {
62 22
            $config['mutation'] = TypeRegistry::get('Mutation');
63
        }
64
65 22
        if (isset($config['query']) || isset($config['mutation'])) {
66 22
            return new Schema($config);
67
        }
68
69
        throw new \RuntimeException('Your GraphQL schema is empty. Create your first object and query and try again');
70
    }
71
}
72