Passed
Pull Request — master (#20020)
by
unknown
17:25 queued 08:30
created

Link::serialize()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 5
nop 1
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use yii\base\BaseObject;
11
12
/**
13
 * Link represents a link object as defined in [JSON Hypermedia API Language](https://tools.ietf.org/html/draft-kelly-json-hal-03).
14
 *
15
 * @author Qiang Xue <[email protected]>
16
 * @since 2.0
17
 */
18
class Link extends BaseObject
19
{
20
    /**
21
     * The self link.
22
     */
23
    const REL_SELF = 'self';
24
25
    /**
26
     * @var string a URI [RFC3986](https://tools.ietf.org/html/rfc3986) or
27
     * URI template [RFC6570](https://tools.ietf.org/html/rfc6570). This property is required.
28
     */
29
    public $href;
30
    /**
31
     * @var string a secondary key for selecting Link Objects which share the same relation type
32
     */
33
    public $name;
34
    /**
35
     * @var string a hint to indicate the media type expected when dereferencing the target resource
36
     */
37
    public $type;
38
    /**
39
     * @var bool a value indicating whether [[href]] refers to a URI or URI template.
40
     */
41
    public $templated = false;
42
    /**
43
     * @var string a URI that hints about the profile of the target resource.
44
     */
45
    public $profile;
46
    /**
47
     * @var string a label describing the link
48
     */
49
    public $title;
50
    /**
51
     * @var string the language of the target resource
52
     */
53
    public $hreflang;
54
55
56
    /**
57
     * Serializes a list of links into proper array format.
58
     * @param array $links the links to be serialized
59
     * @return array the proper array representation of the links.
60
     */
61 10
    public static function serialize(array $links)
62
    {
63 10
        foreach ($links as $rel => $link) {
64 10
            if (is_array($link)) {
65 1
                foreach ($link as $i => $l) {
66 1
                    $link[$i] = $l instanceof self ? array_filter((array) $l) : ['href' => $l];
67
                }
68 1
                $links[$rel] = $link;
69
            }
70 10
            if ($link instanceof self) {
71 1
                $l = array_filter((array)$link);
72 1
                $links[$rel] = $l;
73
            } else {
74 10
                $links[$rel] = ['href' => $link];
75
            }
76
        }
77
78 10
        return $links;
79
    }
80
}
81