Issues (462)

src/models/UnitsData.php (75 issues)

1
<?php
2
/**
3
 * Units plugin for Craft CMS
4
 *
5
 * A plugin for handling physical quantities and the units of measure in which
6
 * they're represented.
7
 *
8
 * @link      https://nystudio107.com/
0 ignored issues
show
The tag in position 1 should be the @copyright tag
Loading history...
9
 * @copyright Copyright (c) nystudio107
0 ignored issues
show
@copyright tag must contain a year and the name of the copyright holder
Loading history...
10
 */
0 ignored issues
show
PHP version not specified
Loading history...
Missing @category tag in file comment
Loading history...
Missing @package tag in file comment
Loading history...
Missing @author tag in file comment
Loading history...
Missing @license tag in file comment
Loading history...
11
12
namespace nystudio107\units\models;
13
14
use craft\base\Model;
15
use nystudio107\units\Units;
16
use PhpUnitsOfMeasure\AbstractPhysicalQuantity;
17
use PhpUnitsOfMeasure\Exception\NonNumericValue;
18
use PhpUnitsOfMeasure\Exception\NonStringUnitName;
19
use PhpUnitsOfMeasure\PhysicalQuantityInterface;
20
use PhpUnitsOfMeasure\UnitOfMeasure;
21
use PhpUnitsOfMeasure\UnitOfMeasureInterface;
22
use yii\base\InvalidArgumentException;
23
use function call_user_func_array;
24
use function get_class;
25
26
/**
0 ignored issues
show
Missing short description in doc comment
Loading history...
27
 * @author    nystudio107
0 ignored issues
show
The tag in position 1 should be the @package tag
Loading history...
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
28
 * @package   Units
0 ignored issues
show
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
29
 * @since     1.0.0
0 ignored issues
show
The tag in position 3 should be the @author tag
Loading history...
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
30
 *
31
 * @property string $valueFraction
32
 * @property array|float[] $valueParts
33
 * @property array|string[] $valuePartsFraction
34
 */
0 ignored issues
show
Missing @category tag in class comment
Loading history...
Missing @license tag in class comment
Loading history...
Missing @link tag in class comment
Loading history...
35
class UnitsData extends Model implements PhysicalQuantityInterface
36
{
37
    // Public Properties
38
    // =========================================================================
39
40
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
41
     * @var ?string The fully qualified class name of the unit of measure
42
     */
43
    public ?string $unitsClass = null;
44
45
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
46
     * @var ?float The value of the unit of measure
47
     */
48
    public ?float $value = null;
49
50
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
51
     * @var ?string The units that the unit of measure is in
52
     */
53
    public ?string $units = null;
54
55
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
56
     * @var AbstractPhysicalQuantity
57
     */
58
    public AbstractPhysicalQuantity $unitsInstance;
59
60
    // Public Methods
61
    // =========================================================================
62
63
    /**
64
     * Call through to the appropriate method in the AbstractPhysicalQuantity
65
     * class in $unitsInstance, if it exists
66
     *
67
     * @param string $method
0 ignored issues
show
Missing parameter comment
Loading history...
68
     * @param array $args
0 ignored issues
show
Missing parameter comment
Loading history...
Expected 2 spaces after parameter type; 1 found
Loading history...
69
     *
70
     * @return mixed
71
     * @throws InvalidArgumentException
72
     * @throws NonNumericValue
73
     * @throws NonStringUnitName
74
     */
75
    public function __call($method, $args)
76
    {
77
        $unitsInstance = $this->unitsInstance;
78
        if (method_exists($unitsInstance, $method)) {
79
            return call_user_func_array([$unitsInstance, $method], $args);
80
        }
81
82
        throw new InvalidArgumentException("Method {$method} doesn't exist");
83
    }
84
85
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
86
     * @inheritdoc
87
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
88
    public function init(): void
89
    {
90
        parent::init();
91
        /** @var Settings $settings */
0 ignored issues
show
The open comment tag must be the only content on the line
Loading history...
Missing short description in doc comment
Loading history...
The close comment tag must be the only content on the line
Loading history...
92
        $settings = Units::$plugin->getSettings();
93
        $this->unitsClass = $this->unitsClass ?? $settings->defaultUnitsClass;
94
        $this->value = $this->value ?? $settings->defaultValue;
95
        $this->units = $this->units ?? $settings->defaultUnits;
96
97
        if ($this->unitsClass !== null) {
98
            $this->unitsInstance = new $this->unitsClass($this->value, $this->units);
99
        }
100
    }
101
102
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
103
     * @inheritdoc
104
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
105
    public function rules(): array
106
    {
107
        $rules = parent::rules();
108
        $rules = array_merge($rules, [
0 ignored issues
show
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
109
            ['unitsClass', 'string'],
110
            ['value', 'number'],
111
            ['units', 'string'],
112
        ]);
0 ignored issues
show
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
113
114
        return $rules;
115
    }
116
117
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
118
     * @inheritdoc
119
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
120
    public function fields(): array
121
    {
122
        $fields = parent::fields();
123
        $fields = array_diff_key(
124
            $fields,
125
            array_flip([
0 ignored issues
show
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
126
                'unitsInstance',
127
            ])
0 ignored issues
show
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
128
        );
129
130
        return $fields;
131
    }
132
133
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
Parameter $unit should have a doc-comment as per coding-style.
Loading history...
134
     * @inheritdoc
135
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
136
    public function toUnit($unit)
137
    {
138
        return $this->unitsInstance->toUnit($unit);
139
    }
140
141
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
142
     * @inheritdoc
143
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
144
    public function toNativeUnit()
145
    {
146
        return $this->unitsInstance->toNativeUnit();
147
    }
148
149
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
150
     * @inheritdoc
151
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
152
    public function __toString(): string
153
    {
154
        return $this->unitsInstance->__toString();
155
    }
156
157
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
Parameter $quantity should have a doc-comment as per coding-style.
Loading history...
158
     * @inheritdoc
159
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
160
    public function add(PhysicalQuantityInterface $quantity)
161
    {
162
        /** @var UnitsData $quantity */
0 ignored issues
show
The open comment tag must be the only content on the line
Loading history...
Missing short description in doc comment
Loading history...
The close comment tag must be the only content on the line
Loading history...
163
        return $this->physicalQuantityToUnitsData($this->unitsInstance->add($quantity->unitsInstance));
164
    }
165
166
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
Parameter $quantity should have a doc-comment as per coding-style.
Loading history...
167
     * @inheritdoc
168
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
169
    public function subtract(PhysicalQuantityInterface $quantity)
170
    {
171
        /** @var UnitsData $quantity */
0 ignored issues
show
The open comment tag must be the only content on the line
Loading history...
Missing short description in doc comment
Loading history...
The close comment tag must be the only content on the line
Loading history...
172
        return $this->physicalQuantityToUnitsData($this->unitsInstance->subtract($quantity->unitsInstance));
173
    }
174
175
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
Parameter $testQuantity should have a doc-comment as per coding-style.
Loading history...
176
     * @inheritdoc
177
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
178
    public function isEquivalentQuantity(PhysicalQuantityInterface $testQuantity)
179
    {
180
        /** @var UnitsData $testQuantity */
0 ignored issues
show
The open comment tag must be the only content on the line
Loading history...
Missing short description in doc comment
Loading history...
The close comment tag must be the only content on the line
Loading history...
181
        return $this->unitsInstance->isEquivalentQuantity($testQuantity->unitsInstance);
0 ignored issues
show
Accessing unitsInstance on the interface PhpUnitsOfMeasure\PhysicalQuantityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
182
    }
183
184
    /**
0 ignored issues
show
Missing short description in doc comment
Loading history...
Parameter $includeAliases should have a doc-comment as per coding-style.
Loading history...
185
     * @inheritdoc
186
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
187
    public function availableUnits(bool $includeAliases = true)
188
    {
189
        $availableUnits = [];
190
        $units = $this->unitsInstance::getUnitDefinitions();
191
        /** @var UnitOfMeasure $unit */
0 ignored issues
show
The open comment tag must be the only content on the line
Loading history...
Missing short description in doc comment
Loading history...
The close comment tag must be the only content on the line
Loading history...
192
        foreach ($units as $unit) {
193
            $name = $unit->getName();
194
            $aliases = $unit->getAliases();
195
            $availableUnits[$name] = $includeAliases ? $aliases : $aliases[0] ?? $name;
196
        }
197
198
        return $availableUnits;
199
    }
200
201
    /**
202
     * Return the measurement as a fraction, with the units appended
203
     *
204
     * @return string
205
     */
206
    public function toFraction(): string
207
    {
208
        return trim(Units::$variable->fraction($this->value) . ' ' . $this->units);
0 ignored issues
show
It seems like $this->value can also be of type null; however, parameter $value of nystudio107\units\variab...itsVariable::fraction() does only seem to accept double, maybe add an additional type check? ( Ignorable by Annotation )

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

208
        return trim(Units::$variable->fraction(/** @scrutinizer ignore-type */ $this->value) . ' ' . $this->units);
Loading history...
209
    }
210
211
    /**
212
     * Return the measurement as a fraction, in the given unit of measure
213
     *
214
     * @param UnitOfMeasureInterface|string $unit The desired unit of measure,
215
     *                                             or a string name of one
0 ignored issues
show
Parameter comment not aligned correctly; expected 44 spaces but found 45
Loading history...
216
     *
217
     * @return string The measurement cast in the requested units, as a
218
     *                fraction
219
     */
220
    public function toUnitFraction($unit): string
221
    {
222
        $value = $this->toUnit($unit);
223
224
        return Units::$variable->fraction($value);
225
    }
226
227
    /**
228
     * Return the value as a fraction
229
     *
230
     * @return string
231
     */
232
    public function getValueFraction(): string
233
    {
234
        return Units::$variable->fraction($this->value);
0 ignored issues
show
It seems like $this->value can also be of type null; however, parameter $value of nystudio107\units\variab...itsVariable::fraction() does only seem to accept double, maybe add an additional type check? ( Ignorable by Annotation )

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

234
        return Units::$variable->fraction(/** @scrutinizer ignore-type */ $this->value);
Loading history...
235
    }
236
237
    /**
238
     * Return an array of the whole number and decimal number ports of the value
239
     * [0] has the whole number part, and [1] has the decimal part
240
     *
241
     * @return float[]
242
     */
243
    public function getValueParts(): array
244
    {
245
        return Units::$variable->float2parts($this->value);
0 ignored issues
show
It seems like $this->value can also be of type null; however, parameter $number of nystudio107\units\variab...Variable::float2parts() does only seem to accept double, maybe add an additional type check? ( Ignorable by Annotation )

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

245
        return Units::$variable->float2parts(/** @scrutinizer ignore-type */ $this->value);
Loading history...
246
    }
247
248
    /**
249
     * Return an array of the whole number and decimal number ports of the
250
     * value with the decimal part converted to a fraction. [0] has the whole
251
     * number part, and [1] has the fractional part
252
     *
253
     * @return string[]
254
     */
255
    public function getValuePartsFraction(): array
256
    {
257
        $parts = Units::$variable->float2parts($this->value);
0 ignored issues
show
It seems like $this->value can also be of type null; however, parameter $number of nystudio107\units\variab...Variable::float2parts() does only seem to accept double, maybe add an additional type check? ( Ignorable by Annotation )

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

257
        $parts = Units::$variable->float2parts(/** @scrutinizer ignore-type */ $this->value);
Loading history...
258
        $parts[0] = (string)$parts[0];
259
        $parts[1] = Units::$variable->float2ratio($parts[1]);
260
261
        return $parts;
262
    }
263
264
    // Protected Methods
265
    // =========================================================================
266
267
    /**
268
     * Convert a PhysicalQuantity object into a UnitsData object
269
     *
270
     * @param PhysicalQuantityInterface $quantity
0 ignored issues
show
Missing parameter comment
Loading history...
271
     *
272
     * @return UnitsData
273
     */
274
    protected function physicalQuantityToUnitsData(PhysicalQuantityInterface $quantity): UnitsData
275
    {
276
        $unitsClass = get_class($quantity);
277
        list($value, $units) = explode(' ', (string)$quantity);
278
        $config = [
279
            'unitsClass' => $unitsClass,
280
            'value' => $value,
281
            'units' => $units,
282
        ];
283
284
        return new UnitsData($config);
285
    }
286
}
287