summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/web/src/Widget/Link.php
blob: cbae3b9558a5557850f789d395459cf2cb7d5995 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php

namespace ipl\Web\Widget;

use ipl\Html\Attribute;
use ipl\Html\Attributes;
use ipl\Html\BaseHtmlElement;
use ipl\Web\Common\BaseTarget;
use ipl\Web\Url;

/**
 * Link element, i.e. <a href="...
 */
class Link extends BaseHtmlElement
{
    use BaseTarget;

    /** @var Url */
    protected $url;

    protected $tag = 'a';

    /**
     * Create a link element
     *
     * @param mixed            $content
     * @param Url|string       $url
     * @param Attributes|array $attributes
     */
    public function __construct($content, $url, $attributes = null)
    {
        $this
            ->setContent($content)
            ->setUrl($url)
            ->getAttributes()
                ->add($attributes)
                ->registerAttributeCallback('href', [$this, 'createHrefAttribute']);
    }

    /**
     * Get the URL of the link
     *
     * @return Url
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * Set the URL of the link
     *
     * @param Url|string $url
     *
     * @return $this
     */
    public function setUrl($url)
    {
        if (! $url instanceof Url) {
            try {
                $url = Url::fromPath($url);
            } catch (\Exception $e) {
                $url = 'invalid';
            }
        }

        $this->url = $url;

        return $this;
    }

    /**
     * Create and return the href attribute
     *
     * Used as attribute callback for the href attribute.
     *
     * @return Attribute
     */
    public function createHrefAttribute()
    {
        return new Attribute('href', (string) $this->getUrl());
    }

    /**
     * Open this link in a modal
     *
     * @return $this
     */
    public function openInModal(): self
    {
        $this->getAttributes()
            ->set('data-icinga-modal', true)
            ->set('data-no-icinga-ajax', true);

        return $this;
    }
}