Completed
Pull Request — master (#7)
by Robbie
02:15
created

BlockLinkField::getParsedValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 4
c 1
b 0
f 1
nc 2
nop 0
dl 0
loc 8
rs 9.4285
1
<?php
2
3
namespace SilverStripe\ElementalBlocks\Form;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\Core\Convert;
7
use SilverStripe\Forms\FormField;
8
use SilverStripe\ORM\DataObject;
9
use SilverStripe\View\ArrayData;
10
11
class BlockLinkField extends FormField
12
{
13
    /**
14
     * Cache for parsed value
15
     *
16
     * @var ArrayData
17
     */
18
    protected $parsedValue;
19
20
    public function Type()
21
    {
22
        return 'blocklinkfield';
23
    }
24
25
    /**
26
     * Reset the cached parsed value when setting a new value
27
     *
28
     * {@inheritDoc}
29
     */
30
    public function setValue($value, $data = null)
31
    {
32
        $this->parsedValue = null;
33
        return parent::setValue($value, $data);
34
    }
35
36
    /**
37
     * Return a parsed {@link ArrayData} object from the contents of the JSON value. Will
38
     * be cached for future use, and the cache will be reset via setValue each time.
39
     *
40
     * @return ArrayData
41
     */
42
    public function getParsedValue()
43
    {
44
        if ($this->parsedValue) {
45
            return $this->parsedValue;
46
        }
47
48
        $parsedValue = Convert::json2array($this->dataValue());
49
        return $this->parsedValue = ArrayData::create((array) $parsedValue);
50
    }
51
52
    /**
53
     * Get whether a {@link SiteTree} link has been defined on this link field
54
     *
55
     * @return bool
56
     */
57
    public function getLinkDefined()
58
    {
59
        return (bool) $this->getParsedValue()->PageID;
60
    }
61
62
    /**
63
     * Get the relative URL for the linked {@link SiteTree} object, with a leading slash
64
     *
65
     * @return string
66
     */
67
    public function getLinkRelativeUrl()
68
    {
69
        /** @var SiteTree $page */
70
        $page = DataObject::get_by_id(SiteTree::class, $this->getParsedValue()->PageID);
71
72
        return $page ? '/' . ltrim($page->URLSegment, '/') : '';
73
    }
74
75
    /**
76
     * Get the link "text"
77
     *
78
     * @return string
79
     */
80
    public function getLinkTitle()
81
    {
82
        return $this->getParsedValue()->Text;
83
    }
84
85
    /**
86
     * Get the link "description", used for titles or alt text
87
     *
88
     * @return string
89
     */
90
    public function getLinkDescription()
91
    {
92
        return $this->getParsedValue()->Description;
93
    }
94
95
    /**
96
     * Get whether to open the link in a new window
97
     *
98
     * @return bool
99
     */
100
    public function getLinkTargetBlank()
101
    {
102
        return (bool) $this->getParsedValue()->TargetBlank;
103
    }
104
}
105