1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Chriscreates\Blog\Traits\Post; |
4
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
6
|
|
|
|
7
|
|
|
trait PostAttributes |
8
|
|
|
{ |
9
|
|
|
public function getTagsCountAttribute() |
10
|
|
|
{ |
11
|
|
|
return $this->tags->count(); |
|
|
|
|
12
|
|
|
} |
13
|
|
|
|
14
|
|
|
public function isPublished() |
15
|
|
|
{ |
16
|
|
|
return $this->status == self::PUBLISHED |
|
|
|
|
17
|
|
|
&& $this->published_at != null; |
|
|
|
|
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public function isDraft() |
21
|
|
|
{ |
22
|
|
|
return $this->status == self::DRAFT |
23
|
|
|
&& $this->published_at == null; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function isScheduled() |
27
|
|
|
{ |
28
|
|
|
return $this->status == self::SCHEDULED |
29
|
|
|
&& $this->published_at > Carbon::now(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function isNotPublished() |
33
|
|
|
{ |
34
|
|
|
return $this->isDraft() || $this->isScheduled(); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function scheduleFor($date) |
38
|
|
|
{ |
39
|
|
|
if ( ! $date instanceof Carbon) { |
40
|
|
|
$date = new Carbon($date); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$this->update([ |
|
|
|
|
44
|
|
|
'status' => self::SCHEDULED, |
45
|
|
|
'published_at' => $date, |
46
|
|
|
]); |
47
|
|
|
|
48
|
|
|
return $this; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function publish() |
52
|
|
|
{ |
53
|
|
|
$this->update([ |
|
|
|
|
54
|
|
|
'status' => self::PUBLISHED, |
55
|
|
|
'published_at' => now(), |
56
|
|
|
]); |
57
|
|
|
|
58
|
|
|
return $this; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function getTimeToReadAttribute() |
62
|
|
|
{ |
63
|
|
|
$word_count = str_word_count(strip_tags($this->content)); |
|
|
|
|
64
|
|
|
|
65
|
|
|
$minutes = floor($word_count / 200); |
66
|
|
|
$seconds = floor($word_count % 200 / (200 / 60)); |
67
|
|
|
|
68
|
|
|
$str_minutes = ($minutes == 1) ? 'minute' : 'minutes'; |
69
|
|
|
$str_seconds = ($seconds == 1) ? 'second' : 'seconds'; |
70
|
|
|
|
71
|
|
|
if ($minutes == 0) { |
72
|
|
|
return "{$seconds} {$str_seconds}"; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return "{$minutes} {$str_minutes}, {$seconds} {$str_seconds}"; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: