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