Passed
Push — feature/second-release ( 258ce1...c43059 )
by Andrea Marco
02:43
created

CasesCollectionCast::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cerbero\LaravelEnum;
6
7
use BackedEnum;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Cerbero\LaravelEnum\BackedEnum. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
use Cerbero\LaravelEnum\Contracts\Bitwise;
9
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
10
use Illuminate\Database\Eloquent\Model;
11
use InvalidArgumentException;
12
use UnitEnum;
13
14
/**
15
 * The cases collection cast.
16
 *
17
 * @template TKey of array-key
18
 * @template TValue
19
 *
20
 * @implements CastsAttributes<CasesCollection, mixed>
21
 */
22
class CasesCollectionCast implements CastsAttributes
23
{
24
    /**
25
     * Disable object caching.
26
     */
27
    public bool $withoutObjectCaching = true;
28
29
    /**
30
     * Instantiate the class.
31
     */
32 19
    public function __construct(private readonly string $enum)
33
    {
34 19
        if (! is_subclass_of($enum, UnitEnum::class)) {
35 1
            throw new InvalidArgumentException('The cast argument must be a valid enum');
36
        }
37
    }
38
39
    /**
40
     * Transform the attribute from the underlying model values.
41
     *
42
     * @param string|int|null $value
43
     * @param array<string, mixed> $attributes
44
     * @return CasesCollection<TKey, TValue>
45
     * @throws \ValueError
46
     */
47 18
    public function get(Model $model, string $key, mixed $value, array $attributes): ?CasesCollection
48
    {
49
        return match (true) {
50 18
            is_string($value) => $this->getByJson($value),
51 7
            is_int($value) => $this->enum::filter(fn(BackedEnum $case) => ($value & $case->value) == $case->value),
0 ignored issues
show
Bug introduced by
Accessing value on the interface BackedEnum suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
52 17
            default => null,
53
        };
54
    }
55
56
    /**
57
     * Transform the given JSON into a cases collection.
58
     *
59
     * @return CasesCollection<TKey, TValue>
60
     * @throws \ValueError
61
     */
62 11
    protected function getByJson(string $json): CasesCollection
63
    {
64
        /** @var list<string|int> $cases */
65 11
        $cases = json_decode($json, true);
66 11
        $cases = array_unique($cases);
0 ignored issues
show
Bug introduced by
$cases of type Cerbero\LaravelEnum\list is incompatible with the type array expected by parameter $array of array_unique(). ( Ignorable by Annotation )

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

66
        $cases = array_unique(/** @scrutinizer ignore-type */ $cases);
Loading history...
67
68
        /** @var CasesCollection<TKey, TValue> */
69 11
        return new CasesCollection(array_map(fn(string|int $value) => $this->enum::from($value), $cases));
70
    }
71
72
    /**
73
     * Transform the attribute to its underlying model values.
74
     *
75
     * @param array<string, mixed> $attributes
76
     */
77 17
    public function set(Model $model, string $key, mixed $value, array $attributes): string|int|null
78
    {
79 17
        $this->withoutObjectCaching = ! $value instanceof CasesCollection;
80
81
        return match (true) {
82 17
            $value instanceof CasesCollection => $value->toJson(),
83 15
            is_array($value) => $this->setByArray($value),
84 4
            is_int($value) => $value,
85 17
            default => null,
86
        };
87
    }
88
89
    /**
90
     * Transform the given array into a serializable string.
91
     *
92
     * @param array<array-key, mixed> $array
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<array-key, mixed> at position 2 could not be parsed: Unknown type name 'array-key' at position 2 in array<array-key, mixed>.
Loading history...
93
     */
94 11
    protected function setByArray(array $array): string|int|null
95
    {
96 11
        if (is_subclass_of($this->enum, Bitwise::class)) {
97 2
            return array_reduce($array, function(?int $carry, BackedEnum|int $item) {
98 2
                return $carry |= $item instanceof BackedEnum ? $item->value : $item;
0 ignored issues
show
Bug introduced by
Accessing value on the interface BackedEnum suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
99 2
            });
100
        }
101
102 9
        $values = reset($array) instanceof UnitEnum
103 4
            ? $this->enum::only(...array_column($array, 'name'))
104 5
            : array_values(array_unique($array));
105
106 9
        return json_encode($values) ?: null;
107
    }
108
}
109