Test Setup Failed
Pull Request — main (#28)
by Enrico
07:55
created

Post::generateStructuredDataScript()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 14
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 18
ccs 0
cts 0
cp 0
crap 2
rs 9.7998
1
<?php
2
3
namespace App\Models;
4
5
use App\Helpers\TextHelpers;
6
use App\Traits\HasStructuredData;
7
use Illuminate\Database\Eloquent\Factories\HasFactory;
8
use Illuminate\Database\Eloquent\Model;
9
use Spatie\MediaLibrary\HasMedia; //used for Gallery field
10
use Spatie\MediaLibrary\InteractsWithMedia; //used for Gallery field
11
use Spatie\MediaLibrary\MediaCollections\Models\Media; //used for Gallery field
12
use Spatie\ModelStatus\HasStatuses;
13
use Spatie\SchemaOrg\Schema;
14
use Spatie\SchemaOrg\Type;
15
use Spatie\Searchable\Searchable;
16
use Spatie\Searchable\SearchResult;
17
use Spatie\Sluggable\HasSlug;
18
use Spatie\Sluggable\SlugOptions;
19
use Spatie\Translatable\HasTranslations;
20
21
class Post extends Model implements HasMedia, Searchable
22
{
23
    use HasFactory;
24
    use HasSlug;
0 ignored issues
show
introduced by
The trait Spatie\Sluggable\HasSlug requires some properties which are not provided by App\Models\Post: $slugSeparator, $preventOverwrite, $maximumLength, $generateUniqueSlugs, $generateSlugsOnCreate, $slugField, $generateSlugFrom, $slugLanguage, $generateSlugsOnUpdate
Loading history...
25
    use HasTranslations;
26
    use HasStatuses;
0 ignored issues
show
Bug introduced by
The trait Spatie\ModelStatus\HasStatuses requires the property $statuses which is not provided by App\Models\Post.
Loading history...
27
    use InteractsWithMedia;
0 ignored issues
show
introduced by
The trait Spatie\MediaLibrary\InteractsWithMedia requires some properties which are not provided by App\Models\Post: $fallbackPath, $mediaConversionRegistrations, $forceDeleting, $fallbackUrl, $media, $collection_name
Loading history...
28
    use HasStructuredData;
29
30
    /**
31
     * The attributes that aren't mass assignable.
32
     *
33
     * @var array
34
     */
35
    protected $guarded = [];
36
37
    /**
38
     * The attributes that are translatable.
39
     *
40
     * @var array
41
     */
42
    public $translatable = ['title','intro_text', 'body', 'introimage_alt'];
43
44
    /**
45
     * The parameters used in the index view search filters.
46
     *
47
     * @var array
48
     */
49
    public const SEARCH_PARAMETERS = [
50
        'title',
51
        'categoryId',
52
        'startDate',
53
        'endDate',
54
        'status',
55
    ];
56
57
    /**
58
     * The possible values the publishing status can be.
59
     */
60
    public const PUBLISHING_STATUS = [
61
        'unpublished' => 'unpublished',
62
        'published' => 'published',
63
    ];
64
65 8
    /**
66
     * Generates a unique slug.
67 8
     */
68 8
    public function getSlugOptions(): SlugOptions
69 8
    {
70
        return SlugOptions::create()
71
            ->generateSlugsFrom('title')
72
            ->saveSlugsTo('slug');
73
    }
74
75
    /**
76
     * Returns the author of the post.
77
     */
78
    public function user()
79
    {
80
        return $this->belongsTo(User::class);
81
    }
82
83
    /**
84
     * Returns the categories of the post.
85
     */
86
    public function category()
87
    {
88
        return $this->belongsTo(PostCategory::class, 'category_id');
89
    }
90
91
    /**
92
     * Returns the insights related to the the post.
93
     */
94
    public function insights()
95
    {
96
        return $this->belongsToMany(Insight::class);
97
    }
98
99 2
    /**
100
     * Returns the tags associated to the post.
101 2
     */
102
    public function tags()
103
    {
104
        return $this->belongsToMany(Tag::class);
105
    }
106
107 1
    /**
108
     * Get all of the post's comments.
109 1
     */
110
    public function comments()
111
    {
112
        return $this->morphMany('App\Models\Comment', 'commentable');
113
    }
114
115
    /**
116
     * Returns the reading time of the post.
117
     *
118
     * @param string|null $format
119
     *
120
     * @return string
121
     */
122
    public function readingTime(string $format = null): string
123
    {
124
        return TextHelpers::estimateReadingTime($this->body, 200, $format);
125
    }
126
127
    /**
128
     * Add Image gallery support using:
129
     * https://spatie.be/docs/laravel-medialibrary/v8/introduction
130
     * https://github.com/ebess/advanced-nova-media-library
131
     *
132
     * @param \Spatie\MediaLibrary\MediaCollections\Models\Media|null $media
133
     *
134
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
135
     */
136
    public function registerMediaConversions(Media $media = null): void
137
    {
138
        $this->addMediaConversion('thumb')
139
            ->width(300)
140
            ->height(300);
141
142
        $this->addMediaConversion('facebook')
143
            ->width(1200)
144
            ->height(630);
145
146
        $this->addMediaConversion('twitter')
147
            ->width(1024)
148
            ->height(512);
149
    }
150
151
    public function registerMediaCollections(): void
152
    {
153
        $this->addMediaCollection('introimage')->singleFile();
154
        $this->addMediaCollection('images');
155
    }
156
157
    /**
158
     * Return true if the post is published
159
     *
160
     * @return bool
161 1
     */
162
    public function isPublished(): bool
163 1
    {
164
        return $this->latestStatus('unpublished', 'published') == 'published';
165
    }
166
167
    /**
168
     * Return the post publishing status
169
     *
170
     * @return string
171
     */
172
    public function publishingStatus(): string
173
    {
174
        return $this->latestStatus('unpublished', 'published');
175
    }
176
177
    /**
178
     * Method required by Spatie Laravel Searchable
179
     */
180
    public function getSearchResult(): SearchResult
181
    {
182
        $url = route('posts.edit', $this->id);
183
184
        return new SearchResult(
185
            $this,
186
            $this->title,
187
            $url
188
        );
189
    }
190
191
    /**
192
     * Factory method for generating the script for a blog post Schema.org type.
193
     *
194
     * @return Type
195
     */
196
    protected function generateStructuredDataScript(): Type
197
    {
198
        return Schema::blogPosting()
199
            ->name($this->title)
200
            ->headline($this->title)
201
            ->if($this->hasMedia('introimage'), function (\Spatie\SchemaOrg\BlogPosting $schema) {
202
                $schema->image($this->getMedia('introimage')->first()->getUrl());
203
            })
204
            ->about($this->category->name)
0 ignored issues
show
Bug introduced by
$this->category->name of type string is incompatible with the type Spatie\SchemaOrg\Contrac...Contracts\ThingContract expected by parameter $about of Spatie\SchemaOrg\BlogPosting::about(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

204
            ->about(/** @scrutinizer ignore-type */ $this->category->name)
Loading history...
205
            ->description($this->intro_text)
206
            ->author(Schema::person()
207
                ->name($this->user->profile->full_name)
208
            )
209
            ->dateCreated($this->created_at)
0 ignored issues
show
Bug introduced by
$this->created_at of type string is incompatible with the type DateTimeInterface[]&DateTimeInterface expected by parameter $dateCreated of Spatie\SchemaOrg\BlogPosting::dateCreated(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

209
            ->dateCreated(/** @scrutinizer ignore-type */ $this->created_at)
Loading history...
210
            ->datePublished($this->created_at)
0 ignored issues
show
Bug introduced by
$this->created_at of type string is incompatible with the type DateTimeInterface[]&DateTimeInterface expected by parameter $datePublished of Spatie\SchemaOrg\BlogPosting::datePublished(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

210
            ->datePublished(/** @scrutinizer ignore-type */ $this->created_at)
Loading history...
211
            ->dateModified($this->updated_at)
0 ignored issues
show
Bug introduced by
$this->updated_at of type string is incompatible with the type DateTimeInterface[]&DateTimeInterface expected by parameter $dateModified of Spatie\SchemaOrg\BlogPosting::dateModified(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

211
            ->dateModified(/** @scrutinizer ignore-type */ $this->updated_at)
Loading history...
212
            ->mainEntityOfPage(Schema::webPage()
213
                ->url(env('APP_URL').'/posts/'.$this->slug)
214
            );
215
    }
216
}
217