Passed
Push — hans/can-you-see-me-now ( 53b516...849831 )
by Simon
05:57
created

DataObjectExtension::shouldPush()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
1
<?php
2
3
4
namespace Firesphere\SolrSearch\Extensions;
5
6
use Exception;
7
use Firesphere\SolrSearch\Helpers\SolrLogger;
8
use Firesphere\SolrSearch\Models\DirtyClass;
9
use Firesphere\SolrSearch\Services\SolrCoreService;
10
use GuzzleHttp\Exception\GuzzleException;
11
use Psr\Log\LoggerInterface;
12
use ReflectionException;
13
use SilverStripe\CMS\Model\SiteTree;
14
use SilverStripe\Control\Controller;
15
use SilverStripe\Core\Injector\Injector;
16
use SilverStripe\ORM\ArrayList;
17
use SilverStripe\ORM\DataExtension;
18
use SilverStripe\ORM\DataList;
19
use SilverStripe\ORM\DataObject;
20
use SilverStripe\ORM\ValidationException;
21
use SilverStripe\Security\Member;
22
use SilverStripe\SiteConfig\SiteConfig;
23
use SilverStripe\Versioned\Versioned;
24
25
/**
26
 * Class \Firesphere\SolrSearch\Compat\DataObjectExtension
27
 *
28
 * Extend every DataObject with the option to update the index.
29
 *
30
 * @package Firesphere\SolrSearch\Extensions
31
 * @property DataObject|DataObjectExtension $owner
32
 */
33
class DataObjectExtension extends DataExtension
34
{
35
    /**
36
     * @var array
37
     */
38
    public static $cachedClasses;
39
    /**
40
     * @var SiteConfig
41
     */
42
    protected static $siteConfig;
43
44
    /**
45
     * Push the item to solr if it is not versioned
46
     * Update the index after write.
47
     *
48
     * @throws ValidationException
49
     * @throws GuzzleException
50
     * @throws ReflectionException
51
     */
52 79
    public function onAfterWrite()
53
    {
54
        /** @var DataObject $owner */
55 79
        $owner = $this->owner;
56
57 79
        if ($this->shouldPush() && !$owner->hasExtension(Versioned::class)) {
58 79
            $this->pushToSolr($owner);
59
        }
60 79
    }
61
62
    /**
63
     * Should this write be pushed to Solr
64
     * @return bool
65
     */
66 79
    protected function shouldPush()
67
    {
68 79
        return !(Controller::curr()->getRequest()->getURL() &&
69 79
            strpos('dev/build', Controller::curr()->getRequest()->getURL()) !== false);
70
    }
71
72
    /**
73
     * Try to push the newly updated item to Solr
74
     *
75
     * @param DataObject $owner
76
     * @throws ValidationException
77
     * @throws GuzzleException
78
     * @throws ReflectionException
79
     */
80 79
    protected function pushToSolr(DataObject $owner)
81
    {
82 79
        $service = new SolrCoreService();
83 79
        if (!$service->isValidClass($owner->ClassName)) {
84 79
            return;
85
        }
86
        /** @var DataObject $owner */
87 2
        $record = $this->getDirtyClass($owner, SolrCoreService::UPDATE_TYPE);
88
89 2
        $ids = json_decode($record->IDs, 1) ?: [];
90 2
        $mode = Versioned::get_reading_mode();
91
        try {
92 2
            Versioned::set_reading_mode(Versioned::DEFAULT_MODE);
93 2
            $service->setInDebugMode(false);
94 2
            $type = SolrCoreService::UPDATE_TYPE;
95
            // If the object should not show in search, remove it
96 2
            if ($owner->ShowInSearch === 0) {
97
                $type = SolrCoreService::DELETE_TYPE;
98
            }
99 2
            $service->updateItems(ArrayList::create([$owner]), $type);
100
            // If we don't get an exception, mark the item as clean
101
            // Added bonus, array_flip removes duplicates
102 2
            $this->clearIDs($owner, $ids, $record);
103
        } catch (Exception $error) {
104
            Versioned::set_reading_mode($mode);
105
            $this->registerException($ids, $record, $error);
106
        }
107 2
        Versioned::set_reading_mode($mode);
108 2
    }
109
110
    /**
111
     * Find or create a new DirtyClass for recording dirty IDs
112
     *
113
     * @param DataObject $owner
114
     * @param string $type
115
     * @return DirtyClass
116
     * @throws ValidationException
117
     */
118 6
    protected function getDirtyClass(DataObject $owner, $type)
119
    {
120
        // Get the DirtyClass object for this item
121
        /** @var null|DirtyClass $record */
122 6
        $record = DirtyClass::get()->filter(['Class' => $owner->ClassName, 'Type' => $type])->first();
123 6
        if (!$record || !$record->exists()) {
124 5
            $record = DirtyClass::create([
125 5
                'Class' => $owner->ClassName,
126 5
                'Type'  => $type,
127
            ]);
128 5
            $record->write();
129
        }
130
131 6
        return $record;
132
    }
133
134
    /**
135
     * Remove the owner ID from the dirty ID set
136
     *
137
     * @param DataObject $owner
138
     * @param array $ids
139
     * @param DirtyClass $record
140
     * @throws ValidationException
141
     */
142 6
    protected function clearIDs(DataObject $owner, array $ids, DirtyClass $record): void
143
    {
144 6
        $values = array_flip($ids);
145 6
        unset($values[$owner->ID]);
146
147 6
        $record->IDs = json_encode(array_keys($values));
148 6
        $record->write();
149 6
    }
150
151
    /**
152
     * Register the exception of the attempted index for later clean-up use
153
     *
154
     * @param array $ids
155
     * @param $record
156
     * @param Exception $error
157
     * @throws ValidationException
158
     * @throws GuzzleException
159
     */
160
    protected function registerException(array $ids, $record, Exception $error): void
161
    {
162
        /** @var DataObject $owner */
163
        $owner = $this->owner;
164
        $ids[] = $owner->ID;
165
        // If we don't get an exception, mark the item as clean
166
        $record->IDs = json_encode($ids);
167
        $record->write();
168
        $logger = Injector::inst()->get(LoggerInterface::class);
169
        $logger->warn(
170
            sprintf(
171
                'Unable to alter %s with ID %s',
172
                $owner->ClassName,
173
                $owner->ID
174
            )
175
        );
176
        $solrLogger = new SolrLogger();
177
        $solrLogger->saveSolrLog('Index');
178
179
        $logger->error($error->getMessage());
180
    }
181
182
    /**
183
     * Push the item to Solr after publishing
184
     *
185
     * @throws ValidationException
186
     * @throws GuzzleException
187
     * @throws ReflectionException
188
     */
189 2
    public function onAfterPublish()
190
    {
191 2
        if ($this->shouldPush()) {
192
            /** @var DataObject $owner */
193 2
            $owner = $this->owner;
194 2
            $this->pushToSolr($owner);
195
        }
196 2
    }
197
198
    /**
199
     * Attempt to remove the item from Solr
200
     *
201
     * @throws ValidationException
202
     * @throws GuzzleException
203
     */
204 4
    public function onAfterDelete(): void
205
    {
206
        /** @var DataObject $owner */
207 4
        $owner = $this->owner;
208
        /** @var DirtyClass $record */
209 4
        $record = $this->getDirtyClass($owner, SolrCoreService::DELETE_TYPE);
210
211 4
        $ids = json_decode($record->IDs, 1) ?: [];
212
213
        try {
214 4
            (new SolrCoreService())->updateItems(ArrayList::create([$owner]), SolrCoreService::DELETE_TYPE);
215
            // If successful, remove it from the array
216
            // Added bonus, array_flip removes duplicates
217 4
            $this->clearIDs($owner, $ids, $record);
218
        } catch (Exception $error) {
219
            $this->registerException($ids, $record, $error);
220
        }
221 4
    }
222
223
    /**
224
     * Get the view status for each member in this object
225
     *
226
     * @return array
227
     */
228 7
    public function getViewStatus(): array
229
    {
230
        // Make sure the siteconfig is loaded
231 7
        if (!static::$siteConfig) {
232 1
            static::$siteConfig = SiteConfig::current_site_config();
233
        }
234
        // Return 0-0 if it's not allowed to show in search
235
        // The setting needs to be explicitly false, to avoid any possible collision
236
        // with objects not having the setting, thus being `null`
237
        /** @var DataObject|SiteTree $owner */
238 7
        $owner = $this->owner;
239
        // Return immediately if the owner has ShowInSearch not being `null`
240 7
        if ($owner->ShowInSearch === false || $owner->ShowInSearch === 0) {
241 1
            return ['false'];
242
        }
243
244 7
        if (isset(static::$cachedClasses[$owner->ClassName])) {
245 1
            return static::$cachedClasses[$owner->ClassName];
246
        }
247
248 7
        $permissions = $this->getGroupViewPermissions($owner);
249
250 7
        if (!$owner instanceof SiteTree) {
251 1
            static::$cachedClasses[$owner->ClassName] = $permissions;
252
        }
253
254 7
        return $permissions;
255
    }
256
    
257
    /**
258
     * Determine the view permissions based on group settings
259
     *
260
     * @param DataObject|SiteTree|SiteConfig $owner
261
     * @return array
262
     */
263 7
    protected function getGroupViewPermissions($owner): array
264
    {
265
        // Switches are not ideal, but it's a lot more readable this way!
266 7
        switch ($owner->CanViewType) {
267 7
            case 'LoggedInUsers':
268
                $return = ['false', 'LoggedIn'];
269
                break;
270 7
            case 'OnlyTheseUsers':
271 1
                $return = ['false'];
272 1
                $return = array_merge($return, $owner->ViewerGroups()->column('Code'));
273 1
                break;
274 7
            case 'Inherit';
275 7
                $parent = !$owner->ParentID ? static::$siteConfig : $owner->Parent();
276 7
                $return = $this->getGroupViewPermissions($parent);
277 7
                break;
278 7
            case 'Anyone': // View is either not implemented, or it's "Anyone"
279 7
                $return = ['null'];
280 7
                break;
281
            default:
282
                // Default to "Anyone can view"
283 1
                $return = ['null'];
284
        }
285
286 7
        return $return;
287
    }
288
}
289