Passed
Pull Request — master (#38)
by Kevin
19:12
created

FactoryCollection::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 4
c 1
b 0
f 1
dl 0
loc 7
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Zenstruck\Foundry;
4
5
/**
6
 * @author Kevin Bond <[email protected]>
7
 */
8
final class FactoryCollection
9
{
10
    /** @var Factory */
11
    private $factory;
12
13
    /** @var int */
14
    private $min;
15
16
    /** @var int */
17
    private $max;
18
19
    /**
20
     * @param int|null $max If set, when created, the collection will be a random size between $min and $max
21
     */
22
    public function __construct(Factory $factory, int $min, ?int $max = null)
23
    {
24
        if ($max && $min > $max) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $max of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
25
            throw new \InvalidArgumentException('Min must be less than max.');
26
        }
27
28
        $this->factory = $factory;
29
        $this->min = $min;
30
        $this->max = $max ?? $min;
31
    }
32
33
    /**
34
     * @param array|callable $attributes
35
     *
36
     * @return Proxy[]|object[]
37
     */
38
    public function create($attributes = []): array
39
    {
40
        return \array_map(
41
            static function(Factory $factory) use ($attributes) {
42
                return $factory->create($attributes);
43
            },
44
            $this->all()
45
        );
46
    }
47
48
    /**
49
     * @return Factory[]
50
     */
51
    public function all(): array
52
    {
53
        return \array_map(
54
            function() {
55
                return clone $this->factory;
56
            },
57
            \array_fill(0, \random_int($this->min, $this->max), null)
58
        );
59
    }
60
61
    public function factory(): Factory
62
    {
63
        return $this->factory;
64
    }
65
}
66