DocumentFactory   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 31
dl 0
loc 70
ccs 33
cts 33
cp 1
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A fake() 0 13 3
B toArray() 0 34 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace VGirol\JsonApiFaker\Factory;
6
7
use VGirol\JsonApiConstant\Members;
8
use VGirol\JsonApiFaker\Contract\DocumentContract;
9
use VGirol\JsonApiFaker\Exception\JsonApiFakerException;
10
11
/**
12
 * Factory for an entire document.
13
 */
14
class DocumentFactory extends BaseFactory implements DocumentContract
15
{
16 1
    use HasData;
17 1
    use HasErrors;
18 1
    use HasIncluded;
19 1
    use HasJsonapi;
20 1
    use HasLinks;
21 1
    use HasMeta;
22
23
    /**
24
     * @throws JsonApiFakerException
25
     */
26 6
    public function toArray(): array
27
    {
28 6
        $json = [];
29
30 6
        if (isset($this->meta)) {
31 6
            $json[Members::META] = $this->meta;
32
        }
33 6
        if (isset($this->links)) {
34 6
            $json[Members::LINKS] = $this->links;
35
        }
36 6
        if (isset($this->errors)) {
37 3
            $json[Members::ERRORS] = array_map(
38
                /**
39
                 * @param \VGirol\JsonApiFaker\Contract\ErrorContract $error
40
                 *
41
                 * @return array|null
42
                 */
43 3
                function ($error) {
44 3
                    return $error->toArray();
45 3
                },
46 3
                $this->errors
47
            );
48
        }
49 6
        if ($this->dataHasBeenSet()) {
50 3
            $json[Members::DATA] = ($this->data === null) ? null : $this->data->toArray();
51
        }
52 6
        if (isset($this->included)) {
53 3
            $json[Members::INCLUDED] = $this->included->toArray();
54
        }
55 6
        if (isset($this->jsonapi)) {
56 6
            $json[Members::JSONAPI] = $this->jsonapi->toArray();
57
        }
58
59 6
        return $json;
60
    }
61
62
    /**
63
     * Fill the document with fake values (links, meta, jsonapi and errors or data).
64
     *
65
     * @param integer $options
66
     * @param integer $count
67
     *
68
     * @return static
69
     * @throws JsonApiFakerException
70
     */
71 6
    public function fake(int $options = 0, int $count = 3)
72
    {
73 6
        if ($options === 0) {
74 3
            $options = Options::FAKE_SINGLE | Options::FAKE_RESOURCE_OBJECT;
75
        }
76
77 6
        $withErrors = (($options & Options::FAKE_ERRORS) == Options::FAKE_ERRORS);
78
79 6
        $this->fakeLinks()
80 6
            ->fakeMeta()
81 6
            ->fakeJsonapi();
82
83 6
        return $withErrors ? $this->fakeErrors($count) : $this->fakeData($options, $count);
84
    }
85
}
86