Test Failed
Pull Request — main (#30)
by Peter
06:01 queued 02:57
created

FakeCarHelper::getRange()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 2
dl 0
loc 21
ccs 2
cts 2
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
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
        $data = static::isWeighted($arrayData)
19
            ? static::getWeighted($arrayData, $count)
20 7
            : static::getRandomElementsFromArray($arrayData, $count);
21 2
22
        if (is_array($data) && $count === 1) {
23
            return array_values($data)[0];
24 5
        }
25
26
        return $data;
27
    }
28
29
    /**
30
     * Determines if an array is weighted(associative).
31
     * An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
32
     *
33
     * @param  array<int|string, int|string>  $array
34
     */
35 7
    public static function isWeighted(array $array): bool
36
    {
37 7
        $keys = array_keys($array);
38
39 7
        return array_keys($keys) !== $keys;
40
    }
41
42
    /**
43
     * Returns a random element from a passed array
44
     *
45
     * @param  array<int|string, int|string>  $values
46
     *
47
     * @throws InvalidArgumentException|RandomException
48
     */
49 5
    public static function getRandomElementFromArray(array $values): int|string
50
    {
51 5
        $elements = static::getRandomElementsFromArray($values, 1);
52
53 5
        return array_values($elements)[0];
54
    }
55
56
    /**
57
     * Get random elements from input array
58
     *
59
     * @param  array<int|string, int|string>  $values  The input array
60
     * @param  int|null  $count  The number of random elements you want to get in your response.
61
     *                           Leave out or set to 0 for random.
62
     * @return array<int|string, int|string>
63
     *
64
     * @throws RandomException
65
     */
66 8
    public static function getRandomElementsFromArray(array $values, ?int $count = 1): array
67
    {
68
        $valuesLength = count($values);
69 8
70
        if ($count > $valuesLength) {
71 8
            throw new InvalidArgumentException('Count larger than array length.');
72 1
        }
73
74
        if ($count === 0) {
75 8
            return [];
76 2
        }
77
78
        if (! $count) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $count of type integer|null is loosely compared to false; 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...
79 8
            $count = $valuesLength === 1 ? 1 : random_int(1, $valuesLength);
80 1
        }
81
82
        return array_intersect_key(
83 8
            $values,
84 8
            array_flip(
85 8
                (array) array_rand($values, $count)
86 8
            )
87 8
        );
88 8
    }
89
90
    /**
91
     * Get one element out of an input array with specified weights to get the distribution
92
     * of the generated elements as you want them.
93
     *
94
     * @param  array<int|string, int>  $values  Input array with values as key and weight as value. ['value 1' => 30, 'value 7' => 70]
95
     *
96
     * @throws Exception
97
     */
98
    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

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