Completed
Push — master ( 852076...2b713c )
by Alex
23s queued 14s
created

ValueHelpers::SetIsSerializedAsElement()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 15
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 23
rs 9.7666
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * Created by PhpStorm.
6
 * User: alex
7
 * Date: 22/07/20
8
 * Time: 8:21 PM.
9
 */
10
namespace AlgoWeb\ODataMetadata\Helpers;
11
12
use AlgoWeb\ODataMetadata\CsdlConstants;
13
use AlgoWeb\ODataMetadata\Edm\Validation\Internal\ValidationHelper;
14
use AlgoWeb\ODataMetadata\EdmConstants;
15
use AlgoWeb\ODataMetadata\Exception\InvalidOperationException;
16
use AlgoWeb\ODataMetadata\Interfaces\IEdmElement;
17
use AlgoWeb\ODataMetadata\Interfaces\IModel;
18
19
trait ValueHelpers
20
{
21
    /**
22
     * Sets an annotation indicating if the value should be serialized as an element.
23
     * @param IModel $model                 model containing the value
24
     * @param bool   $isSerializedAsElement value indicating if the value should be serialized as an element
25
     */
26
    public function SetIsSerializedAsElement(IModel $model, bool $isSerializedAsElement): void
27
    {
28
        /** @var IEdmElement $self */
29
        $self = $this;
30
        assert($self instanceof IEdmElement);
31
        if ($isSerializedAsElement) {
32
            $error = null;
33
            if (!ValidationHelper::ValidateValueCanBeWrittenAsXmlElementAnnotation(
34
                $self,
35
                null,
36
                null,
37
                $error
38
            )
39
            ) {
40
                throw new InvalidOperationException(strval($error));
41
            }
42
        }
43
44
        $model->SetAnnotationValue(
45
            $self,
46
            EdmConstants::InternalUri,
47
            CsdlConstants::IsSerializedAsElementAnnotation,
48
            $isSerializedAsElement
49
        );
50
    }
51
52
    /**
53
     * Gets an annotation indicating if the value should be serialized as an element.
54
     * @param  IModel $model model containing the value
55
     * @return bool   value indicating if the string should be serialized as an element
56
     */
57
    public function IsSerializedAsElement(IModel $model): bool
58
    {
59
        $self = $this;
60
        assert($self instanceof IEdmElement);
61
        $value = $model->GetAnnotationValue(
62
            'boolean',
63
            $self,
64
            EdmConstants::InternalUri,
65
            CsdlConstants::IsSerializedAsElementAnnotation
66
        );
67
        return is_bool($value) ? $value : false;
68
    }
69
}
70