Passed
Push — analysis-Yjrw2v ( 23ef57 )
by Philippe
125:41 queued 115:07
created

Page::isPublished()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Thinktomorrow\Chief\Pages;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Support\Collection;
7
use Illuminate\Database\Eloquent\Model;
8
use Thinktomorrow\Chief\Modules\Module;
9
use Thinktomorrow\Chief\Audit\AuditTrait;
10
use Thinktomorrow\Chief\Concerns\Featurable;
11
use Thinktomorrow\Chief\Menu\ActsAsMenuItem;
12
use Illuminate\Database\Eloquent\SoftDeletes;
13
use Thinktomorrow\Chief\Relations\ActsAsChild;
14
use Thinktomorrow\Chief\Snippets\WithSnippets;
15
use Thinktomorrow\Chief\Relations\ActsAsParent;
16
use Thinktomorrow\Chief\Urls\MemoizedUrlRecord;
17
use Thinktomorrow\Chief\Urls\UrlRecordNotFound;
18
use Thinktomorrow\Chief\Management\ManagedModel;
19
use Thinktomorrow\Chief\Relations\ActingAsChild;
20
use Thinktomorrow\AssetLibrary\AssetTrait;
21
use Thinktomorrow\Chief\Relations\ActingAsParent;
22
use Thinktomorrow\Chief\Concerns\Viewable\Viewable;
23
use Thinktomorrow\Chief\Concerns\Morphable\Morphable;
24
use Thinktomorrow\Chief\FlatReferences\FlatReference;
25
use Thinktomorrow\Chief\Urls\ProvidesUrl\ProvidesUrl;
26
use Thinktomorrow\Chief\Concerns\Archivable\Archivable;
27
use Thinktomorrow\Chief\Urls\ProvidesUrl\ResolvingRoute;
28
use Thinktomorrow\Chief\Concerns\Publishable\Publishable;
29
use Thinktomorrow\Chief\Concerns\Translatable\Translatable;
30
use Thinktomorrow\Chief\Concerns\Viewable\ViewableContract;
31
use Astrotomic\Translatable\Translatable as BaseTranslatable;
32
use Thinktomorrow\AssetLibrary\HasAsset;
33
use Thinktomorrow\Chief\Concerns\Morphable\MorphableContract;
34
use Thinktomorrow\Chief\Concerns\Translatable\TranslatableContract;
35
36
class Page extends Model implements ManagedModel, TranslatableContract, HasAsset, ActsAsParent, ActsAsChild, ActsAsMenuItem, MorphableContract, ViewableContract, ProvidesUrl
37
{
38
    use BaseTranslatable {
0 ignored issues
show
Bug introduced by
The trait Astrotomic\Translatable\Translatable requires the property $each which is not provided by Thinktomorrow\Chief\Pages\Page.
Loading history...
39
        getAttribute as getTranslatableAttribute;
40
    }
41
42
    use Morphable,
0 ignored issues
show
Bug introduced by
The trait Thinktomorrow\Chief\Concerns\Morphable\Morphable requires the property $morph_key which is not provided by Thinktomorrow\Chief\Pages\Page.
Loading history...
introduced by
The trait Thinktomorrow\Chief\Concerns\Viewable\Viewable requires some properties which are not provided by Thinktomorrow\Chief\Pages\Page: $content, $viewKey
Loading history...
introduced by
The trait Thinktomorrow\AssetLibrary\AssetTrait requires some properties which are not provided by Thinktomorrow\Chief\Pages\Page: $assetRelation, $pivot, $fallbackPath, $assetFallbackLocale, $each, $locale, $mediaConversionRegistrations, $useAssetFallbackLocale, $fallbackUrl, $media, $collection_name
Loading history...
43
        AssetTrait,
44
        Translatable,
45
        SoftDeletes,
46
        Publishable,
47
        Featurable,
48
        Archivable,
49
        AuditTrait,
50
        ActingAsParent,
51
        ActingAsChild,
52
        WithSnippets,
53
        ResolvingRoute,
54
        Viewable;
55
56
    // Explicitly mention the translation model so on inheritance the child class uses the proper default translation model
57
    protected $translationModel      = PageTranslation::class;
58
    protected $translationForeignKey = 'page_id';
59
    protected $translatedAttributes  = [
60
        'title', 'content', 'short', 'seo_title', 'seo_description', 'seo_keywords', 'seo_image'
61
    ];
62
63
    public $table          = "pages";
64
    protected $guarded     = [];
65
    protected $with        = ['translations'];
66
67
    protected $baseViewPath;
68
    protected static $baseUrlSegment = '/';
69
70
    protected static $cachedUrls = [];
71
72
    public static function clearCachedUrls()
73
    {
74
        static::$cachedUrls = null;
75
    }
76
77
    public function __construct(array $attributes = [])
78
    {
79
        $this->constructWithSnippets();
80
81
        if (!isset($this->baseViewPath)) {
82
            $this->baseViewPath = config('thinktomorrow.chief.base-view-paths.pages', 'pages');
83
        }
84
85
        parent::__construct($attributes);
86
    }
87
88
    public static function managedModelKey(): string
89
    {
90
        if (isset(static::$managedModelKey)) {
91
            return static::$managedModelKey;
0 ignored issues
show
Bug introduced by
The property managedModelKey does not seem to exist on Thinktomorrow\Chief\Pages\Page. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
92
        }
93
94
        throw new \Exception('Missing required static property \'managedModelKey\' on ' . static::class. '.');
95
    }
96
97
    /**
98
     * Parse and render any found snippets in custom
99
     * or translatable attribute values.
100
     *
101
     * @param string $value
102
     * @return mixed|null|string|string[]
103
     */
104
    public function getAttribute($value)
105
    {
106
        $value = $this->getTranslatableAttribute($value);
107
108
        if ($this->shouldParseWithSnippets($value)) {
109
            $value = $this->parseWithSnippets($value);
110
        }
111
112
        return $value;
113
    }
114
115
    /**
116
     * Page specific modules. We exclude text modules since they are modules in pure
117
     * technical terms and not so much as behavioural elements for the admin.
118
     *
119
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
120
     */
121
    public function modules()
122
    {
123
        return $this->hasMany(Module::class, 'page_id')->where('morph_key', '<>', 'text');
124
    }
125
126
    public function flatReference(): FlatReference
127
    {
128
        return new FlatReference(static::class, $this->id);
129
    }
130
131
    public function flatReferenceLabel(): string
132
    {
133
        if ($this->exists) {
134
            $status = ! $this->isPublished() ? ' [' . $this->statusAsPlainLabel().']' : null;
135
136
            return $this->title ? $this->title . $status : '';
0 ignored issues
show
Bug introduced by
The property title does not seem to exist on Thinktomorrow\Chief\Pages\Page. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
137
        }
138
139
        return '';
140
    }
141
142
    public function flatReferenceGroup(): string
143
    {
144
        $classKey = get_class($this);
145
        if (property_exists($this, 'labelSingular')) {
146
            $labelSingular =  $this->labelSingular;
0 ignored issues
show
Bug introduced by
The property labelSingular does not seem to exist on Thinktomorrow\Chief\Pages\Page. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
147
        } else {
148
            $labelSingular = Str::singular($classKey);
149
        }
150
151
        return $labelSingular;
152
    }
153
154
    public function mediaUrls($type = null): Collection
155
    {
156
        $assets = $this->assets($type, app()->getLocale())->map->url();
0 ignored issues
show
introduced by
The method getLocale() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

156
        $assets = $this->assets($type, app()->/** @scrutinizer ignore-call */ getLocale())->map->url();
Loading history...
157
158
        if ($assets->first() == null) {
159
            $assets = $this->assets($type)->map->url();
160
        }
161
162
        return $assets;
163
    }
164
165
    public function mediaUrl($type = null): ?string
166
    {
167
        return $this->mediaUrls($type)->first();
168
    }
169
170
    public static function findPublished($id)
171
    {
172
        return static::published()->find($id);
173
    }
174
175
    public function scopeSortedByCreated($query)
176
    {
177
        $query->orderBy('created_at', 'DESC');
178
    }
179
180
    /** @inheritdoc */
181
    public function url(string $locale = null): string
182
    {
183
        if (!$locale) {
184
            $locale = app()->getLocale();
185
        }
186
        try {
187
            $memoizedKey = $this->getMorphClass().'-'.$this->id.'-'.$locale;
188
189
            if (isset(static::$cachedUrls[$memoizedKey])) {
190
                return static::$cachedUrls[$memoizedKey];
191
            }
192
193
            $slug = MemoizedUrlRecord::findByModel($this, $locale)->slug;
194
195
            return static::$cachedUrls[$memoizedKey] = $this->resolveUrl($locale, [$slug]);
196
        } catch (UrlRecordNotFound $e) {
197
            return '';
198
        }
199
    }
200
201
    public function resolveUrl(string $locale = null, $parameters = null): string
202
    {
203
        $routeName = config('thinktomorrow.chief.route.name');
204
205
        return $this->resolveRoute($routeName, $parameters, $locale);
0 ignored issues
show
Bug introduced by
It seems like $locale can also be of type string; however, parameter $locale of Thinktomorrow\Chief\Pages\Page::resolveRoute() does only seem to accept null, maybe add an additional type check? ( Ignorable by Annotation )

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

205
        return $this->resolveRoute($routeName, $parameters, /** @scrutinizer ignore-type */ $locale);
Loading history...
206
    }
207
208
    /** @inheritdoc */
209
    public function previewUrl(string $locale = null): string
210
    {
211
        return $this->url($locale).'?preview-mode';
212
    }
213
214
215
    /** @inheritdoc */
216
    public static function baseUrlSegment(string $locale = null): string
217
    {
218
        if (!isset(static::$baseUrlSegment)) {
219
            return '/';
220
        }
221
222
        if (!is_array(static::$baseUrlSegment)) {
0 ignored issues
show
introduced by
The condition is_array(static::baseUrlSegment) is always false.
Loading history...
223
            return static::$baseUrlSegment;
224
        }
225
226
        // When an array, we try to locate the expected segment by locale
227
        $key = $locale ?? app()->getlocale();
228
229
        if (isset(static::$baseUrlSegment[$key])) {
230
            return static::$baseUrlSegment[$key];
231
        }
232
233
        $fallback_locale = config('app.fallback_locale');
234
        if (isset(static::$baseUrlSegment[$fallback_locale])) {
235
            return static::$baseUrlSegment[$fallback_locale];
236
        }
237
238
        // Fall back to first entry in case no match is found
239
        return reset(static::$baseUrlSegment);
240
    }
241
242
    public function menuLabel(): string
243
    {
244
        return $this->title ?? '';
0 ignored issues
show
Bug introduced by
The property title does not seem to exist on Thinktomorrow\Chief\Pages\Page. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
245
    }
246
247
    /**
248
     * We override the publishable trait defaults because Page needs
249
     * to be concerned with the archived state as well.
250
     *
251
     * TODO: IMPROVEMENT SHOULD BE TO MANAGE THE PAGE STATES IN ONE LOCATION. eg state machine
252
     */
253
    public function isPublished()
254
    {
255
        return (!!$this->published && is_null($this->archived_at));
256
    }
257
258
    public function isDraft()
259
    {
260
        return (!$this->published && is_null($this->archived_at));
261
    }
262
263
    public function publish()
264
    {
265
        $this->published = 1;
266
        $this->archived_at = null;
267
268
        $this->save();
269
    }
270
271
    public function draft()
272
    {
273
        $this->published = 0;
274
        $this->archived_at = null;
275
276
        $this->save();
277
    }
278
279
    public function statusAsLabel()
280
    {
281
        if ($this->isPublished()) {
282
            return '<a href="'.$this->url().'" target="_blank"><em>online</em></a>';
283
        }
284
285
        if ($this->isDraft()) {
286
            return '<a href="'.$this->previewUrl().'" target="_blank" class="text-error"><em>offline</em></a>';
287
        }
288
289
        if ($this->isArchived()) {
290
            return '<span><em>gearchiveerd</em></span>';
291
        }
292
293
        return '-';
294
    }
295
296
    public function statusAsPlainLabel()
297
    {
298
        if ($this->isPublished()) {
299
            return 'online';
300
        }
301
302
        if ($this->isDraft()) {
303
            return 'offline';
304
        }
305
306
        if ($this->isArchived()) {
307
            return 'gearchiveerd';
308
        }
309
310
        return '-';
311
    }
312
}
313