-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLink.php
139 lines (122 loc) · 2.91 KB
/
Link.php
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<?php
namespace Oddvalue\LinkBuilder;
use Oddvalue\LinkBuilder\Contracts\Linkable;
use Oddvalue\LinkBuilder\Contracts\LinkGenerator;
abstract class Link implements LinkGenerator
{
/**
* The model we're generating a link for
*
* @var object
*/
protected $model;
/**
* Options array
* There's no concrete implementation or use case for this
* do with it as you wish
*
* @var array
*/
protected $options;
/**
* Holds the HTML attribute object
*
* @var \Oddvalue\LinkBuilder\HtmlAttributes
*/
protected $attributes;
/**
* The attribute on the model from which the link href is derived
*
* @var string
*/
protected $hrefAttribute = 'slug';
/**
* The attribute on the model to use as the link text
*
* @var string
*/
protected $labelAttribute = 'name';
/**
* Instantiate the generator with the linkable model
*
* @param Linkable $model
* @param array $options
*/
public function __construct(Linkable $model, array $options = [])
{
$this->model = $model;
if (key_exists('class', $options)) {
$options['attributes'] = @$options['attributes'] ?: [];
$options['attributes']['class'] = $options['class'];
unset($options['class']);
}
$attributes = [];
if (key_exists('attributes', $options)) {
$attributes = $options['attributes'];
unset($options['attributes']);
}
$this->setAttributes($attributes);
$this->options = $options;
}
/**
* Get the link href for a given model
*
* @param $model
* @return string
*/
public function href() : string
{
return '/' . $this->model->{$this->hrefAttribute};
}
/**
* Get the link text for a given model
*
* @param $model
* @param array $options
* @return string
*/
public function label() : string
{
return (string) $this->model->{$this->labelAttribute};
}
/**
* Get the HtmlAttributes object
*
* @return \Oddvalue\LinkBuilder\HtmlAttributes
*/
public function getAttributes() : HtmlAttributes
{
return $this->attributes;
}
/**
* Set the link attributes
*
* @param array $attributes
* @return self
*/
public function setAttributes(array $attributes)
{
$this->attributes = HtmlAttributes::make($attributes);
return $this;
}
/**
* Generate an HTML link for the model
*
* @return string
*/
public function toHtml()
{
return <<<HTML
<a href="{$this->href()}"{$this->getAttributes()}>{$this->label()}</a>
HTML;
}
/**
* Cast the generator to a string
*
* @return string
*/
public function __toString() : string
{
return $this->toHtml();
}
}