1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is a part of graphql-youshido project. |
4
|
|
|
* |
5
|
|
|
* @author Alexandr Viniychuk <[email protected]> |
6
|
|
|
* created: 12/1/15 11:05 PM |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Youshido\GraphQL\Type\Config\Traits; |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
use Youshido\GraphQL\Type\AbstractType; |
13
|
|
|
use Youshido\GraphQL\Type\Field\Field; |
14
|
|
|
use Youshido\GraphQL\Type\TypeMap; |
15
|
|
|
use Youshido\GraphQL\Validator\Exception\ConfigurationException; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Class FieldsAwareTrait |
19
|
|
|
* @package Youshido\GraphQL\Type\Config\Traits |
20
|
|
|
*/ |
21
|
|
|
trait FieldsAwareTrait |
22
|
|
|
{ |
23
|
|
|
protected $fields = []; |
24
|
|
|
|
25
|
13 |
|
public function buildFields() |
26
|
|
|
{ |
27
|
13 |
|
$sourceFields = empty($this->data['fields']) ? [] : $this->data['fields']; |
|
|
|
|
28
|
13 |
|
foreach ($sourceFields as $fieldName => $fieldInfo) { |
29
|
10 |
|
if ($fieldInfo instanceof Field || $fieldInfo instanceof AbstractType) { |
30
|
1 |
|
$this->fields[$fieldName] = $fieldInfo; |
31
|
1 |
|
continue; |
32
|
|
|
}; |
33
|
|
|
|
34
|
9 |
|
$this->addField($fieldName, $fieldInfo['type'], $fieldInfo); |
35
|
13 |
|
} |
36
|
13 |
|
} |
37
|
|
|
|
38
|
10 |
|
public function addField($name, $type, $config = []) |
39
|
|
|
{ |
40
|
10 |
|
if (is_string($type)) { |
41
|
9 |
|
if (!TypeMap::isScalarType($type)) { |
42
|
|
|
throw new ConfigurationException('You can\'t pass ' . $type . ' as a string type.'); |
43
|
|
|
} |
44
|
|
|
|
45
|
9 |
|
$type = TypeMap::getScalarTypeObject($type); |
46
|
9 |
|
} |
47
|
|
|
|
48
|
10 |
|
$config['name'] = $name; |
49
|
10 |
|
$config['type'] = $type; |
50
|
10 |
|
$field = new Field($config); |
51
|
|
|
|
52
|
10 |
|
$this->fields[$name] = $field; |
53
|
|
|
|
54
|
10 |
|
return $this; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param $name |
59
|
|
|
* |
60
|
|
|
* @return Field |
61
|
|
|
*/ |
62
|
8 |
|
public function getField($name) |
63
|
|
|
{ |
64
|
8 |
|
return $this->hasField($name) ? $this->fields[$name] : null; |
65
|
2 |
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param $name |
69
|
|
|
* |
70
|
|
|
* @return bool |
71
|
|
|
*/ |
72
|
8 |
|
public function hasField($name) |
73
|
|
|
{ |
74
|
8 |
|
return array_key_exists($name, $this->fields); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @return Field[] |
79
|
|
|
*/ |
80
|
4 |
|
public function getFields() |
81
|
|
|
{ |
82
|
4 |
|
return $this->fields; |
83
|
|
|
} |
84
|
|
|
} |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: