Passed
Push — master ( 97e8d4...784af9 )
by Raissa
05:32 queued 03:00
created

src/Extensions/ElementalAreasExtension.php (3 issues)

1
<?php
2
3
namespace DNADesign\Elemental\Extensions;
4
5
use DNADesign\Elemental\Forms\ElementalAreaField;
6
use DNADesign\Elemental\Models\BaseElement;
7
use DNADesign\Elemental\Models\ElementalArea;
8
use SilverStripe\CMS\Model\RedirectorPage;
9
use SilverStripe\CMS\Model\SiteTree;
10
use SilverStripe\CMS\Model\VirtualPage;
11
use SilverStripe\Core\ClassInfo;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\Forms\FieldList;
14
use SilverStripe\Forms\LiteralField;
15
use SilverStripe\ORM\DataExtension;
16
17
/**
18
 * This extension handles most of the relationships between pages and element
19
 * area, it doesn't add an ElementArea to the page however. Because of this,
20
 * developers can add multiple {@link ElementArea} areas to to a page.
21
 *
22
 * If you want multiple ElementalAreas add them as has_ones, add this extensions
23
 * and MAKE SURE you don't forget to add ElementAreas to $owns, otherwise they
24
 * will never publish
25
 *
26
 * private static $has_one = array(
27
 *     'ElementalArea1' => ElementalArea::class,
28
 *     'ElementalArea2' => ElementalArea::class
29
 * );
30
 *
31
 * private static $owns = array(
32
 *     'ElementalArea1',
33
 *     'ElementalArea2'
34
 * );
35
 *
36
 * private static $cascade_duplicates = array(
37
 *     'ElementalArea1',
38
 *     'ElementalArea2'
39
 * );
40
 *
41
 * @package elemental
42
 */
43
class ElementalAreasExtension extends DataExtension
44
{
45
    /**
46
     * @config
47
     *
48
     * @var array $ignored_classes Classes to ignore adding elements too.
49
     */
50
    private static $ignored_classes = [];
51
52
    /**
53
     * @config
54
     *
55
     * On saving the element area, should Elemental reset the main website
56
     * `$Content` field.
57
     *
58
     * @var boolean
59
     */
60
    private static $clear_contentfield = false;
61
62
    /**
63
     * Get the available element types for this page type,
64
     *
65
     * Uses allowed_elements, stop_element_inheritance, disallowed_elements in
66
     * order to get to correct list.
67
     *
68
     * @return array
69
     */
70
    public function getElementalTypes()
71
    {
72
        $config = $this->owner->config();
73
74
        if (is_array($config->get('allowed_elements'))) {
75
            if ($config->get('stop_element_inheritance')) {
76
                $availableClasses = $config->get('allowed_elements', Config::UNINHERITED);
77
            } else {
78
                $availableClasses = $config->get('allowed_elements');
79
            }
80
        } else {
81
            $availableClasses = ClassInfo::subclassesFor(BaseElement::class);
82
        }
83
84
        if ($config->get('stop_element_inheritance')) {
85
            $disallowedElements = (array) $config->get('disallowed_elements', Config::UNINHERITED);
86
        } else {
87
            $disallowedElements = (array) $config->get('disallowed_elements');
88
        }
89
        $list = array();
90
91
        foreach ($availableClasses as $availableClass) {
92
            /** @var BaseElement $inst */
93
            $inst = singleton($availableClass);
94
95
            if (!in_array($availableClass, $disallowedElements) && $inst->canCreate()) {
96
                if ($inst->hasMethod('canCreateElement') && !$inst->canCreateElement()) {
0 ignored issues
show
The method canCreateElement() does not exist on DNADesign\Elemental\Models\BaseElement. 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

96
                if ($inst->hasMethod('canCreateElement') && !$inst->/** @scrutinizer ignore-call */ canCreateElement()) {
Loading history...
97
                    continue;
98
                }
99
100
                $list[$availableClass] = $inst->getType();
101
            }
102
        }
103
104
        if ($config->get('sort_types_alphabetically') !== false) {
105
            asort($list);
106
        }
107
108
        if (isset($list[BaseElement::class])) {
109
            unset($list[BaseElement::class]);
110
        }
111
112
        $this->owner->invokeWithExtensions('updateAvailableTypesForClass', $class, $list);
113
114
        return $list;
115
    }
116
117
    /**
118
     * Returns an array of the relation names to ElementAreas. Ignores any
119
     * has_one fields named `Parent` as that would indicate that this is child
120
     * of an existing area
121
     *
122
     * @return array
123
     */
124
    public function getElementalRelations()
125
    {
126
        $hasOnes = $this->owner->hasOne();
127
128
        if (!$hasOnes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $hasOnes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
129
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
130
        }
131
132
        $elementalAreaRelations = [];
133
134
        foreach ($hasOnes as $hasOneName => $hasOneClass) {
135
            if ($hasOneName === 'Parent' || $hasOneName === 'ParentID') {
136
                continue;
137
            }
138
139
            if ($hasOneClass == ElementalArea::class || is_subclass_of($hasOneClass, ElementalArea::class)) {
140
                $elementalAreaRelations[] = $hasOneName;
141
            }
142
        }
143
144
        return $elementalAreaRelations;
145
    }
146
147
    /**
148
     * Setup the CMS Fields
149
     *
150
     * @param FieldList
151
     */
152
    public function updateCMSFields(FieldList $fields)
153
    {
154
        if (!$this->supportsElemental()) {
155
            return;
156
        }
157
158
        // add an empty holder for content as some module explicitly use insert
159
        // after content.
160
        $fields->replaceField('Content', new LiteralField('Content', ''));
161
        $elementalAreaRelations = $this->owner->getElementalRelations();
162
163
        foreach ($elementalAreaRelations as $eaRelationship) {
164
            $key = $eaRelationship . 'ID';
165
166
            // remove the scaffold dropdown
167
            $fields->removeByName($key);
168
169
            // remove the field, but don't add anything.
170
            if (!$this->owner->isInDb()) {
171
                continue;
172
            }
173
174
            // Example: $eaRelationship = 'ElementalArea';
175
            $area = $this->owner->$eaRelationship();
176
177
            $editor = ElementalAreaField::create($eaRelationship, $area, $this->getElementalTypes());
178
179
            if ($this->owner instanceof SiteTree && $fields->findOrMakeTab('Root.Main')->fieldByName('Metadata')) {
180
                $fields->addFieldToTab('Root.Main', $editor, 'Metadata');
181
            } else {
182
                $fields->addFieldToTab('Root.Main', $editor);
183
            }
184
        }
185
186
        return $fields;
187
    }
188
189
    /**
190
     * Make sure there is always an ElementalArea for adding Elements
191
     */
192
    public function onBeforeWrite()
193
    {
194
        parent::onBeforeWrite();
195
196
        if (!$this->supportsElemental()) {
197
            return;
198
        }
199
200
        $elementalAreaRelations = $this->owner->getElementalRelations();
201
202
        foreach ($elementalAreaRelations as $eaRelationship) {
203
            $areaID = $eaRelationship . 'ID';
204
205
            if (!$this->owner->$areaID) {
206
                $area = ElementalArea::create();
207
                $area->OwnerClassName = $this->owner->ClassName;
208
                $area->write();
209
                $this->owner->$areaID = $area->ID;
210
            }
211
        }
212
213
        if (Config::inst()->get(self::class, 'clear_contentfield')) {
214
            $this->owner->Content = '';
215
        }
216
    }
217
218
    /**
219
     * @return boolean
220
     */
221
    public function supportsElemental()
222
    {
223
        if ($this->owner->hasMethod('includeElemental')) {
224
            $res = $this->owner->includeElemental();
225
226
            if ($res !== null) {
227
                return $res;
228
            }
229
        }
230
231
        if (is_a($this->owner, RedirectorPage::class) || is_a($this->owner, VirtualPage::class)) {
232
            return false;
233
        } elseif ($ignored = Config::inst()->get(ElementalPageExtension::class, 'ignored_classes')) {
234
            foreach ($ignored as $check) {
235
                if (is_a($this->owner, $check)) {
236
                    return false;
237
                }
238
            }
239
        }
240
241
        return true;
242
    }
243
}
244