Completed
Pull Request — master (#29)
by Robbie
109:46 queued 107:23
created

BasePage::getAvailableTranslations()   C

Complexity

Conditions 9
Paths 67

Size

Total Lines 50
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 28
nc 67
nop 0
dl 0
loc 50
rs 6
c 0
b 0
f 0
1
<?php
2
3
namespace CWP\CWP\PageTypes;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\Control\Director;
7
use SilverStripe\Forms\FieldList;
8
use SilverStripe\Forms\GridField\GridField;
9
use SilverStripe\Forms\GridField\GridFieldAddExistingAutocompleter;
10
use SilverStripe\Forms\GridField\GridFieldAddNewButton;
11
use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor;
12
use SilverStripe\Forms\GridField\GridFieldDataColumns;
13
use SilverStripe\Forms\GridField\GridFieldEditButton;
14
use SilverStripe\Forms\GridField\GridFieldFilterHeader;
15
use SilverStripe\Forms\TreeMultiselectField;
16
use SilverStripe\Taxonomy\TaxonomyTerm;
17
use SilverStripe\Versioned\Versioned;
18
use SilverStripe\View\ArrayData;
19
use TractorCow\Fluent\Model\Locale;
0 ignored issues
show
Bug introduced by
The type TractorCow\Fluent\Model\Locale 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...
20
use TractorCow\Fluent\State\FluentState;
0 ignored issues
show
Bug introduced by
The type TractorCow\Fluent\State\FluentState 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...
21
use UndefinedOffset\SortableGridField\Forms\GridFieldSortableRows;
0 ignored issues
show
Bug introduced by
The type UndefinedOffset\Sortable...s\GridFieldSortableRows 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...
22
23
/**
24
 * **BasePage** is the foundation which can be used for constructing your own pages.
25
 * By default it is hidden from the CMS - we rely on developers creating their own
26
 * `Page` class in the `mysite/code` which will extend from the **BasePage**.
27
 */
28
29
class BasePage extends SiteTree
30
{
31
    private static $icon = 'cwp/cwp:images/icons/sitetree_images/page.png';
0 ignored issues
show
introduced by
The private property $icon is not used, and could be removed.
Loading history...
32
33
    /**
34
     * Hide this page type from the CMS. hide_ancestor is slightly misnamed, should really be just "hide"
35
     *
36
     * {@inheritDoc}
37
     */
38
    private static $hide_ancestor = BasePage::class;
0 ignored issues
show
introduced by
The private property $hide_ancestor is not used, and could be removed.
Loading history...
39
40
    /**
41
     * @config
42
     * @var bool
43
     */
44
    private static $pdf_export = false;
0 ignored issues
show
introduced by
The private property $pdf_export is not used, and could be removed.
Loading history...
45
46
    /**
47
     * Domain to generate PDF's from, DOES not include protocol
48
     * i.e. google.com not http://google.com
49
     * @config
50
     * @var string
51
     */
52
    private static $pdf_base_url = "";
0 ignored issues
show
introduced by
The private property $pdf_base_url is not used, and could be removed.
Loading history...
53
54
    /**
55
     * Allow custom overriding of the path to the WKHTMLTOPDF binary, in cases
56
     * where multiple versions of the binary are available to choose from. This
57
     * should be the full path to the binary (e.g. /usr/local/bin/wkhtmltopdf)
58
     * @see BasePage_Controller::generatePDF();
59
     *
60
     * @config
61
     * @var string|null
62
     */
63
    private static $wkhtmltopdf_binary = null;
0 ignored issues
show
introduced by
The private property $wkhtmltopdf_binary is not used, and could be removed.
Loading history...
64
65
    /**
66
     * Where to store generated PDF files
67
     *
68
     * @config
69
     * @var string
70
     */
71
    private static $generated_pdf_path = 'assets/_generated_pdfs';
0 ignored issues
show
introduced by
The private property $generated_pdf_path is not used, and could be removed.
Loading history...
72
73
    private static $api_access = [
0 ignored issues
show
introduced by
The private property $api_access is not used, and could be removed.
Loading history...
74
        'view' => [
75
            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
76
            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
77
        ],
78
        'edit' => [
79
            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
80
            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
81
        ],
82
    ];
83
84
    private static $table_name = 'BasePage';
0 ignored issues
show
introduced by
The private property $table_name is not used, and could be removed.
Loading history...
85
86
    /**
87
     * @config
88
     * @var string
89
     */
90
    private static $related_pages_title = 'Related pages';
0 ignored issues
show
introduced by
The private property $related_pages_title is not used, and could be removed.
Loading history...
91
92
    private static $many_many = [
0 ignored issues
show
introduced by
The private property $many_many is not used, and could be removed.
Loading history...
93
        'Terms' => TaxonomyTerm::class,
94
        'RelatedPages' => BasePage::class,
95
    ];
96
97
    private static $many_many_extraFields = [
0 ignored issues
show
introduced by
The private property $many_many_extraFields is not used, and could be removed.
Loading history...
98
        'RelatedPages' => [
99
            'SortOrder' => 'Int',
100
        ],
101
    ];
102
103
    private static $plural_name = 'Base Pages';
0 ignored issues
show
introduced by
The private property $plural_name is not used, and could be removed.
Loading history...
104
105
    /**
106
     * Get the footer holder.
107
     */
108
    public function getFooter()
109
    {
110
        return FooterHolder::get_one(FooterHolder::class);
111
    }
112
113
    /**
114
     * Return the full filename of the pdf file, including path & extension
115
     */
116
    public function getPdfFilename()
117
    {
118
        $baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
119
120
        $folderPath = $this->config()->get('generated_pdf_path');
121
        if ($folderPath[0] != '/') {
122
            $folderPath = BASE_PATH . '/' . $folderPath;
123
        }
124
125
        return sprintf('%s/%s.pdf', $folderPath, $baseName);
126
    }
127
128
    /**
129
     * Build pdf link for template.
130
     */
131
    public function PdfLink()
132
    {
133
        if (!$this->config()->get('pdf_export')) {
134
            return false;
135
        }
136
137
        $path = $this->getPdfFilename();
138
139
        if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
140
            return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
141
        }
142
        return $this->Link('downloadpdf');
143
    }
144
145
    public function RelatedPages()
146
    {
147
        return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
148
    }
149
150
    public function RelatedPagesTitle()
151
    {
152
        return $this->config()->get('related_pages_title');
153
    }
154
155
    /**
156
     * Remove linked pdf when publishing the page,
157
     * as it would be out of date.
158
     */
159
    public function onAfterPublish()
160
    {
161
        $filepath = $this->getPdfFilename();
162
        if (file_exists($filepath)) {
163
            unlink($filepath);
164
        }
165
    }
166
167
    /**
168
     * Remove linked pdf when unpublishing the page,
169
     * so it's no longer valid.
170
     *
171
     * @return boolean
172
     */
173
    public function doUnpublish()
174
    {
175
        if (!parent::doUnpublish()) {
0 ignored issues
show
introduced by
The method doUnpublish() does not exist on SilverStripe\CMS\Model\SiteTree. 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

175
        if (!parent::/** @scrutinizer ignore-call */ doUnpublish()) {
Loading history...
176
            return false;
177
        }
178
179
        $filepath = $this->getPdfFilename();
180
        if (file_exists($filepath)) {
181
            unlink($filepath);
182
        }
183
184
        return true;
185
    }
186
187
    public function getCMSFields()
188
    {
189
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
190
            // Related Pages
191
            $components = GridFieldConfig_RelationEditor::create();
192
            $components->removeComponentsByType(GridFieldAddNewButton::class);
193
            $components->removeComponentsByType(GridFieldEditButton::class);
194
            $components->removeComponentsByType(GridFieldFilterHeader::class);
195
            $components->addComponent(new GridFieldSortableRows('SortOrder'));
196
197
            /** @var GridFieldDataColumns $dataColumns */
198
            $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
199
            $dataColumns->setDisplayFields([
200
                'Title' => _t(__CLASS__ . '.ColumnTitle', 'Title'),
201
                'ClassName' => _t(__CLASS__ . '.ColumnPageType', 'Page Type')
202
            ]);
203
204
            $fields->findOrMakeTab(
205
                'Root.RelatedPages',
206
                _t(__CLASS__ . '.RelatedPages', 'Related pages')
207
            );
208
            $fields->addFieldToTab(
209
                'Root.RelatedPages',
210
                GridField::create(
211
                    'RelatedPages',
0 ignored issues
show
Bug introduced by
'RelatedPages' of type string is incompatible with the type array expected by parameter $args of SilverStripe\View\ViewableData::create(). ( Ignorable by Annotation )

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

211
                    /** @scrutinizer ignore-type */ 'RelatedPages',
Loading history...
212
                    _t(__CLASS__ . '.RelatedPages', 'Related pages'),
213
                    $this->RelatedPages(),
0 ignored issues
show
Bug introduced by
$this->RelatedPages() of type SilverStripe\ORM\Relatio...ORM\UnsavedRelationList is incompatible with the type array expected by parameter $args of SilverStripe\View\ViewableData::create(). ( Ignorable by Annotation )

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

213
                    /** @scrutinizer ignore-type */ $this->RelatedPages(),
Loading history...
214
                    $components
215
                )
216
            );
217
218
            // Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
219
            $hasMany = $this->hasMany();
220
            $manyMany = $this->manyMany();
221
            if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
222
                $components = GridFieldConfig_RelationEditor::create();
223
                $components->removeComponentsByType(GridFieldAddNewButton::class);
224
                $components->removeComponentsByType(GridFieldEditButton::class);
225
226
                /** @var GridFieldAddExistingAutocompleter $autoCompleter */
227
                $autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
228
                $autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
229
230
                /** @var GridFieldDataColumns $dataColumns */
231
                $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
232
                $dataColumns->setDisplayFields([
233
                    'Name' => _t(__CLASS__ . '.Term', 'Term'),
234
                    'TaxonomyName' => _t(__CLASS__ . '.Taxonomy', 'Taxonomy')
235
                ]);
236
237
                $fields->findOrMakeTab('Root.Tags', _t(__CLASS__ . '.TagsTabTitle', 'Tags'));
238
                $fields->addFieldToTab(
239
                    'Root.Tags',
240
                    TreeMultiselectField::create(
241
                        'Terms',
242
                        _t(__CLASS__ . '.Terms', 'Terms'),
243
                        TaxonomyTerm::class
244
                    )->setDescription(_t(__CLASS__ . '.TermsDescription', 'Click to search for additional terms'))
245
                );
246
            }
247
        });
248
        return parent::getCMSFields();
249
    }
250
251
    /**
252
     * Returns the native language name for the selected locale/language, empty string if Fluent is not available
253
     *
254
     * @return string
255
     */
256
    public function getSelectedLanguage()
257
    {
258
        if (!class_exists(Locale::class) || !$this->hasMethod('Locales')) {
259
            return '';
260
        }
261
262
        /** @var ArrayData $information */
263
        $information = $this->LocaleInformation(FluentState::singleton()->getLocale());
0 ignored issues
show
Bug introduced by
The method LocaleInformation() does not exist on CWP\CWP\PageTypes\BasePage. 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

263
        /** @scrutinizer ignore-call */ 
264
        $information = $this->LocaleInformation(FluentState::singleton()->getLocale());
Loading history...
264
265
        return $information->LanguageNative;
266
    }
267
}
268