| Total Complexity | 49 | 
| Total Lines | 416 | 
| Duplicated Lines | 0 % | 
| Changes | 42 | ||
| Bugs | 4 | Features | 0 | 
Complex classes like SolrIndexTask often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SolrIndexTask, and based on these observations, apply Extract Interface, too.
| 1 | <?php  | 
            ||
| 36 | class SolrIndexTask extends BuildTask  | 
            ||
| 37 | { | 
            ||
| 38 | use LoggerTrait;  | 
            ||
| 39 | use SolrIndexTrait;  | 
            ||
| 40 | /**  | 
            ||
| 41 | * URLSegment of this task  | 
            ||
| 42 | *  | 
            ||
| 43 | * @var string  | 
            ||
| 44 | */  | 
            ||
| 45 | private static $segment = 'SolrIndexTask';  | 
            ||
| 46 | /**  | 
            ||
| 47 | * Store the current states for all instances of SiteState  | 
            ||
| 48 | *  | 
            ||
| 49 | * @var array  | 
            ||
| 50 | */  | 
            ||
| 51 | public $currentStates;  | 
            ||
| 52 | /**  | 
            ||
| 53 | * My name  | 
            ||
| 54 | *  | 
            ||
| 55 | * @var string  | 
            ||
| 56 | */  | 
            ||
| 57 | protected $title = 'Solr Index update';  | 
            ||
| 58 | /**  | 
            ||
| 59 | * What do I do?  | 
            ||
| 60 | *  | 
            ||
| 61 | * @var string  | 
            ||
| 62 | */  | 
            ||
| 63 | protected $description = 'Add or update documents to an existing Solr core.';  | 
            ||
| 64 | |||
| 65 | /**  | 
            ||
| 66 | * SolrIndexTask constructor. Sets up the document factory  | 
            ||
| 67 | *  | 
            ||
| 68 | * @throws ReflectionException  | 
            ||
| 69 | */  | 
            ||
| 70 | public function __construct()  | 
            ||
| 71 |     { | 
            ||
| 72 | parent::__construct();  | 
            ||
| 73 | // Only index live items.  | 
            ||
| 74 | // The old FTS module also indexed Draft items. This is unnecessary  | 
            ||
| 75 | Versioned::set_reading_mode(Versioned::DEFAULT_MODE);  | 
            ||
| 76 | // If versioned is needed, a separate Versioned Search module is required  | 
            ||
| 77 | $this->setService(Injector::inst()->get(SolrCoreService::class));  | 
            ||
| 78 | $this->setLogger(Injector::inst()->get(LoggerInterface::class));  | 
            ||
| 79 | $this->setDebug(Director::isDev() || Director::is_cli());  | 
            ||
| 80 |         $this->setBatchLength(DocumentFactory::config()->get('batchLength')); | 
            ||
| 81 |         $cores = SolrCoreService::config()->get('cpucores') ?: 1; | 
            ||
| 82 | $this->setCores($cores);  | 
            ||
| 83 | $currentStates = SiteState::currentStates();  | 
            ||
| 84 | SiteState::setDefaultStates($currentStates);  | 
            ||
| 85 | }  | 
            ||
| 86 | |||
| 87 | /**  | 
            ||
| 88 | * Implement this method in the task subclass to  | 
            ||
| 89 | * execute via the TaskRunner  | 
            ||
| 90 | *  | 
            ||
| 91 | * @param HTTPRequest $request Current request  | 
            ||
| 92 | * @return int|bool  | 
            ||
| 93 | * @throws Exception  | 
            ||
| 94 | * @throws GuzzleException  | 
            ||
| 95 | */  | 
            ||
| 96 | public function run($request)  | 
            ||
| 97 |     { | 
            ||
| 98 | $start = time();  | 
            ||
| 99 |         $this->getLogger()->info(date('Y-m-d H:i:s')); | 
            ||
| 100 | list($vars, $group, $isGroup) = $this->taskSetup($request);  | 
            ||
| 101 | $groups = 0;  | 
            ||
| 102 |         $indexes = $this->service->getValidIndexes($request->getVar('index')); | 
            ||
| 103 | |||
| 104 |         foreach ($indexes as $indexName) { | 
            ||
| 105 | /** @var BaseIndex $index */  | 
            ||
| 106 | $index = Injector::inst()->get($indexName, false);  | 
            ||
| 107 | $this->setIndex($index);  | 
            ||
| 108 | |||
| 109 | $indexClasses = $this->index->getClasses();  | 
            ||
| 110 | |||
| 111 | $indexClasses = $this->getClassNames($indexClasses);  | 
            ||
| 112 | $classes = $this->getClasses($vars, $indexClasses);  | 
            ||
| 113 |             if (!count($classes)) { | 
            ||
| 114 | continue;  | 
            ||
| 115 | }  | 
            ||
| 116 | |||
| 117 | $this->clearIndex($vars);  | 
            ||
| 118 | |||
| 119 | $groups = $this->indexClassForIndex($classes, $isGroup, $group);  | 
            ||
| 120 | }  | 
            ||
| 121 | |||
| 122 |         $this->getLogger()->info(date('Y-m-d H:i:s')); | 
            ||
| 123 |         $this->getLogger()->info(sprintf('Time taken: %s minutes', (time() - $start) / 60)); | 
            ||
| 124 | |||
| 125 | return $groups;  | 
            ||
| 126 | }  | 
            ||
| 127 | |||
| 128 | /**  | 
            ||
| 129 | * Get the actual classes to index, to avoid array-to-string issues etc.  | 
            ||
| 130 | * @param array $classes  | 
            ||
| 131 | * @return array  | 
            ||
| 132 | */  | 
            ||
| 133 | protected function getClassNames($classes)  | 
            ||
| 134 |     { | 
            ||
| 135 | $return = [];  | 
            ||
| 136 |         foreach ($classes as $i => $classOptions) { | 
            ||
| 137 |             if (is_array($classOptions)) { | 
            ||
| 138 | $return[] = array_key_first($classes[$i]);  | 
            ||
| 139 |             } else { | 
            ||
| 140 | $return[] = $classOptions;  | 
            ||
| 141 | }  | 
            ||
| 142 | }  | 
            ||
| 143 | |||
| 144 | return $return;  | 
            ||
| 145 | }  | 
            ||
| 146 | |||
| 147 | /**  | 
            ||
| 148 | * Set up the requirements for this task  | 
            ||
| 149 | *  | 
            ||
| 150 | * @param HTTPRequest $request Current request  | 
            ||
| 151 | * @return array  | 
            ||
| 152 | */  | 
            ||
| 153 | protected function taskSetup($request): array  | 
            ||
| 154 |     { | 
            ||
| 155 | $vars = $request->getVars();  | 
            ||
| 156 | $this->debug = $this->debug || isset($vars['debug']);  | 
            ||
| 157 | $group = $vars['group'] ?? 0;  | 
            ||
| 158 | $start = $vars['start'] ?? 0;  | 
            ||
| 159 | $group = ($start > $group) ? $start : $group;  | 
            ||
| 160 | $isGroup = isset($vars['group']);  | 
            ||
| 161 | |||
| 162 | return [$vars, $group, $isGroup];  | 
            ||
| 163 | }  | 
            ||
| 164 | |||
| 165 | /**  | 
            ||
| 166 | * get the classes to run for this task execution  | 
            ||
| 167 | *  | 
            ||
| 168 | * @param array $vars URL GET Parameters  | 
            ||
| 169 | * @param array $classes Classes to index  | 
            ||
| 170 | * @return bool|array  | 
            ||
| 171 | */  | 
            ||
| 172 | protected function getClasses($vars, array $classes): array  | 
            ||
| 173 |     { | 
            ||
| 174 |         if (isset($vars['class'])) { | 
            ||
| 175 | return array_intersect($classes, [$vars['class']]);  | 
            ||
| 176 | }  | 
            ||
| 177 | |||
| 178 | return $classes;  | 
            ||
| 179 | }  | 
            ||
| 180 | |||
| 181 | /**  | 
            ||
| 182 | * Clear the given index if a full re-index is needed  | 
            ||
| 183 | *  | 
            ||
| 184 | * @param array $vars URL GET Parameters  | 
            ||
| 185 | * @throws Exception  | 
            ||
| 186 | */  | 
            ||
| 187 | public function clearIndex($vars)  | 
            ||
| 188 |     { | 
            ||
| 189 |         if (!empty($vars['clear'])) { | 
            ||
| 190 |             $this->getLogger()->info(sprintf('Clearing index %s', $this->index->getIndexName())); | 
            ||
| 191 | $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $this->index);  | 
            ||
| 192 | }  | 
            ||
| 193 | }  | 
            ||
| 194 | |||
| 195 | /**  | 
            ||
| 196 | * Index the classes for a specific index  | 
            ||
| 197 | *  | 
            ||
| 198 | * @param array $classes Classes that need indexing  | 
            ||
| 199 | * @param bool $isGroup Indexing a specific group?  | 
            ||
| 200 | * @param int $group Group to index  | 
            ||
| 201 | * @return int  | 
            ||
| 202 | * @throws Exception  | 
            ||
| 203 | * @throws GuzzleException  | 
            ||
| 204 | */  | 
            ||
| 205 | protected function indexClassForIndex($classes, $isGroup, $group): int  | 
            ||
| 206 |     { | 
            ||
| 207 | $groups = 0;  | 
            ||
| 208 |         foreach ($classes as $class) { | 
            ||
| 209 | $groups = $this->indexClass($isGroup, $class, $group);  | 
            ||
| 210 | }  | 
            ||
| 211 | |||
| 212 | return $groups;  | 
            ||
| 213 | }  | 
            ||
| 214 | |||
| 215 | /**  | 
            ||
| 216 |      * Index a single class for a given index. {@link static::indexClassForIndex()} | 
            ||
| 217 | *  | 
            ||
| 218 | * @param bool $isGroup Is a specific group indexed  | 
            ||
| 219 | * @param string $class Class to index  | 
            ||
| 220 | * @param int $group Group to index  | 
            ||
| 221 | * @return int  | 
            ||
| 222 | * @throws GuzzleException  | 
            ||
| 223 | * @throws ValidationException  | 
            ||
| 224 | */  | 
            ||
| 225 | private function indexClass($isGroup, $class, int $group): int  | 
            ||
| 226 |     { | 
            ||
| 227 |         $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $this->getIndex()->getIndexName())); | 
            ||
| 228 | list($totalGroups, $groups) = $this->getGroupSettings($isGroup, $class, $group);  | 
            ||
| 229 |         $this->getLogger()->info(sprintf('Total groups %s', $totalGroups)); | 
            ||
| 230 |         do { // Run from oldest to newest | 
            ||
| 231 |             try { | 
            ||
| 232 | // The unittest param is from phpunit.xml.dist, meant to bypass the exit(0) call  | 
            ||
| 233 | // The pcntl check is for unit tests, but CircleCI does not support PCNTL (yet)  | 
            ||
| 234 | // @todo fix CircleCI to support PCNTL  | 
            ||
| 235 |                 if ($this->hasPCNTL()) { | 
            ||
| 236 | $group = $this->spawnChildren($class, $group, $groups);  | 
            ||
| 237 |                 } else { | 
            ||
| 238 | $this->doReindex($group, $class);  | 
            ||
| 239 | }  | 
            ||
| 240 | $group++;  | 
            ||
| 241 |             } catch (Exception $error) { | 
            ||
| 242 | $this->logException($this->index->getIndexName(), $group, $error);  | 
            ||
| 243 | $group++;  | 
            ||
| 244 | continue;  | 
            ||
| 245 | }  | 
            ||
| 246 | } while ($group <= $groups);  | 
            ||
| 247 | |||
| 248 | return $totalGroups;  | 
            ||
| 249 | }  | 
            ||
| 250 | |||
| 251 | /**  | 
            ||
| 252 | * Check the amount of groups and the total against the isGroup check.  | 
            ||
| 253 | *  | 
            ||
| 254 | * @param bool $isGroup Is it a specific group  | 
            ||
| 255 | * @param string $class Class to check  | 
            ||
| 256 | * @param int $group Current group to index  | 
            ||
| 257 | * @return array  | 
            ||
| 258 | */  | 
            ||
| 259 | private function getGroupSettings($isGroup, $class, int $group): array  | 
            ||
| 260 |     { | 
            ||
| 261 | $totalGroups = (int)ceil($class::get()->count() / $this->getBatchLength());  | 
            ||
| 262 | $groups = $isGroup ? ($group + $this->getCores() - 1) : $totalGroups;  | 
            ||
| 263 | |||
| 264 | return [$totalGroups, $groups];  | 
            ||
| 265 | }  | 
            ||
| 266 | |||
| 267 | private function hasPCNTL()  | 
            ||
| 273 | );  | 
            ||
| 274 | }  | 
            ||
| 275 | |||
| 276 | /**  | 
            ||
| 277 | * For each core, spawn a child process that will handle a separate group.  | 
            ||
| 278 | * This speeds up indexing through CLI massively.  | 
            ||
| 279 | *  | 
            ||
| 280 | * @param string $class Class to index  | 
            ||
| 281 | * @param int $group Group to index  | 
            ||
| 282 | * @param int $groups Total amount of groups  | 
            ||
| 283 | * @return int Last group indexed  | 
            ||
| 284 | * @throws Exception  | 
            ||
| 285 | * @throws GuzzleException  | 
            ||
| 286 | */  | 
            ||
| 287 | private function spawnChildren($class, int $group, int $groups): int  | 
            ||
| 288 |     { | 
            ||
| 289 | $start = $group;  | 
            ||
| 290 | $pids = [];  | 
            ||
| 291 | $cores = $this->getCores();  | 
            ||
| 292 | // for each core, start a grouped indexing  | 
            ||
| 293 |         for ($i = 0; $i < $cores; $i++) { | 
            ||
| 294 | $start = $group + $i;  | 
            ||
| 295 |             if ($start < $groups) { | 
            ||
| 296 | $this->runForkedChild($class, $pids, $i, $start);  | 
            ||
| 297 | }  | 
            ||
| 298 | }  | 
            ||
| 299 | // Wait for each child to finish  | 
            ||
| 300 |         foreach ($pids as $key => $pid) { | 
            ||
| 301 | pcntl_waitpid($pid, $status);  | 
            ||
| 302 |             if ($status === 0) { | 
            ||
| 303 | unset($pids[$key]);  | 
            ||
| 304 | }  | 
            ||
| 305 | }  | 
            ||
| 306 | $commit = $this->index->getClient()->createUpdate();  | 
            ||
| 307 | $commit->addCommit();  | 
            ||
| 308 | |||
| 309 | $this->index->getClient()->update($commit);  | 
            ||
| 310 | |||
| 311 | return $start;  | 
            ||
| 312 | }  | 
            ||
| 313 | |||
| 314 | /**  | 
            ||
| 315 | * Create a fork and run the child  | 
            ||
| 316 | *  | 
            ||
| 317 | * @param string $class Class to index  | 
            ||
| 318 | * @param array $pids Array of all the child Process IDs  | 
            ||
| 319 | * @param int $coreNumber Core number  | 
            ||
| 320 | * @param int $start Start point for the objects  | 
            ||
| 321 | * @return void  | 
            ||
| 322 | * @throws GuzzleException  | 
            ||
| 323 | * @throws ValidationException  | 
            ||
| 324 | */  | 
            ||
| 325 | private function runForkedChild($class, array &$pids, int $coreNumber, int $start): void  | 
            ||
| 326 |     { | 
            ||
| 327 | $pid = pcntl_fork();  | 
            ||
| 328 | // PID needs to be pushed before anything else, for some reason  | 
            ||
| 329 | $pids[$coreNumber] = $pid;  | 
            ||
| 330 | $config = DB::getConfig();  | 
            ||
| 331 | DB::connect($config);  | 
            ||
| 332 | $this->runChild($class, $pid, $start);  | 
            ||
| 333 | }  | 
            ||
| 334 | |||
| 335 | /**  | 
            ||
| 336 | * Ren a single child index operation  | 
            ||
| 337 | *  | 
            ||
| 338 | * @param string $class Class to index  | 
            ||
| 339 | * @param int $pid PID of the child  | 
            ||
| 340 | * @param int $start Position to start  | 
            ||
| 341 | * @throws GuzzleException  | 
            ||
| 342 | * @throws ValidationException  | 
            ||
| 343 | * @throws Exception  | 
            ||
| 344 | */  | 
            ||
| 345 | private function runChild($class, int $pid, int $start): void  | 
            ||
| 358 | }  | 
            ||
| 359 | }  | 
            ||
| 360 | }  | 
            ||
| 361 | |||
| 362 | /**  | 
            ||
| 363 | * Reindex the given group, for each state  | 
            ||
| 364 | *  | 
            ||
| 365 | * @param int $group Group to index  | 
            ||
| 366 | * @param string $class Class to index  | 
            ||
| 367 | * @param bool|int $pcntl Are we a child process or not  | 
            ||
| 368 | * @throws Exception  | 
            ||
| 369 | */  | 
            ||
| 370 | private function doReindex($group, $class, $pcntl = false)  | 
            ||
| 371 |     { | 
            ||
| 372 |         foreach (SiteState::getStates() as $state) { | 
            ||
| 373 |             if ($state !== 'default' && !empty($state)) { | 
            ||
| 374 | SiteState::withState($state);  | 
            ||
| 375 | }  | 
            ||
| 376 | $this->stateReindex($group, $class);  | 
            ||
| 377 | }  | 
            ||
| 378 | |||
| 379 | SiteState::withState(SiteState::DEFAULT_STATE);  | 
            ||
| 380 |         $this->getLogger()->info(sprintf('Indexed group %s', $group)); | 
            ||
| 381 | |||
| 382 |         if (Controller::curr()->getRequest()->getVar('unittest') === 'pcntl') { | 
            ||
| 383 |             throw new Exception('Catch exception for unittests'); | 
            ||
| 384 |         } elseif ($pcntl !== false) { | 
            ||
| 385 | exit(0);  | 
            ||
| 386 | }  | 
            ||
| 387 | }  | 
            ||
| 388 | |||
| 389 | /**  | 
            ||
| 390 | * Index a group of a class for a specific state and index  | 
            ||
| 391 | *  | 
            ||
| 392 | * @param string $group Group to index  | 
            ||
| 393 | * @param string|array $class Class to index  | 
            ||
| 394 | * @throws Exception  | 
            ||
| 395 | */  | 
            ||
| 396 | private function stateReindex($group, $class): void  | 
            ||
| 413 | }  | 
            ||
| 414 | }  | 
            ||
| 415 | |||
| 416 | /**  | 
            ||
| 417 | * Execute the update on the client  | 
            ||
| 418 | *  | 
            ||
| 419 | * @param SS_List $items Items to index  | 
            ||
| 420 | * @throws Exception  | 
            ||
| 421 | */  | 
            ||
| 422 | private function updateIndex($items): void  | 
            ||
| 430 | }  | 
            ||
| 431 | |||
| 432 | /**  | 
            ||
| 433 | * Log an exception if it happens. Most are catched, these logs are for the developers  | 
            ||
| 434 | * to identify problems and fix them.  | 
            ||
| 435 | *  | 
            ||
| 436 | * @param string $index Index that is currently running  | 
            ||
| 437 | * @param int $group Group currently attempted to index  | 
            ||
| 438 | * @param Exception $exception Exception that's been thrown  | 
            ||
| 439 | * @throws GuzzleException  | 
            ||
| 440 | * @throws ValidationException  | 
            ||
| 441 | */  | 
            ||
| 442 | private function logException($index, int $group, Exception $exception): void  | 
            ||
| 452 | }  | 
            ||
| 453 | }  | 
            ||
| 454 |