Test Failed
Pull Request — main (#30)
by Peter
09:21 queued 06:39
created

FakeCarHelper   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 143
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 42
dl 0
loc 143
ccs 39
cts 39
cp 1
rs 10
c 2
b 0
f 0
wmc 19

7 Methods

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

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

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