Completed
Branch master (bc5900)
by Vincent
01:31
created

BaseFactory::setGenerator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace VGirol\JsonApiFaker\Factory;
6
7
use Faker\Generator;
8
use VGirol\JsonApiFaker\Contract\FactoryContract;
9
use VGirol\JsonApiFaker\Contract\GeneratorContract;
10
use VGirol\JsonApiFaker\Messages;
11
12
/**
13
 * This class implements some methods of the FactoryContract interface.
14
 */
15
abstract class BaseFactory implements FactoryContract
16
{
17
    const FAKE_RESOURCE_OBJECT = 1;
18
    const FAKE_RESOURCE_IDENTIFIER = 2;
19
    const FAKE_SINGLE = 4;
20
    const FAKE_COLLECTION = 8;
21
    const FAKE_CAN_BE_NULL = 16;
22
    const FAKE_ERRORS = 32;
23
24
    /**
25
     * The factory generator
26
     *
27
     * @var GeneratorContract
28
     */
29
    public $generator;
30
31
    abstract public function toArray(): ?array;
32
33
    abstract public function fake();
34
35
    /**
36
     * Set the Generator instance
37
     *
38
     * @param GeneratorContract $generator
39
     *
40
     * @return static
41
     */
42 9
    public function setGenerator($generator)
43
    {
44 9
        $this->generator = $generator;
45
46 9
        return $this;
47
    }
48
49 19
    public function addToObject(string $object, string $name, $value): void
50
    {
51 19
        if (!isset($this->{$object})) {
52 19
            $this->{$object} = [];
53
        }
54
55 19
        $this->{$object}[$name] = $value;
56 19
    }
57
58 2
    public function addToArray(string $object, $value): void
59
    {
60 2
        if (!isset($this->{$object})) {
61 1
            $this->{$object} = [];
62
        }
63
64 2
        $this->{$object}[] = $value;
65 2
    }
66
67
    /**
68
     * @inheritDoc
69
     * @throws \Exception
70
     */
71 2
    public function toJson($options = 0): string
72
    {
73 2
        $json = json_encode($this->toArray(), $options);
74
75 2
        if ($json === false) {
76 1
            throw new \Exception(
77 1
                sprintf(Messages::JSON_ENCODE_ERROR, json_last_error_msg())
78
            );
79
        }
80
81 1
        return $json;
82
    }
83
84
    /**
85
     * This methods creates some members with fake names and values.
86
     *
87
     * The fake member is filled with the null value :
88
     * $options = [
89
     *      'member name' => null
90
     * ]
91
     *
92
     * The default array of methods is used to fill the fake value :
93
     * $options = [
94
     *      'member name' => []
95
     * ]
96
     *
97
     * Only the provided methods are used to fill the fake value :
98
     * $options = [
99
     *      'member name' => [ array of methods allowed to fake ]
100
     * ]
101
     *
102
     * If no key name is provided, a fake member name is generated :
103
     * $options = [
104
     *      null,
105
     *      [],
106
     *      [ array of methods allowed to fake ]
107
     * ]
108
     *
109
     * @param integer|array $options The number of keys to generate or an array of keys to use.
110
     *
111
     * @return array<string,mixed>
112
     */
113 16
    protected function fakeMembers($options): array
114
    {
115 16
        $faker = \Faker\Factory::create();
116
117 16
        if (is_int($options)) {
118 15
            $count = $options;
119 15
            $options = [];
120 15
            for ($i = 0; $i < $count; $i++) {
121 15
                $options[] = [];
122
            }
123
        }
124
125 16
        $values = [];
126 16
        foreach ($options as $key => $providers) {
127 16
            $name = $this->fakeMemberName($faker, $key);
128 16
            $value = $this->fakeValue($faker, $providers);
129
130 16
            $values[$name] = $value;
131
        }
132
133 16
        return $values;
134
    }
135
136
    /**
137
     * Returns a fake member's name.
138
     *
139
     * @param Generator $faker
140
     * @param string|integer|null $name
141
     *
142
     * @return string
143
     */
144 17
    protected function fakeMemberName(Generator $faker, $name = null): string
145
    {
146 17
        if (\is_null($name) || \is_int($name)) {
147 16
            $forbidden = ['id', 'type'];
148
            do {
149 16
                $name = $faker->unique()->word;
150 16
            } while (in_array($name, $forbidden));
151
        }
152
153 17
        if (\strpos($name, '/') === false) {
154 17
            return $name;
155
        }
156
157 1
        return $faker->unique()->regexify($name);
158
    }
159
160
    /**
161
     * Returns a fake member's value.
162
     *
163
     * @param Generator $faker
164
     * @param array<string>|null $providers
165
     * @return mixed
166
     */
167 17
    protected function fakeValue(Generator $faker, $providers = [])
168
    {
169
        $allowed = [
170 17
            'word',
171
            'sentence',
172
            'boolean',
173
            'randomNumber',
174
            'randomFloat',
175
            'date'
176
        ];
177
178 17
        if (is_null($providers)) {
179 1
            return null;
180
        }
181
182 17
        $method = $faker->randomElement(
183 17
            empty($providers) ? $allowed : $providers
184
        );
185
186 17
        return $faker->{$method};
187
    }
188
}
189