Test Failed
Push — main ( b30d66...68ae2b )
by Peter
15:45 queued 12:41
created

FakeCarHelper::getWeighted()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 2
b 0
f 0
nc 3
nop 2
dl 0
loc 19
ccs 10
cts 10
cp 1
crap 3
rs 9.9666
1
<?php
2
3
namespace Faker\Provider;
4
5
use Exception;
6
use InvalidArgumentException;
7
use Random\RandomException;
0 ignored issues
show
Bug introduced by
The type Random\RandomException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
class FakeCarHelper
10
{
11
    /**
12
     * @param  array<int|string, int|string>  $arrayData
13
     *
14 7
     * @throws Exception
15
     */
16 7
    public static function getArrayData(array $arrayData, int $count = 1): mixed
17 4
    {
18 3
        if (static::isWeighted($arrayData)) {
19
            /** @var array<int|string, int> $arrayData */
20 7
            $data = static::getWeighted($arrayData, $count);
21 2
        } else {
22
            $data = static::getRandomElementsFromArray($arrayData, $count);
23
        }
24 5
25
        if (is_array($data) && $count === 1) {
26
            return array_values($data)[0];
27
        }
28
29
        return $data;
30
    }
31
32
    /**
33
     * Determines if an array is weighted(associative).
34
     * An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
35 7
     *
36
     * @param  array<int|string, int|string>  $array
37 7
     */
38
    public static function isWeighted(array $array): bool
39 7
    {
40
        $keys = array_keys($array);
41
42
        return array_keys($keys) !== $keys;
43
    }
44
45
    /**
46
     * Returns a random element from a passed array
47
     *
48
     * @param  array<int|string, int|string>  $values
49 5
     *
50
     * @throws InvalidArgumentException|RandomException
51 5
     */
52
    public static function getRandomElementFromArray(array $values): int|string
53 5
    {
54
        $elements = static::getRandomElementsFromArray($values, 1);
55
56
        return array_values($elements)[0];
57
    }
58
59
    /**
60
     * Get random elements from input array
61
     *
62
     * @param  array<int|string, int|string>  $values  The input array
63
     * @param  int|null  $count  The number of random elements you want to get in your response.
64
     *                           Leave out or set to 0 for random.
65
     * @return array<int|string, int|string>
66 8
     *
67
     * @throws RandomException
68
     */
69 8
    public static function getRandomElementsFromArray(array $values, ?int $count = 1): array
70
    {
71 8
        $valuesLength = count($values);
72 1
73
        if ($count > $valuesLength) {
74
            throw new InvalidArgumentException('Count larger than array length.');
75 8
        }
76 2
77
        if ($count === 0) {
78
            return [];
79 8
        }
80 1
81
        if ($count === null) {
82
            $count = $valuesLength === 1 ? 1 : random_int(1, $valuesLength);
83 8
        }
84 8
85 8
        return array_intersect_key(
86 8
            $values,
87 8
            array_flip(
88 8
                (array) array_rand($values, $count)
89
            )
90
        );
91
    }
92
93
    /**
94
     * Get one element out of an input array with specified weights to get the distribution
95
     * of the generated elements as you want them.
96
     *
97
     * @param  array<int|string, int>  $values  Input array with values as key and weight as value. ['value 1' => 30, 'value 7' => 70]
98
     *
99
     * @throws Exception
100
     */
101 5
    public static function getWeighted(array $values, int $count = 1): string|int
0 ignored issues
show
Unused Code introduced by
The parameter $count is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

101
    public static function getWeighted(array $values, /** @scrutinizer ignore-unused */ int $count = 1): string|int

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
102
    {
103 5
        // TODO: Implement support for $count > 1
104 5
        $currentTotal = 0;
105
        $firstRand    = random_int(1, 100);
106 5
107
        $total = array_sum($values);
108 5
109
        $rand = ($firstRand / 100) * $total;
110 5
111 5
        foreach ($values as $key => $weight) {
112
            $currentTotal += $weight;
113 5
114 5
            if ($rand <= $currentTotal) {
115
                return $key;
116
            }
117
        }
118 1
119
        return '';
120
    }
121
122
    /**
123
     * @param  array<int>  $range
124
     *
125
     * @throws RandomException
126
     */
127
    public static function getRange(array $range, int $decimals = 0): int|string
128 1
    {
129
        if (count($range) !== 2) {
130 1
            throw new RandomException('Invalid range');
131
        }
132
133
        if ($range[0] > $range[1]) {
134
            throw new RandomException('Invalid range');
135
        }
136
137
        if ($decimals < 0) {
138
            throw new InvalidArgumentException('Invalid decimals');
139
        }
140
141
        if ($decimals > 0) {
142
            $factor = 10 ** $decimals;
143
144
            return number_format(random_int($range[0] * $factor, $range[1] * $factor) / $factor, $decimals);
145
        }
146
147
        return random_int($range[0], $range[1]);
148
    }
149
150
    /**
151
     * @param  array<int>  $range
152
     *
153
     * @throws RandomException
154
     */
155
    public static function getRangeWithUnit(array $range, string $unit, int $decimals = 0): string
156
    {
157
        return static::getRange($range, $decimals).' '.$unit;
158
    }
159
}
160