Completed
Pull Request — master (#13)
by Robbie
02:33
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\Core\Config\Config;
8
use SilverStripe\Forms\FieldList;
9
use SilverStripe\Forms\GridField\GridField;
10
use SilverStripe\Forms\GridField\GridFieldAddExistingAutocompleter;
11
use SilverStripe\Forms\GridField\GridFieldAddNewButton;
12
use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor;
13
use SilverStripe\Forms\GridField\GridFieldDataColumns;
14
use SilverStripe\Forms\GridField\GridFieldEditButton;
15
use SilverStripe\Forms\GridField\GridFieldFilterHeader;
16
use SilverStripe\Forms\TreeMultiselectField;
17
use SilverStripe\i18n\i18n;
18
use SilverStripe\ORM\ArrayList;
19
use SilverStripe\Taxonomy\TaxonomyTerm;
20
use SilverStripe\Versioned\Versioned;
21
use SilverStripe\View\ArrayData;
22
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...
23
24
/**
25
 * **BasePage** is the foundation which can be used for constructing your own pages.
26
 * By default it is hidden from the CMS - we rely on developers creating their own
27
 * `Page` class in the `mysite/code` which will extend from the **BasePage**.
28
 */
29
30
class BasePage extends SiteTree
31
{
32
    private static $icon = '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...
33
34
    /**
35
     * Hide this page type from the CMS. hide_ancestor is slightly misnamed, should really be just "hide"
36
     *
37
     * {@inheritDoc}
38
     */
39
    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...
40
41
    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...
42
43
    /*
44
    *Domain to generate PDF's from, DOES not include protocol
45
    *i.e. google.com not http://google.com
46
    */
47
    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...
48
49
    /**
50
     * Allow custom overriding of the path to the WKHTMLTOPDF binary, in cases
51
     * where multiple versions of the binary are available to choose from. This
52
     * should be the full path to the binary (e.g. /usr/local/bin/wkhtmltopdf)
53
     * @see BasePage_Controller::generatePDF();
54
     */
55
    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...
56
57
    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...
58
59
    private static $api_access = [
0 ignored issues
show
introduced by
The private property $api_access is not used, and could be removed.
Loading history...
60
        'view' => [
61
            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
62
            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
63
        ],
64
        'edit' => [
65
            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
66
            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
67
        ],
68
    ];
69
70
    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...
71
72
    public static $related_pages_title = 'Related pages';
73
74
    private static $many_many = [
0 ignored issues
show
introduced by
The private property $many_many is not used, and could be removed.
Loading history...
75
        'Terms' => TaxonomyTerm::class,
76
        'RelatedPages' => BasePage::class,
77
    ];
78
79
    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...
80
        'RelatedPages' => [
81
            'SortOrder' => 'Int',
82
        ],
83
    ];
84
85
    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...
86
87
    public $pageIcon = 'images/icons/sitetree_images/page.png';
88
89
    /**
90
     * Get the footer holder.
91
     */
92
    public function getFooter()
93
    {
94
        return FooterHolder::get_one(FooterHolder::class);
95
    }
96
97
    /**
98
     * Return the full filename of the pdf file, including path & extension
99
     */
100
    public function getPdfFilename()
101
    {
102
        $baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
103
104
        $folderPath = Config::inst()->get(BasePage::class, 'generated_pdf_path');
105
        if ($folderPath[0] != '/') {
106
            $folderPath = BASE_PATH . '/' . $folderPath;
107
        }
108
109
        return sprintf('%s/%s.pdf', $folderPath, $baseName);
110
    }
111
112
    /**
113
     * Build pdf link for template.
114
     */
115
    public function PdfLink()
116
    {
117
        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
118
            return false;
119
        }
120
121
        $path = $this->getPdfFilename();
122
123
        if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
124
            return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
125
        }
126
        return $this->Link('downloadpdf');
127
    }
128
129
    public function RelatedPages()
130
    {
131
        return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
132
    }
133
134
    public function RelatedPagesTitle()
135
    {
136
        return $this->stat('related_pages_title');
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\View\ViewableData::stat() has been deprecated: 5.0 Use ->config()->get() instead ( Ignorable by Annotation )

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

136
        return /** @scrutinizer ignore-deprecated */ $this->stat('related_pages_title');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
137
    }
138
139
    /**
140
     * Remove linked pdf when publishing the page,
141
     * as it would be out of date.
142
     */
143
    public function onAfterPublish()
144
    {
145
        $filepath = $this->getPdfFilename();
146
        if (file_exists($filepath)) {
147
            unlink($filepath);
148
        }
149
    }
150
151
    /**
152
     * Remove linked pdf when unpublishing the page,
153
     * so it's no longer valid.
154
     *
155
     * @return boolean
156
     */
157
    public function doUnpublish()
158
    {
159
        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

159
        if (!parent::/** @scrutinizer ignore-call */ doUnpublish()) {
Loading history...
160
            return false;
161
        }
162
163
        $filepath = $this->getPdfFilename();
164
        if (file_exists($filepath)) {
165
            unlink($filepath);
166
        }
167
168
        return true;
169
    }
170
171
    /**
172
     * @deprecated 2.0.0 remove with other deprecations
173
     * @todo Remove once CWP moves to 3.3 core (which includes this in SiteTree)
174
     * @return self
175
     */
176
    public function doRestoreToStage()
177
    {
178
        $this->invokeWithExtensions('onBeforeRestoreToStage', $this);
179
        $result = parent::doRestoreToStage();
180
        $this->invokeWithExtensions('onAfterRestoreToStage', $this);
181
182
        return $result;
183
    }
184
185
    public function getCMSFields()
186
    {
187
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
188
            // Related Pages
189
            $components = GridFieldConfig_RelationEditor::create();
190
            $components->removeComponentsByType(GridFieldAddNewButton::class);
191
            $components->removeComponentsByType(GridFieldEditButton::class);
192
            $components->removeComponentsByType(GridFieldFilterHeader::class);
193
            $components->addComponent(new GridFieldSortableRows('SortOrder'));
194
195
            $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
196
            $dataColumns->setDisplayFields([
197
                'Title' => _t('BasePage.ColumnTitle', 'Title'),
198
                'ClassName' => _t('BasePage.ColumnPageType', 'Page Type')
199
            ]);
200
201
            $fields->findOrMakeTab(
202
                'Root.RelatedPages',
203
                _t('BasePage.RelatedPages', 'Related pages')
204
            );
205
            $fields->addFieldToTab(
206
                'Root.RelatedPages',
207
                GridField::create(
208
                    '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

208
                    /** @scrutinizer ignore-type */ 'RelatedPages',
Loading history...
209
                    _t('BasePage.RelatedPages', 'Related pages'),
210
                    $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

210
                    /** @scrutinizer ignore-type */ $this->RelatedPages(),
Loading history...
211
                    $components
212
                )
213
            );
214
215
            // Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
216
            $hasMany = $this->hasMany();
217
            $manyMany = $this->manyMany();
218
            if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
219
                $components = GridFieldConfig_RelationEditor::create();
220
                $components->removeComponentsByType(GridFieldAddNewButton::class);
221
                $components->removeComponentsByType(GridFieldEditButton::class);
222
223
                $autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
224
                $autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
225
226
                $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
227
                $dataColumns->setDisplayFields([
228
                    'Name' => _t('BasePage.Term', 'Term'),
229
                    'TaxonomyName' => _t('BasePage.Taxonomy', 'Taxonomy')
230
                ]);
231
232
                $fields->findOrMakeTab('Root.Tags', _t('BasePage.TagsTabTitle', 'Tags'));
233
                $fields->addFieldToTab(
234
                    'Root.Tags',
235
                    TreeMultiselectField::create(
236
                        'Terms',
237
                        _t('BasePage.Terms', 'Terms'),
238
                        TaxonomyTerm::class
239
                    )->setDescription(_t('BasePage.TermsDescription', 'Click to search for additional terms'))
240
                );
241
            }
242
        });
243
        return parent::getCMSFields();
244
    }
245
246
    /**
247
     * Provides data for translation navigation.
248
     * Collects all site translations, marks the current one, and redirects
249
     * to the translated home page if a. there is a translated homepage and b. the
250
     * translation of the specific page is not available.
251
     * @todo re-implement with Fluent
252
     */
253
    public function getAvailableTranslations()
254
    {
255
        if (!class_exists('Translatable')) {
256
            return false;
257
        }
258
259
        $translations = new ArrayList();
260
        $globalTranslations = Translatable::get_existing_content_languages();
0 ignored issues
show
Bug introduced by
The type CWP\CWP\PageTypes\Translatable 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...
261
262
        foreach ($globalTranslations as $loc => $langName) {
263
            // Find out the language name in native language.
264
            $nativeLangName = i18n::get_language_name($loc, true);
0 ignored issues
show
Bug introduced by
The method get_language_name() does not exist on SilverStripe\i18n\i18n. ( Ignorable by Annotation )

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

264
            /** @scrutinizer ignore-call */ 
265
            $nativeLangName = i18n::get_language_name($loc, true);

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...
265
            if (!$nativeLangName) {
266
                $nativeLangName = i18n::get_language_name(i18n::get_lang_from_locale($loc), true);
0 ignored issues
show
Bug introduced by
The method get_lang_from_locale() does not exist on SilverStripe\i18n\i18n. ( Ignorable by Annotation )

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

266
                $nativeLangName = i18n::get_language_name(i18n::/** @scrutinizer ignore-call */ get_lang_from_locale($loc), true);

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...
267
            }
268
            if (!$nativeLangName) {
269
                // Fall back to the locale name.
270
                $nativeLangName = $langName;
271
            }
272
273
            // Eliminate the part in brackets (e.g. [mandarin])
274
            $nativeLangName = preg_replace('/ *[\(\[].*$/', '', $nativeLangName);
275
276
            // Find out the link to the translated page.
277
            $link = null;
278
            $page = $this->getTranslation($loc);
0 ignored issues
show
Bug introduced by
The method getTranslation() 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

278
            /** @scrutinizer ignore-call */ 
279
            $page = $this->getTranslation($loc);
Loading history...
279
            if ($page) {
280
                $link = $page->Link();
281
            }
282
            if (!$link) {
283
                // Fall back to the home page
284
                $link = Translatable::get_homepage_link_by_locale($loc);
285
            }
286
            if (!$link) {
287
                continue;
288
            }
289
290
            // Assemble the table for the switcher.
291
            $translations->push(new ArrayData(array(
292
                'Locale' => i18n::convert_rfc1766($loc),
293
                'LangName' => $nativeLangName,
294
                'Link' => $link,
295
                'Current' => (Translatable::get_current_locale()==$loc)
296
            )));
297
        }
298
299
        if ($translations->count()>1) {
300
            return $translations;
301
        } else {
302
            return null;
303
        }
304
    }
305
306
    /**
307
     * Returns the native language name for the selected locale/language, empty string if Translatable is not available
308
     *
309
     * @return string
310
     * @todo re-implement with Fluent
311
     */
312
    public function getSelectedLanguage()
313
    {
314
        if (!class_exists('Translatable')) {
315
            return '';
316
        }
317
318
        $language = explode('_', Translatable::get_current_locale());
319
        $languageCode = array_shift($language);
320
        $nativeName = i18n::get_language_name($languageCode, true);
321
322
        return $nativeName;
323
    }
324
}
325