Passed
Push — fix/module-slug ( 15002a )
by Ben
09:40
created

ManagesPagebuilder::findEditUrl()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 6
dl 0
loc 10
rs 10
c 1
b 1
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
4
namespace Thinktomorrow\Chief\Management;
5
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Facades\DB;
8
use Thinktomorrow\Chief\Pages\Page;
9
use Thinktomorrow\Chief\Sets\SetReference;
10
use Thinktomorrow\Chief\Modules\TextModule;
11
use Thinktomorrow\Chief\Modules\PagetitleModule;
12
use Thinktomorrow\Chief\Sets\StoredSetReference;
13
use Thinktomorrow\Chief\PageBuilder\UpdateSections;
14
use Thinktomorrow\Chief\Relations\AvailableChildren;
15
use Thinktomorrow\Chief\Fields\Types\PagebuilderField;
16
use Thinktomorrow\Chief\Tests\Fakes\NewsletterModuleFake;
17
use Thinktomorrow\Chief\FlatReferences\FlatReferencePresenter;
18
use Thinktomorrow\Chief\Concerns\Translatable\TranslatableContract;
19
20
trait ManagesPagebuilder
21
{
22
    /**
23
     * The naming convention is important here because to hook into the saving
24
     * flow it needs to have the save<key>Field method naming.
25
     *
26
     * @param PagebuilderField $field
27
     * @param Request $request
28
     */
29
    public function saveSectionsField(PagebuilderField $field, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $field 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

29
    public function saveSectionsField(/** @scrutinizer ignore-unused */ PagebuilderField $field, Request $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...
30
    {
31
        $sections = $request->get('sections', []);
32
33
        $modules = $sections['modules'] ?? [];
34
        $text    = $sections['text'] ?? [];
35
        $sets    = $sections['pagesets'] ?? [];
36
        $order   = $sections['order'] ?? [];
37
38
        UpdateSections::forModel($this->model, $modules, $text, $sets, $order)
39
            ->updateModules()
40
            ->updateSets()
41
            ->addTextModules()
42
            ->updateTextModules()
43
            ->sort();
44
    }
45
46
    protected function createPagebuilderField(): PagebuilderField
47
    {
48
        $model = $this->model;
49
50
        $availableChildren = AvailableChildren::forParent($model);
51
52
        $modules = $availableChildren->onlyModules()->reject(function ($module) use ($model) {
53
            return $module->page_id != null && $module->page_id != $model->id;
54
        });
55
56
        $available_modules = FlatReferencePresenter::toGroupedSelectValues($modules)->toArray();
57
        $available_pages = FlatReferencePresenter::toGroupedSelectValues($availableChildren->onlyPages())->toArray();
58
        $available_sets = FlatReferencePresenter::toGroupedSelectValues($availableChildren->onlySets())->toArray();
59
60
        // Current sections
61
        $sections = $model->children()->map(function ($section, $index) {
62
            if ($section instanceof TranslatableContract) {
63
                $section->injectTranslationForForm();
0 ignored issues
show
Bug introduced by
The method injectTranslationForForm() does not exist on Thinktomorrow\Chief\Conc...le\TranslatableContract. Since it exists in all sub-types, consider adding an abstract or default implementation to Thinktomorrow\Chief\Conc...le\TranslatableContract. ( Ignorable by Annotation )

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

63
                $section->/** @scrutinizer ignore-call */ 
64
                          injectTranslationForForm();
Loading history...
64
            }
65
66
            return [
67
                // Module reference is by id.
68
                'id'         => $section->flatReference()->get(),
69
70
                // Key is a separate value to assign each individual module.
71
                // This is separate from id to avoid vue key binding conflicts.
72
                'key'        => $section->flatReference()->get(),
73
                'type'       => $this->guessPagebuilderSectionType($section),
74
                'slug'       => $section->slug,
75
                'editUrl'    => $this->findEditUrl($section),
76
                'sort'       => $index,
77
                'trans'      => $section->trans ?? [],
78
            ];
79
        })->toArray();
80
81
        return PagebuilderField::make('sections')
0 ignored issues
show
Bug Best Practice introduced by
The expression return Thinktomorrow\Chi...leSets($available_sets) could return the type null|string which is incompatible with the type-hinted return Thinktomorrow\Chief\Fields\Types\PagebuilderField. Consider adding an additional type-check to rule them out.
Loading history...
82
                                ->translatable($this->model->availableLocales())
83
                                ->sections($sections)
84
                                ->availablePages($available_pages)
85
                                ->availableModules($available_modules)
86
                                ->availableSets($available_sets);
87
    }
88
89
    /**
90
     * @param $model
91
     * @return string|null
92
     */
93
    private function findEditUrl($model): ?string
94
    {
95
        if (! $model instanceof ManagedModel) {
96
            return null;
97
        }
98
99
        try {
100
            return app(Managers::class)->findByModel($model)->route('edit');
101
        } catch (NonRegisteredManager $e) {
102
            return null;
103
        }
104
    }
105
106
    /**
107
     * Section type is the grouping inside the pagebuilder (specifically the menu)
108
     *
109
     * @param $section
110
     * @return string
111
     */
112
    private function guessPagebuilderSectionType($section)
113
    {
114
        if ($section instanceof TextModule) {
115
            return 'text';
116
        }
117
118
        if ($section instanceof PagetitleModule) {
119
            return 'pagetitle';
120
        }
121
122
        if ($section instanceof StoredSetReference || $section instanceof SetReference) {
123
            // TODO: clean this up and replace 'pageset' with 'set';
124
            return 'pageset';
125
        }
126
127
        if ($section instanceof Page) {
128
            return 'page';
129
        }
130
131
        // We want all other types to be registered as modules
132
        return 'module';
133
    }
134
}
135