Passed
Pull Request — master (#33)
by Melech
03:28
created

MessageCapable::fromMessage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 18
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Valkyrja Framework package.
7
 *
8
 * (c) Melech Mizrachi <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Valkyrja\Model\Models;
15
16
use Valkyrja\Routing\Message;
17
18
use function assert;
19
20
/**
21
 * Trait MessageCapable.
22
 *
23
 * @author Melech Mizrachi
24
 */
25
trait MessageCapable
26
{
27
    /**
28
     * @inheritDoc
29
     */
30
    public static function fromMessage(string $message, array $data = []): static
31
    {
32
        assert(is_a($message, Message::class, true));
33
34
        $arr           = [];
35
        $messageValues = $message::values();
36
        $messageNames  = $message::names();
37
38
        // Convert the data from message value keyed to name keyed
39
        foreach ($messageValues as $key => $messageValue) {
40
            $messageName       = $messageNames[$key];
41
            $arr[$messageName] = $data[$messageValue];
42
        }
43
44
        /** @var static $model */
45
        $model = static::fromArray($arr);
46
47
        return $model;
48
    }
49
50
    /**
51
     * @inheritDoc
52
     */
53
    public function asMessageArray(string $message, string ...$properties): array
54
    {
55
        assert(is_a($message, Message::class, true));
56
57
        $messageArray  = [];
58
        $asArray       = $this->asArray(...$properties);
0 ignored issues
show
Bug introduced by
It seems like asArray() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

58
        /** @scrutinizer ignore-call */ 
59
        $asArray       = $this->asArray(...$properties);
Loading history...
59
        $messageNames  = $message::names();
60
        $messageValues = $message::values();
61
62
        // Convert the data from name keyed to message value keyed
63
        foreach ($messageNames as $key => $messageName) {
64
            $messageValue                = $messageValues[$key];
65
            $messageArray[$messageValue] = $asArray[$messageName];
66
        }
67
68
        return $messageArray;
69
    }
70
}
71