Passed
Push — ft/urls ( c085ae...625b56 )
by Ben
26:26
created

PageManager::addDefaultShortDescription()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Thinktomorrow\Chief\Pages;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Str;
7
use Thinktomorrow\Chief\Audit\Audit;
8
use Thinktomorrow\Chief\Fields\Fields;
9
use Thinktomorrow\Chief\Filters\Filters;
10
use Thinktomorrow\Chief\Fields\FieldsTab;
11
use Thinktomorrow\Chief\Management\Manager;
12
use Thinktomorrow\Chief\Fields\Types\TextField;
13
use Thinktomorrow\Chief\Fields\FieldArrangement;
14
use Thinktomorrow\Chief\Fields\Types\InputField;
15
use Thinktomorrow\Chief\Fields\Types\MediaField;
16
use Thinktomorrow\Chief\Management\Registration;
17
use Thinktomorrow\Chief\Fields\RemainingFieldsTab;
18
use Thinktomorrow\Chief\Management\AbstractManager;
19
use Thinktomorrow\Chief\Management\Assistants\ArchiveAssistant;
20
use Thinktomorrow\Chief\Management\Assistants\PublishAssistant;
21
use Thinktomorrow\Chief\Management\Assistants\UrlAssistant;
22
use Thinktomorrow\Chief\Management\Details\Details;
23
use Thinktomorrow\Chief\Pages\Application\DeletePage;
24
use Thinktomorrow\Chief\Management\Exceptions\DeleteAborted;
25
use Thinktomorrow\Chief\Management\Exceptions\NotAllowedManagerRoute;
26
27
class PageManager extends AbstractManager implements Manager
28
{
29
    /** @var PageBuilderField */
0 ignored issues
show
Bug introduced by
The type Thinktomorrow\Chief\Pages\PageBuilderField was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
    private $pageBuilderField;
31
32
    protected $assistants = [
33
        'url' => UrlAssistant::class,
34
        'archive' => ArchiveAssistant::class,
35
        'publish' => PublishAssistant::class,
36
    ];
37
38 72
    public function __construct(Registration $registration)
39
    {
40 72
        parent::__construct($registration);
41 72
    }
42
43 66
    public function can($verb): bool
44
    {
45
        try {
46 66
            $this->authorize($verb);
47 1
        } catch (NotAllowedManagerRoute $e) {
48 1
            return false;
49
        }
50
51 65
        return parent::can($verb);
52
    }
53
54
    /**
55
     * @param $verb
56
     * @throws NotAllowedManagerRoute
57
     */
58 66
    private function authorize($verb)
59
    {
60 66
        $permission = 'update-page';
61
62 66
        if (in_array($verb, ['index','show'])) {
63 17
            $permission = 'view-page';
64 53
        } elseif (in_array($verb, ['create','store'])) {
65 17
            $permission = 'create-page';
66 40
        } elseif (in_array($verb, ['delete'])) {
67 4
            $permission = 'delete-page';
68
        }
69
70 66
        if (! auth()->guard('chief')->user()->hasPermissionTo($permission)) {
0 ignored issues
show
Bug introduced by
The method hasPermissionTo() does not exist on Illuminate\Contracts\Auth\Authenticatable. It seems like you code against a sub-type of Illuminate\Contracts\Auth\Authenticatable such as Illuminate\Foundation\Auth\User. ( Ignorable by Annotation )

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

70
        if (! auth()->guard('chief')->user()->/** @scrutinizer ignore-call */ hasPermissionTo($permission)) {
Loading history...
71 1
            throw NotAllowedManagerRoute::notAllowedPermission($permission, $this);
72
        }
73 65
    }
74
75
    /**
76
     * The set of fields that should be manageable for a certain model.
77
     *
78
     * Additionally, you should:
79
     * 1. Make sure to setup the proper migrations and
80
     * 2. For a translatable field you should add this field to the $translatedAttributes property of the model as well.
81
     *
82
     * @return Fields
83
     */
84 43
    public function fields(): Fields
85
    {
86 43
        return parent::fields()->add(
87 43
            $this->pageBuilderField(),
88 43
            InputField::make('title')->translatable($this->model->availableLocales())
0 ignored issues
show
Bug introduced by
It seems like Thinktomorrow\Chief\Fiel...erzichten en modules.') can also be of type null; however, parameter $fields of Thinktomorrow\Chief\Fields\Fields::add() does only seem to accept Thinktomorrow\Chief\Fields\Types\Field, 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

88
            /** @scrutinizer ignore-type */ InputField::make('title')->translatable($this->model->availableLocales())
Loading history...
Bug introduced by
The method availableLocales() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

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

88
            InputField::make('title')->translatable($this->model->/** @scrutinizer ignore-call */ availableLocales())

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
89 43
                                     ->validation('required-fallback-locale|max:200', [], [
90 43
                                         'trans.'.config('app.fallback_locale', 'nl').'.title' => 'title',
91
                                     ])
92 43
                                     ->label('De titel van je '.$this->model->labelSingular ?? 'pagina')
0 ignored issues
show
Bug introduced by
The method label() does not exist on Thinktomorrow\Chief\Fields\Types\InputField. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

92
                                     ->/** @scrutinizer ignore-call */ label('De titel van je '.$this->model->labelSingular ?? 'pagina')
Loading history...
93 43
                                     ->description('Dit is de titel die zal worden getoond in de overzichten en modules.'),
0 ignored issues
show
Bug introduced by
The method description() does not exist on Thinktomorrow\Chief\Fields\Types\InputField. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

93
                                     ->/** @scrutinizer ignore-call */ description('Dit is de titel die zal worden getoond in de overzichten en modules.'),
Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
94 43
            InputField::make('seo_title')
95 43
                ->translatable($this->model->availableLocales())
96 43
                ->label('Zoekmachine titel'),
97 43
            TextField::make('seo_description')
98 43
                ->translatable($this->model->availableLocales())
99 43
                ->label('Zoekmachine omschrijving')
0 ignored issues
show
Bug introduced by
The method label() does not exist on Thinktomorrow\Chief\Fields\Types\TextField. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

99
                ->/** @scrutinizer ignore-call */ label('Zoekmachine omschrijving')
Loading history...
100 43
                ->description('omschrijving van de pagina zoals in search engines (o.a. google) wordt weergegeven.'),
0 ignored issues
show
Bug introduced by
The method description() does not exist on Thinktomorrow\Chief\Fields\Types\TextField. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

100
                ->/** @scrutinizer ignore-call */ description('omschrijving van de pagina zoals in search engines (o.a. google) wordt weergegeven.'),
Loading history...
101 43
            InputField::make('seo_keywords')
102 43
                ->translatable($this->model->availableLocales())
103 43
                ->label('Zoekmachine sleutelwoorden')
104 43
                ->description('sleutelwoorden van de pagina waarop in search engines (o.a google) gezocht kan worden.'),
105 43
            MediaField::make('seo_image')
106 43
                ->translatable($this->model->availableLocales())
107 43
                ->label('Zoekmachine foto')
0 ignored issues
show
Bug introduced by
The method label() does not exist on Thinktomorrow\Chief\Fields\Types\MediaField. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

107
                ->/** @scrutinizer ignore-call */ label('Zoekmachine foto')
Loading history...
108 43
                ->description('foto die bij het delen van deze pagina getoont word. (afmeting: 1200x627px)')
0 ignored issues
show
Bug introduced by
The method description() does not exist on Thinktomorrow\Chief\Fields\Types\MediaField. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

108
                ->/** @scrutinizer ignore-call */ description('foto die bij het delen van deze pagina getoont word. (afmeting: 1200x627px)')
Loading history...
109
        );
110
    }
111
112
    public static function filters(): Filters
113
    {
114
        return new Filters([
115
            PublishedFilter::class
116
        ]);
117
    }
118
119 43
    private function pageBuilderField()
120
    {
121 43
        if ($this->pageBuilderField) {
122 38
            return $this->pageBuilderField;
123
        }
124
125 43
        return $this->pageBuilderField = $this->createPagebuilderField();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->createPagebuilderField() of type Thinktomorrow\Chief\Fields\Types\PagebuilderField is incompatible with the declared type Thinktomorrow\Chief\Pages\PageBuilderField of property $pageBuilderField.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
126
    }
127
128 2
    public function fieldArrangement($key = null): FieldArrangement
129
    {
130 2
        if ($key == 'create') {
131
            return new FieldArrangement($this->fieldsWithAssistantFields()->filterBy(function ($field) {
132 1
                return in_array($field->key, ['title']);
133 1
            }));
134
        }
135
136 1
        return new FieldArrangement($this->fieldsWithAssistantFields(), [
137 1
            new FieldsTab('pagina', ['sections']),
138 1
            new RemainingFieldsTab('inhoud'),
139 1
            new FieldsTab('eigen modules', [], 'chief::back.pages._partials.modules'),
140 1
            new FieldsTab('seo', ['seo_title', 'seo_description', 'seo_keywords', 'seo_image']),
141
        ]);
142
    }
143
144 66
    public function details(): Details
145
    {
146
        // For existing model
147 66
        if ($this->model->id) {
148 52
            return parent::details()
149 52
                ->set('title', $this->model->title)
150 52
                ->set('intro', 'laatst aangepast op ' . $this->model->updated_at->format('d/m/Y H:i'))
151 52
                ->set('context', '<span class="inline-s">' . $this->assistant('publish')->publicationStatusAsLabel() . '</span>');
0 ignored issues
show
Bug introduced by
The method publicationStatusAsLabel() does not exist on Thinktomorrow\Chief\Mana...nt\Assistants\Assistant. It seems like you code against a sub-type of Thinktomorrow\Chief\Mana...nt\Assistants\Assistant such as Thinktomorrow\Chief\Mana...stants\PublishAssistant. ( Ignorable by Annotation )

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

151
                ->set('context', '<span class="inline-s">' . $this->assistant('publish')->/** @scrutinizer ignore-call */ publicationStatusAsLabel() . '</span>');
Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 130 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
152
        }
153
154 17
        return parent::details();
155
    }
156
157 44
    public function saveFields(): Manager
158
    {
159
        // Store the morph_key upon creation
160 44
        if (! $this->model->morph_key) {
161 14
            $this->model->morph_key = $this->model->morphKey();
0 ignored issues
show
Bug introduced by
The method morphKey() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

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

161
            /** @scrutinizer ignore-call */ 
162
            $this->model->morph_key = $this->model->morphKey();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
162
        }
163
164 44
        return parent::saveFields();
165
    }
166
167 4
    public function delete()
168
    {
169 4
        if (request()->get('deleteconfirmation') !== 'DELETE') {
170 1
            throw new DeleteAborted();
171
        }
172
173 3
        app(DeletePage::class)->handle($this->model->id);
174 3
    }
175
176 16
    public function storeRequest(Request $request): Request
177
    {
178 16
        $trans = [];
179 16
        $urls = $request->get('url-slugs', []);
180
181 16
        foreach ($request->get('trans', []) as $locale => $translation) {
182 15
            if (is_array_empty($translation)) {
183 1
                continue;
184
            }
185
186 15
            $trans[$locale] = $this->addDefaultShortDescription($translation);
187
188
            // Automatically add an url for this locale based on the given title
189 15
            if (!isset($urls[$locale]) && isset($translation['title'])) {
190 15
                $urls[$locale] = Str::slug($translation['title']);
191
            }
192
        }
193
194
        // Merge with request...
195 16
        return $request->merge(['trans' => $trans, 'url-slugs' => $urls]);
196
    }
197
198 35
    public function updateRequest(Request $request): Request
199
    {
200 35
        $trans = [];
201 35
        foreach ($request->get('trans', []) as $locale => $translation) {
202 34
            if (is_array_empty($translation)) {
203
204
                // Nullify all values
205
                $trans[$locale] = array_map(function ($value) {
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed. ( Ignorable by Annotation )

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

205
                $trans[$locale] = array_map(function (/** @scrutinizer ignore-unused */ $value) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
206 2
                    return null;
207 2
                }, $translation);
208 2
                continue;
209
            }
210
211 34
            $trans[$locale] = $this->addDefaultShortDescription($translation);
212
        }
213
214
        // Merge with request...
215 35
        return $request->merge(['trans' => $trans]);
216
    }
217
218 14
    public function afterStore($request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

218
    public function afterStore(/** @scrutinizer ignore-unused */ $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
219
    {
220 14
        Audit::activity()
221 14
            ->performedOn($this->model)
0 ignored issues
show
Bug introduced by
It seems like $this->model can also be of type Illuminate\Contracts\Foundation\Application; however, parameter $model of Spatie\Activitylog\ActivityLogger::performedOn() does only seem to accept Illuminate\Database\Eloquent\Model, 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

221
            ->performedOn(/** @scrutinizer ignore-type */ $this->model)
Loading history...
222 14
            ->log('created');
223 14
    }
224
225 33
    public function afterUpdate($request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

225
    public function afterUpdate(/** @scrutinizer ignore-unused */ $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
226
    {
227 33
        Audit::activity()
228 33
            ->performedOn($this->model)
0 ignored issues
show
Bug introduced by
It seems like $this->model can also be of type Illuminate\Contracts\Foundation\Application; however, parameter $model of Spatie\Activitylog\ActivityLogger::performedOn() does only seem to accept Illuminate\Database\Eloquent\Model, 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

228
            ->performedOn(/** @scrutinizer ignore-type */ $this->model)
Loading history...
229 33
            ->log('edited');
230 33
    }
231
232
    /**
233
     * @param array $translation
234
     * @return array
235
     */
236 46
    private function addDefaultShortDescription(array $translation): array
237
    {
238 46
        if (isset($translation['content'])) {
239 1
            $translation['short'] = $translation['short'] ?? teaser($translation['content'], 100);
240
        }
241
242 46
        return $translation;
243
    }
244
}
245