ElementalArea   A
last analyzed

Complexity

Total Complexity 36

Size/Duplication

Total Lines 284
Duplicated Lines 0 %

Importance

Changes 7
Bugs 1 Features 0
Metric Value
eloc 103
c 7
b 1
f 0
dl 0
loc 284
rs 9.52
wmc 36

10 Methods

Rating   Name   Duplication   Size   Complexity  
A forTemplate() 0 3 1
A setElementsCached() 0 5 1
A supportedPageTypes() 0 11 3
A canEdit() 0 12 3
A canView() 0 12 3
A Breadcrumbs() 0 13 2
A Elements() 0 7 2
A ElementControllers() 0 20 4
C getOwnerPage() 0 80 16
A setOwnerPageCached() 0 7 1
1
<?php
2
3
namespace DNADesign\Elemental\Models;
4
5
use DNADesign\Elemental\Extensions\ElementalAreasExtension;
6
use SilverStripe\Core\ClassInfo;
7
use SilverStripe\Core\Injector\Injector;
8
use SilverStripe\Dev\TestOnly;
9
use SilverStripe\ORM\ArrayList;
10
use SilverStripe\ORM\DataObject;
11
use SilverStripe\ORM\FieldType\DBField;
12
use SilverStripe\ORM\FieldType\DBHTMLText;
13
use SilverStripe\ORM\HasManyList;
14
use SilverStripe\ORM\UnsavedRelationList;
15
use SilverStripe\Versioned\Versioned;
16
use SilverStripe\View\ViewableData;
17
18
/**
19
 * Class ElementalArea
20
 * @package DNADesign\Elemental\Models
21
 *
22
 * @property string $OwnerClassName
23
 *
24
 * @mixin Versioned
25
 */
26
class ElementalArea extends DataObject
27
{
28
    private static $db = [
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
29
        'OwnerClassName' => 'Varchar(255)',
30
    ];
31
32
    private static $has_many = [
0 ignored issues
show
introduced by
The private property $has_many is not used, and could be removed.
Loading history...
33
        'Elements' => BaseElement::class,
34
    ];
35
36
    private static $extensions = [
0 ignored issues
show
introduced by
The private property $extensions is not used, and could be removed.
Loading history...
37
        Versioned::class,
38
    ];
39
40
    private static $owns = [
0 ignored issues
show
introduced by
The private property $owns is not used, and could be removed.
Loading history...
41
        'Elements',
42
    ];
43
44
    private static $cascade_deletes = [
0 ignored issues
show
introduced by
The private property $cascade_deletes is not used, and could be removed.
Loading history...
45
        'Elements',
46
    ];
47
48
    private static $cascade_duplicates = [
0 ignored issues
show
introduced by
The private property $cascade_duplicates is not used, and could be removed.
Loading history...
49
        'Elements',
50
    ];
51
52
    private static $summary_fields = [
0 ignored issues
show
introduced by
The private property $summary_fields is not used, and could be removed.
Loading history...
53
        'Title' => 'Title',
54
    ];
55
56
    private static $table_name = 'ElementalArea';
0 ignored issues
show
introduced by
The private property $table_name is not used, and could be removed.
Loading history...
57
58
    /**
59
     * Don't show this model in campaign admin as part of implicit change sets
60
     *
61
     * @config
62
     * @var bool
63
     */
64
    private static $hide_in_campaigns = true;
0 ignored issues
show
introduced by
The private property $hide_in_campaigns is not used, and could be removed.
Loading history...
65
66
    /**
67
     * Cache various data to improve CMS load time
68
     *
69
     * @internal
70
     * @var array
71
     */
72
    protected $cacheData = [];
73
74
    /**
75
     * @return array
76
     */
77
    public function supportedPageTypes()
78
    {
79
        $elementalClasses = [];
80
81
        foreach (ClassInfo::getValidSubClasses(DataObject::class) as $class) {
82
            if (ViewableData::has_extension($class, ElementalAreasExtension::class)) {
83
                $elementalClasses[] = $class;
84
            }
85
        }
86
87
        return $elementalClasses;
88
    }
89
90
    /**
91
     * @return DBHTMLText
92
     */
93
    public function forTemplate()
94
    {
95
        return $this->renderWith(static::class);
96
    }
97
98
    /**
99
     * @param ArrayList $elements
100
     * @return $this
101
     */
102
    public function setElementsCached(ArrayList $elements)
103
    {
104
        $this->cacheData['elements'] = $elements;
105
106
        return $this;
107
    }
108
109
    /**
110
     * @param DataObject $page
111
     * @return $this
112
     */
113
    public function setOwnerPageCached(DataObject $page)
114
    {
115
        $cacheKey = 'owner_page_'. Versioned::get_reading_mode();
116
117
        $this->cacheData[$cacheKey] = $page;
118
119
        return $this;
120
    }
121
122
    /**
123
     * A cache-aware accessor for the elements
124
     * @return ArrayList|HasManyList|BaseElement[]
125
     */
126
    public function Elements()
127
    {
128
        if (isset($this->cacheData['elements'])) {
129
            return $this->cacheData['elements'];
130
        }
131
132
        return parent::Elements();
0 ignored issues
show
introduced by
The method Elements() does not exist on SilverStripe\ORM\DataObject. 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

132
        return parent::/** @scrutinizer ignore-call */ Elements();
Loading history...
133
    }
134
135
    /**
136
     * Necessary to display results in CMS site search.
137
     *
138
     * @return DBField
139
     */
140
    public function Breadcrumbs()
141
    {
142
        $ownerClassName = $this->OwnerClassName;
143
144
        if ($owner = $ownerClassName::get()->filter('ElementalAreaID', $this->ID)->first()) {
145
            return DBField::create_field('HTMLText', sprintf(
146
                '<a href="%s">%s</a>',
147
                $owner->CMSEditLink(),
148
                $owner->Title
149
            ));
150
        }
151
152
        return null;
153
    }
154
155
    /**
156
     * Used in template instead of {@link Elements()} to wrap each element in
157
     * its' controller, making it easier to access and process form logic and
158
     * actions stored in {@link ElementController}.
159
     *
160
     * @return ArrayList
161
     * @throws \Exception
162
     */
163
    public function ElementControllers()
164
    {
165
        // Don't try and process unsaved lists
166
        if ($this->Elements() instanceof UnsavedRelationList) {
167
            return ArrayList::create();
168
        }
169
170
        $controllers = ArrayList::create();
171
        $items = $this->Elements()->filterByCallback(function (BaseElement $item) {
172
            return $item->canView();
173
        });
174
175
        if (!is_null($items)) {
176
            foreach ($items as $element) {
177
                $controller = $element->getController();
178
                $controllers->push($controller);
179
            }
180
        }
181
182
        return $controllers;
183
    }
184
185
    /**
186
     * @return null|DataObject
187
     * @throws \Psr\Container\NotFoundExceptionInterface
188
     * @throws \SilverStripe\ORM\ValidationException
189
     */
190
    public function getOwnerPage()
191
    {
192
        // You can't find the owner page of a area that hasn't been save yet
193
        if (!$this->isInDB()) {
194
            return null;
195
        }
196
197
        // Allow for repeated calls to read from cache
198
        $cacheKey = 'owner_page_'. Versioned::get_reading_mode();
199
200
        if (isset($this->cacheData[$cacheKey])) {
201
            return $this->cacheData[$cacheKey];
202
        }
203
204
        if ($this->OwnerClassName && ClassInfo::exists($this->OwnerClassName)) {
205
            $class = $this->OwnerClassName;
206
            $instance = Injector::inst()->get($class);
207
            if (!ClassInfo::hasMethod($instance, 'getElementalRelations')) {
208
                return null;
209
            }
210
            $elementalAreaRelations = $instance->getElementalRelations();
211
212
            foreach ($elementalAreaRelations as $eaRelationship) {
213
                $areaID = $eaRelationship . 'ID';
214
215
                $table = DataObject::getSchema()->tableForField($class, $areaID);
216
                $baseTable = DataObject::getSchema()->baseDataTable($class);
217
                $page = DataObject::get_one($class, [
218
                    "\"{$table}\".\"{$areaID}\" = ?" => $this->ID,
219
                    "\"{$baseTable}\".\"ClassName\" = ?" => $class
220
                ]);
221
222
                if ($page) {
223
                    $this->setOwnerPageCached($page);
224
225
                    return $page;
226
                }
227
            }
228
        }
229
230
        foreach ($this->supportedPageTypes() as $class) {
231
            $instance = Injector::inst()->get($class);
232
            if (!ClassInfo::hasMethod($instance, 'getElementalRelations')) {
233
                return null;
234
            }
235
236
            $areaIDFilters = [];
237
            foreach ($instance->getElementalRelations() as $eaRelationship) {
238
                $areaIDFilters[$eaRelationship . 'ID'] = $this->ID;
239
            }
240
241
            try {
242
                $page = DataObject::get($class)->filterAny($areaIDFilters)->first();
243
            } catch (\Exception $ex) {
244
                // Usually this is catching cases where test stubs from other modules are trying to be loaded
245
                // and failing in unit tests.
246
                if (in_array(TestOnly::class, class_implements($class))) {
247
                    continue;
248
                }
249
                // Continue as normal...
250
                throw $ex;
251
            }
252
253
            if ($page) {
254
                if ($this->OwnerClassName !== $class) {
255
                    $this->OwnerClassName = $class;
256
257
                    // Avoid recursion: only write if it's already in the database
258
                    if ($this->isInDB()) {
259
                        $this->write();
260
                    }
261
                }
262
263
                $this->setOwnerPageCached($page);
264
265
                return $page;
266
            }
267
        }
268
269
        return null;
270
    }
271
272
    /**
273
     * @param null $member
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $member is correct as it would always require null to be passed?
Loading history...
274
     * @return bool
275
     * @throws \Psr\Container\NotFoundExceptionInterface
276
     * @throws \SilverStripe\ORM\ValidationException
277
     */
278
    public function canEdit($member = null)
279
    {
280
        if (parent::canEdit($member)) {
281
            return true;
282
        }
283
284
        $ownerPage = $this->getOwnerPage();
285
        if ($ownerPage !== null) {
286
            return $this->getOwnerPage()->canEdit($member);
287
        }
288
289
        return false;
290
    }
291
292
    /**
293
     * @param null $member
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $member is correct as it would always require null to be passed?
Loading history...
294
     * @return bool
295
     * @throws \Psr\Container\NotFoundExceptionInterface
296
     * @throws \SilverStripe\ORM\ValidationException
297
     */
298
    public function canView($member = null)
299
    {
300
        if (parent::canEdit($member)) {
301
            return true;
302
        }
303
304
        $ownerPage = $this->getOwnerPage();
305
        if ($ownerPage !== null) {
306
            return $this->getOwnerPage()->canView($member);
307
        }
308
309
        return false;
310
    }
311
}
312