| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Web\Widget; |
| 4 |
|
| 5 |
use ipl\Html\Attribute; |
| 6 |
use ipl\Html\Attributes; |
| 7 |
use ipl\Html\BaseHtmlElement; |
| 8 |
use ipl\Web\Common\BaseTarget; |
| 9 |
use ipl\Web\Url; |
| 10 |
|
| 11 |
/** |
| 12 |
* Link element, i.e. <a href="... |
| 13 |
*/ |
| 14 |
class Link extends BaseHtmlElement |
| 15 |
{ |
| 16 |
use BaseTarget; |
| 17 |
|
| 18 |
/** @var Url */ |
| 19 |
protected $url; |
| 20 |
|
| 21 |
protected $tag = 'a'; |
| 22 |
|
| 23 |
/** |
| 24 |
* Create a link element |
| 25 |
* |
| 26 |
* @param mixed $content |
| 27 |
* @param Url|string $url |
| 28 |
* @param Attributes|array $attributes |
| 29 |
*/ |
| 30 |
public function __construct($content, $url, $attributes = null) |
| 31 |
{ |
| 32 |
$this |
| 33 |
->setContent($content) |
| 34 |
->setUrl($url) |
| 35 |
->getAttributes() |
| 36 |
->add($attributes) |
| 37 |
->registerAttributeCallback('href', [$this, 'createHrefAttribute']); |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Get the URL of the link |
| 42 |
* |
| 43 |
* @return Url |
| 44 |
*/ |
| 45 |
public function getUrl() |
| 46 |
{ |
| 47 |
return $this->url; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Set the URL of the link |
| 52 |
* |
| 53 |
* @param Url|string $url |
| 54 |
* |
| 55 |
* @return $this |
| 56 |
*/ |
| 57 |
public function setUrl($url) |
| 58 |
{ |
| 59 |
if (! $url instanceof Url) { |
| 60 |
try { |
| 61 |
$url = Url::fromPath($url); |
| 62 |
} catch (\Exception $e) { |
| 63 |
$url = 'invalid'; |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
$this->url = $url; |
| 68 |
|
| 69 |
return $this; |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* Create and return the href attribute |
| 74 |
* |
| 75 |
* Used as attribute callback for the href attribute. |
| 76 |
* |
| 77 |
* @return Attribute |
| 78 |
*/ |
| 79 |
public function createHrefAttribute() |
| 80 |
{ |
| 81 |
return new Attribute('href', (string) $this->getUrl()); |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* Open this link in a modal |
| 86 |
* |
| 87 |
* @return $this |
| 88 |
*/ |
| 89 |
public function openInModal(): self |
| 90 |
{ |
| 91 |
$this->getAttributes() |
| 92 |
->set('data-icinga-modal', true) |
| 93 |
->set('data-no-icinga-ajax', true); |
| 94 |
|
| 95 |
return $this; |
| 96 |
} |
| 97 |
} |