Completed
Push — master ( c162bb...a7a918 )
by Portey
03:50
created

AbstractInputObjectType::parseValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
/*
3
* This file is a part of graphql-youshido project.
4
*
5
* @author Alexandr Viniychuk <[email protected]>
6
* created: 12/2/15 9:00 PM
7
*/
8
9
namespace Youshido\GraphQL\Type\InputObject;
10
11
12
use Youshido\GraphQL\Config\Object\InputObjectTypeConfig;
13
use Youshido\GraphQL\Field\FieldInterface;
14
use Youshido\GraphQL\Type\AbstractType;
15
use Youshido\GraphQL\Type\Traits\AutoNameTrait;
16
use Youshido\GraphQL\Type\Traits\FieldsAwareObjectTrait;
17
use Youshido\GraphQL\Type\TypeMap;
18
19
abstract class AbstractInputObjectType extends AbstractType
20
{
21
22
    use AutoNameTrait, FieldsAwareObjectTrait;
23
24 1
    public function __construct($config = [])
25
    {
26 1
        if (empty($config)) {
27
            $config = [
28 1
                'name' => $this->getName()
29
            ];
30
        }
31 1
        $this->config = new InputObjectTypeConfig($config, $this);
32 1
        $this->build($this->config);
33 1
    }
34
35
    /**
36
     * @param InputObjectTypeConfig $config
37
     * @return mixed
38
     */
39
    abstract public function build($config);
40
41 3
    public function isValidValue($value)
42
    {
43 3
        if (!is_array($value)) {
44 1
            return false;
45
        }
46
47 3
        $typeConfig     = $this->getConfig();
48 3
        $requiredFields = array_filter($typeConfig->getFields(), function (FieldInterface $field) {
49 3
            return $field->getType()->getKind() == TypeMap::KIND_NON_NULL;
50 3
        });
51
52 3
        foreach ($value as $valueKey => $valueItem) {
53 3
            if (!$typeConfig->hasField($valueKey) || !$typeConfig->getField($valueKey)->getType()->isValidValue($valueItem)) {
54 2
                return false;
55
            }
56
57 3
            if (array_key_exists($valueKey, $requiredFields)) {
58 3
                unset($requiredFields[$valueKey]);
59
            }
60
        }
61
62 3
        return !(count($requiredFields) > 0);
63
    }
64
65 2
    public function getKind()
66
    {
67 2
        return TypeMap::KIND_INPUT_OBJECT;
68
    }
69
70 1
    public function isInputType()
71
    {
72 1
        return true;
73
    }
74
75 1
    public function parseValue($value)
76
    {
77 1
        $typeConfig = $this->getConfig();
78 1
        foreach ($value as $valueKey => $item) {
79 1
            $value[$valueKey] = $typeConfig->getField($valueKey)->getType()->parseValue($item);
80
        }
81
82 1
        return $value;
83
    }
84
85
}
86