diff --git a/src/Search/Criteria/SearchCriteria.php b/src/Search/Criteria/SearchCriteria.php index 5c4f64dd..06ed6801 100644 --- a/src/Search/Criteria/SearchCriteria.php +++ b/src/Search/Criteria/SearchCriteria.php @@ -222,7 +222,7 @@ protected function getConjunctions() protected function getConjunction($key) { $conjunctions = $this->getConjunctions(); - if (!array_key_exists($key, $conjunctions)) { + if (!array_key_exists($key, $conjunctions ?? [])) { return null; } diff --git a/src/Search/FullTextSearch.php b/src/Search/FullTextSearch.php index c81ec5b4..8efdeff0 100644 --- a/src/Search/FullTextSearch.php +++ b/src/Search/FullTextSearch.php @@ -67,7 +67,7 @@ public static function get_indexes($class = null, $rebuild = false) } if ($hidden) { - $candidates = array_diff($candidates, $hidden); + $candidates = array_diff($candidates ?? [], $hidden); } // Create all indexes @@ -86,7 +86,7 @@ public static function get_indexes($class = null, $rebuild = false) $valid = array(); foreach ($all as $indexclass => $instance) { - if (is_subclass_of($indexclass, $class)) { + if (is_subclass_of($indexclass, $class ?? '')) { $valid[$indexclass] = $instance; } } diff --git a/src/Search/Indexes/SearchIndex.php b/src/Search/Indexes/SearchIndex.php index 8c18166b..3e16d6cb 100644 --- a/src/Search/Indexes/SearchIndex.php +++ b/src/Search/Indexes/SearchIndex.php @@ -70,7 +70,7 @@ abstract class SearchIndex extends ViewableData */ protected function getSourceName($source) { - $source = explode(self::config()->get('class_delimiter'), $source); + $source = explode(self::config()->get('class_delimiter') ?? '', $source ?? ''); return $source[0]; } @@ -102,7 +102,7 @@ public function __toString() */ public function fieldData($field, $forceType = null, $extraOptions = []) { - $fullfield = str_replace(".", "_", $field); + $fullfield = str_replace(".", "_", $field ?? ''); $sources = $this->getClasses(); foreach ($sources as $source => $options) { @@ -112,8 +112,8 @@ public function fieldData($field, $forceType = null, $extraOptions = []) $found = []; - if (strpos($field, '.') !== false) { - $lookups = explode(".", $field); + if (strpos($field ?? '', '.') !== false) { + $lookups = explode(".", $field ?? ''); $field = array_pop($lookups); foreach ($lookups as $lookup) { @@ -133,7 +133,7 @@ public function fieldData($field, $forceType = null, $extraOptions = []) // we only want to include base class for relation, omit classes that inherited the relation $relationList = Config::inst()->get($dataclass, 'has_one', Config::UNINHERITED); $relationList = (!is_null($relationList)) ? $relationList : []; - if (!array_key_exists($lookup, $relationList)) { + if (!array_key_exists($lookup, $relationList ?? [])) { continue; } @@ -146,7 +146,7 @@ public function fieldData($field, $forceType = null, $extraOptions = []) // we only want to include base class for relation, omit classes that inherited the relation $relationList = Config::inst()->get($dataclass, 'has_many', Config::UNINHERITED); $relationList = (!is_null($relationList)) ? $relationList : []; - if (!array_key_exists($lookup, $relationList)) { + if (!array_key_exists($lookup, $relationList ?? [])) { continue; } @@ -160,7 +160,7 @@ public function fieldData($field, $forceType = null, $extraOptions = []) // we only want to include base class for relation, omit classes that inherited the relation $relationList = Config::inst()->get($dataclass, 'many_many', Config::UNINHERITED); $relationList = (!is_null($relationList)) ? $relationList : []; - if (!array_key_exists($lookup, $relationList)) { + if (!array_key_exists($lookup, $relationList ?? [])) { continue; } @@ -199,7 +199,7 @@ public function fieldData($field, $forceType = null, $extraOptions = []) $class = $this->getSourceName($class); $dataclasses = SearchIntrospection::hierarchy($class, $options['include_children']); - while (count($dataclasses)) { + while (count($dataclasses ?? [])) { $dataclass = array_shift($dataclasses); $type = null; $fieldoptions = $options; @@ -228,9 +228,9 @@ public function fieldData($field, $forceType = null, $extraOptions = []) if ($type) { // Don't search through child classes of a class we matched on. TODO: Should we? - $dataclasses = array_diff($dataclasses, array_values(ClassInfo::subclassesFor($dataclass))); + $dataclasses = array_diff($dataclasses ?? [], array_values(ClassInfo::subclassesFor($dataclass) ?? [])); // Trim arguments off the type string - if (preg_match('/^(\w+)\(/', $type, $match)) { + if (preg_match('/^(\w+)\(/', $type ?? '', $match)) { $type = $match[1]; } // Get the origin @@ -412,7 +412,7 @@ public function variantStateExcluded($state) public function buildDependancyList() { - $this->dependancyList = array_keys($this->getClasses()); + $this->dependancyList = array_keys($this->getClasses() ?? []); foreach ($this->getFieldsIterator() as $name => $field) { if (!isset($field['class'])) { @@ -434,7 +434,7 @@ public function getDerivedFields() $this->derivedFields = array(); foreach ($this->getFieldsIterator() as $name => $field) { - if (count($field['lookup_chain']) < 2) { + if (count($field['lookup_chain'] ?? []) < 2) { continue; } @@ -445,7 +445,7 @@ public function getDerivedFields() $this->derivedFields[$key]['fields'][$fieldname] = $fieldname; SearchIntrospection::add_unique_by_ancestor($this->derivedFields['classes'], $field['class']); } else { - $chain = array_reverse($field['lookup_chain']); + $chain = array_reverse($field['lookup_chain'] ?? []); array_shift($chain); $this->derivedFields[$key] = array( @@ -473,7 +473,7 @@ public function getDocumentIDForState($base, $id, $state) { ksort($state); $parts = array('id' => $id, 'base' => $base, 'state' => json_encode($state)); - return implode('-', array_values($parts)); + return implode('-', array_values($parts ?? [])); } /** @@ -586,7 +586,7 @@ public function getDirtyIDs($class, $id, $statefulids, $fields) // First, if this object is directly contained in the index, add it foreach ($this->classes as $searchclass => $options) { - if ($searchclass == $class || ($options['include_children'] && is_subclass_of($class, $searchclass))) { + if ($searchclass == $class || ($options['include_children'] && is_subclass_of($class, $searchclass ?? ''))) { $base = DataObject::getSchema()->baseDataClass($searchclass); $dirty[$base] = array(); foreach ($statefulids as $statefulid) { @@ -605,7 +605,7 @@ public function getDirtyIDs($class, $id, $statefulids, $fields) if (!SearchIntrospection::is_subclass_of($class, $derivation['classes'])) { continue; } - if (!array_intersect_key($fields, $derivation['fields'])) { + if (!array_intersect_key($fields ?? [], $derivation['fields'])) { continue; } diff --git a/src/Search/Processors/SearchUpdateBatchedProcessor.php b/src/Search/Processors/SearchUpdateBatchedProcessor.php index 9105fe40..cad98f41 100644 --- a/src/Search/Processors/SearchUpdateBatchedProcessor.php +++ b/src/Search/Processors/SearchUpdateBatchedProcessor.php @@ -89,7 +89,7 @@ public function process() } // Don't re-process completed queue - if ($this->currentBatch >= count($this->batches)) { + if ($this->currentBatch >= count($this->batches ?? [])) { return true; } @@ -138,14 +138,14 @@ protected function segmentBatches($source) while ($ids) { // Estimate maximum number of items to take for this iteration, allowing for the soft cap $take = $batchSize - $currentSize; - if (count($ids) <= $take + $softCap) { + if (count($ids ?? []) <= $take + $softCap) { $take += $softCap; } - $items = array_slice($ids, 0, $take, true); - $ids = array_slice($ids, count($items), null, true); + $items = array_slice($ids ?? [], 0, $take, true); + $ids = array_slice($ids ?? [], count($items ?? []), null, true); // Update batch - $currentSize += count($items); + $currentSize += count($items ?? []); $merge = array( $base => array( $stateKey => array( diff --git a/src/Search/Processors/SearchUpdateCommitJobProcessor.php b/src/Search/Processors/SearchUpdateCommitJobProcessor.php index 00d23e05..944c0fc2 100644 --- a/src/Search/Processors/SearchUpdateCommitJobProcessor.php +++ b/src/Search/Processors/SearchUpdateCommitJobProcessor.php @@ -97,7 +97,7 @@ public static function queue($dirty = true, $startAfter = null) if ($dirty) { $indexes = FullTextSearch::get_indexes(); - static::$dirty_indexes = array_keys($indexes); + static::$dirty_indexes = array_keys($indexes ?? []); } return $id; } @@ -126,7 +126,7 @@ public function getAllIndexes() { if (empty($this->indexes)) { $indexes = FullTextSearch::get_indexes(); - $this->indexes = array_keys($indexes); + $this->indexes = array_keys($indexes ?? []); } return $this->indexes; } @@ -135,7 +135,7 @@ public function jobFinished() { // If we've indexed exactly as many as we would like, we are done return $this->skipped - || (count($this->getAllIndexes()) <= count($this->completed)); + || (count($this->getAllIndexes() ?? []) <= count($this->completed ?? [])); } public function prepareForRestart() @@ -213,7 +213,7 @@ protected function commitIndex($index) { // Skip index if this is already complete $name = get_class($index); - if (in_array($name, $this->completed)) { + if (in_array($name, $this->completed ?? [])) { $this->addMessage("Skipping already comitted index {$name}"); return; } @@ -240,8 +240,8 @@ public function setup() public function getJobData() { $data = new stdClass(); - $data->totalSteps = count($this->getAllIndexes()); - $data->currentStep = count($this->completed); + $data->totalSteps = count($this->getAllIndexes() ?? []); + $data->currentStep = count($this->completed ?? []); $data->isComplete = $this->jobFinished(); $data->messages = $this->messages; @@ -265,7 +265,7 @@ public function setJobData($totalSteps, $currentStep, $isComplete, $jobData, $me public function addMessage($message, $severity = 'INFO') { - $severity = strtoupper($severity); + $severity = strtoupper($severity ?? ''); $this->messages[] = '[' . date('Y-m-d H:i:s') . "][$severity] $message"; } diff --git a/src/Search/Processors/SearchUpdateProcessor.php b/src/Search/Processors/SearchUpdateProcessor.php index 0655e6d8..26cad813 100644 --- a/src/Search/Processors/SearchUpdateProcessor.php +++ b/src/Search/Processors/SearchUpdateProcessor.php @@ -55,7 +55,7 @@ public function addDirtyIDs($class, $statefulids, $index) $forclass[$statekey] = array('state' => $state, 'ids' => array($id => array($index))); } elseif (!isset($forclass[$statekey]['ids'][$id])) { $forclass[$statekey]['ids'][$id] = array($index); - } elseif (array_search($index, $forclass[$statekey]['ids'][$id]) === false) { + } elseif (array_search($index, $forclass[$statekey]['ids'][$id] ?? []) === false) { $forclass[$statekey]['ids'][$id][] = $index; // dirty count stays the same } @@ -89,7 +89,7 @@ protected function prepareIndexes() SearchVariant::activate_state($state); // Ensure that indexes for all new / updated objects are included - $objs = DataObject::get($base)->byIDs(array_keys($ids)); + $objs = DataObject::get($base)->byIDs(array_keys($ids ?? [])); /** @var DataObject $obj */ foreach ($objs as $obj) { diff --git a/src/Search/Processors/SearchUpdateQueuedJobProcessor.php b/src/Search/Processors/SearchUpdateQueuedJobProcessor.php index edb70027..cc4557a1 100644 --- a/src/Search/Processors/SearchUpdateQueuedJobProcessor.php +++ b/src/Search/Processors/SearchUpdateQueuedJobProcessor.php @@ -45,7 +45,7 @@ public function getJobType() public function jobFinished() { - return $this->currentBatch >= count($this->batches); + return $this->currentBatch >= count($this->batches ?? []); } public function setup() @@ -68,7 +68,7 @@ public function afterComplete() public function getJobData() { $data = new stdClass(); - $data->totalSteps = count($this->batches); + $data->totalSteps = count($this->batches ?? []); $data->currentStep = $this->currentBatch; $data->isComplete = $this->jobFinished(); $data->messages = $this->messages; @@ -91,7 +91,7 @@ public function setJobData($totalSteps, $currentStep, $isComplete, $jobData, $me public function addMessage($message, $severity = 'INFO') { - $severity = strtoupper($severity); + $severity = strtoupper($severity ?? ''); $this->messages[] = '[' . date('Y-m-d H:i:s') . "][$severity] $message"; } diff --git a/src/Search/SearchIntrospection.php b/src/Search/SearchIntrospection.php index 076e54be..d0aae23f 100644 --- a/src/Search/SearchIntrospection.php +++ b/src/Search/SearchIntrospection.php @@ -21,7 +21,7 @@ class SearchIntrospection public static function is_subclass_of($class, $of) { $ancestry = isset(self::$ancestry[$class]) ? self::$ancestry[$class] : (self::$ancestry[$class] = ClassInfo::ancestry($class)); - return is_array($of) ? (bool)array_intersect($of, $ancestry) : array_key_exists($of, $ancestry); + return is_array($of) ? (bool)array_intersect($of, $ancestry) : array_key_exists($of, $ancestry ?? []); } protected static $hierarchy = array(); @@ -40,12 +40,12 @@ public static function hierarchy($class, $includeSubclasses = true, $dataOnly = $key = "$class!" . ($includeSubclasses ? 'sc' : 'an') . '!' . ($dataOnly ? 'do' : 'al'); if (!isset(self::$hierarchy[$key])) { - $classes = array_values(ClassInfo::ancestry($class)); + $classes = array_values(ClassInfo::ancestry($class) ?? []); if ($includeSubclasses) { - $classes = array_unique(array_merge($classes, array_values(ClassInfo::subclassesFor($class)))); + $classes = array_unique(array_merge($classes, array_values(ClassInfo::subclassesFor($class) ?? []))); } - $idx = array_search(DataObject::class, $classes); + $idx = array_search(DataObject::class, $classes ?? []); if ($idx !== false) { array_splice($classes, 0, $idx+1); } @@ -76,7 +76,7 @@ public static function add_unique_by_ancestor(&$list, $class) // Strip out any subclasses of $class already in the list $children = ClassInfo::subclassesFor($class); - $list = array_diff($list, $children); + $list = array_diff($list ?? [], $children); // Then add the class in $list[] = $class; diff --git a/src/Search/Services/SearchableService.php b/src/Search/Services/SearchableService.php index 421d06f2..de19cb66 100644 --- a/src/Search/Services/SearchableService.php +++ b/src/Search/Services/SearchableService.php @@ -199,11 +199,11 @@ private function classSkipsCanViewCheck(string $class): bool if (empty($skipClasses)) { return false; } - if (in_array($class, $skipClasses)) { + if (in_array($class, $skipClasses ?? [])) { return true; } foreach ($skipClasses as $skipClass) { - if (in_array($skipClass, class_parents($class))) { + if (in_array($skipClass, class_parents($class) ?? [])) { return true; } } diff --git a/src/Search/Updaters/SearchUpdater.php b/src/Search/Updaters/SearchUpdater.php index d279acee..48cb7295 100644 --- a/src/Search/Updaters/SearchUpdater.php +++ b/src/Search/Updaters/SearchUpdater.php @@ -106,7 +106,7 @@ public static function handle_manipulation($manipulation) 'command' => $command, 'fields' => array() ); - } elseif (is_subclass_of($class, $writes[$key]['class'])) { + } elseif (is_subclass_of($class, $writes[$key]['class'] ?? '')) { // Otherwise update the class label if it's more specific than the currently recorded one $writes[$key]['class'] = $class; } @@ -118,7 +118,7 @@ public static function handle_manipulation($manipulation) } // Trim non-delete records without fields - foreach (array_keys($writes) as $key) { + foreach (array_keys($writes ?? []) as $key) { if ($writes[$key]['command'] !== 'delete' && empty($writes[$key]['fields'])) { unset($writes[$key]); } diff --git a/src/Search/Variants/SearchVariant.php b/src/Search/Variants/SearchVariant.php index eeaf970f..e1045ffe 100644 --- a/src/Search/Variants/SearchVariant.php +++ b/src/Search/Variants/SearchVariant.php @@ -202,7 +202,7 @@ public static function withCommon(array $classes = []) // Merge the variants applicable to the current class into the list of common variants, using // the variant instance to replace any previous versions for the same class name (should be singleton // anyway). - $commonVariants = array_replace($commonVariants, $variantsForClass); + $commonVariants = array_replace($commonVariants ?? [], $variantsForClass); } // Cache for future calls @@ -322,7 +322,7 @@ protected function mergeClasses($left, $right) $merged = array_values(array_unique(array_merge($left, $right))); // If there is only one item, return it as a single string - if (count($merged) === 1) { + if (count($merged ?? []) === 1) { return reset($merged); } return $merged; diff --git a/src/Search/Variants/SearchVariantVersioned.php b/src/Search/Variants/SearchVariantVersioned.php index dea5f1ee..ebbc840c 100644 --- a/src/Search/Variants/SearchVariantVersioned.php +++ b/src/Search/Variants/SearchVariantVersioned.php @@ -65,7 +65,7 @@ public function extractManipulationState(&$manipulation) $class = $details['class']; $stage = Versioned::DRAFT; - if (preg_match('/^(.*)_' . Versioned::LIVE . '$/', $table, $matches)) { + if (preg_match('/^(.*)_' . Versioned::LIVE . '$/', $table ?? '', $matches)) { $class = DataObject::getSchema()->tableClass($matches[1]); $stage = Versioned::LIVE; } diff --git a/src/Search/Variants/SearchVariant_Caller.php b/src/Search/Variants/SearchVariant_Caller.php index 1603659a..427dc2b6 100644 --- a/src/Search/Variants/SearchVariant_Caller.php +++ b/src/Search/Variants/SearchVariant_Caller.php @@ -19,7 +19,7 @@ public function call($method, &...$args) $values = array(); foreach ($this->variants as $variant) { - if (method_exists($variant, $method)) { + if (method_exists($variant, $method ?? '')) { $value = $variant->$method(...$args); if ($value !== null) { $values[] = $value; diff --git a/src/Solr/Reindex/Handlers/SolrReindexBase.php b/src/Solr/Reindex/Handlers/SolrReindexBase.php index 91fb7476..71d05d77 100644 --- a/src/Solr/Reindex/Handlers/SolrReindexBase.php +++ b/src/Solr/Reindex/Handlers/SolrReindexBase.php @@ -81,9 +81,9 @@ protected function getClassesForIndex(SolrIndex $index, $filterClasses = null) // Apply filter if (!is_array($filterClasses)) { - $filterClasses = explode(',', $filterClasses); + $filterClasses = explode(',', $filterClasses ?? ''); } - return array_intersect_key($classes, array_combine($filterClasses, $filterClasses)); + return array_intersect_key($classes ?? [], array_combine($filterClasses ?? [], $filterClasses ?? [])); } /** diff --git a/src/Solr/Reindex/Handlers/SolrReindexImmediateHandler.php b/src/Solr/Reindex/Handlers/SolrReindexImmediateHandler.php index bbffd058..27e627ec 100644 --- a/src/Solr/Reindex/Handlers/SolrReindexImmediateHandler.php +++ b/src/Solr/Reindex/Handlers/SolrReindexImmediateHandler.php @@ -109,7 +109,7 @@ protected function processGroup( $res = $process->getOutput(); if ($logger) { - $logger->info(preg_replace('/\r\n|\n/', '$0 ', $res)); + $logger->info(preg_replace('/\r\n|\n/', '$0 ', $res ?? '')); } // If we're in dev mode, commit more often for fun and profit diff --git a/src/Solr/Services/SolrService.php b/src/Solr/Services/SolrService.php index b7177516..a36d52a6 100644 --- a/src/Solr/Services/SolrService.php +++ b/src/Solr/Services/SolrService.php @@ -24,7 +24,7 @@ class SolrService extends SolrService_Core */ protected function coreCommand($command, $core, $params = array()) { - $command = strtoupper($command); + $command = strtoupper($command ?? ''); $params = array_merge($params, array('action' => $command, 'wt' => 'json')); $params[$command === 'CREATE' ? 'name' : 'core'] = $core; diff --git a/src/Solr/Solr.php b/src/Solr/Solr.php index 905eb78e..26e9adb4 100644 --- a/src/Solr/Solr.php +++ b/src/Solr/Solr.php @@ -94,7 +94,7 @@ public static function solr_options() $module = ModuleLoader::getModule('silverstripe/fulltextsearch'); $modulePath = $module->getPath(); - if (version_compare($version, '4', '>=')) { + if (version_compare($version ?? '', '4', '>=')) { $versionDefaults = [ 'service' => Solr4Service::class, 'extraspath' => $modulePath . '/conf/solr/4/extras/', diff --git a/src/Solr/SolrIndex.php b/src/Solr/SolrIndex.php index efbcd7ee..97eac5bc 100644 --- a/src/Solr/SolrIndex.php +++ b/src/Solr/SolrIndex.php @@ -89,7 +89,7 @@ public function getTemplatesPath() { $globalOptions = Solr::solr_options(); $path = $this->templatesPath ? $this->templatesPath : $globalOptions['templatespath']; - return rtrim($path, '/'); + return rtrim($path ?? '', '/'); } /** @@ -127,7 +127,7 @@ public function getIndexName() $indexParts[] = $indexSuffix; } - return implode($indexParts); + return implode($indexParts ?? ''); } public function getTypes() @@ -256,11 +256,11 @@ protected function getCollatedSuggestion($collation = '') */ protected function getNiceSuggestion($collation = '') { - $collationParts = explode(' ', $collation); + $collationParts = explode(' ', $collation ?? ''); // Remove advanced query params from the beginning of each collation part. foreach ($collationParts as $key => &$part) { - $part = ltrim($part, '+'); + $part = ltrim($part ?? '', '+'); } return implode(' ', $collationParts); @@ -275,7 +275,7 @@ protected function getNiceSuggestion($collation = '') */ protected function getSuggestionQueryString($collation = '') { - return str_replace(' ', '+', $this->getNiceSuggestion($collation)); + return str_replace(' ', '+', $this->getNiceSuggestion($collation) ?? ''); } /** @@ -312,7 +312,7 @@ public function fieldData($field, $forceType = null, $extraOptions = array()) { // Ensure that 'boost' is recorded here without being captured by solr $boost = null; - if (array_key_exists('boost', $extraOptions)) { + if (array_key_exists('boost', $extraOptions ?? [])) { $boost = $extraOptions['boost']; unset($extraOptions['boost']); } @@ -515,7 +515,7 @@ protected function classIs($class, $base) } // Check single origin - return $class === $base || is_subclass_of($class, $base); + return $class === $base || is_subclass_of($class, $base ?? ''); } protected function _addField($doc, $object, $field) @@ -536,7 +536,7 @@ protected function _addField($doc, $object, $field) if (!$sub) { continue; } - $sub = gmdate('Y-m-d\TH:i:s\Z', strtotime($sub)); + $sub = gmdate('Y-m-d\TH:i:s\Z', strtotime($sub ?? '')); } /* Solr requires numbers to be valid if presented, not just empty */ @@ -552,7 +552,7 @@ protected function _addField($doc, $object, $field) if (!$value) { return; } - $value = gmdate('Y-m-d\TH:i:s\Z', strtotime($value)); + $value = gmdate('Y-m-d\TH:i:s\Z', strtotime($value ?? '')); } /* Solr requires numbers to be valid if presented, not just empty */ @@ -586,7 +586,7 @@ protected function _addAs($object, $base, $options) // Add the user-specified fields foreach ($this->getFieldsIterator() as $name => $field) { - if ($field['base'] === $base || (is_array($field['base']) && in_array($base, $field['base']))) { + if ($field['base'] === $base || (is_array($field['base']) && in_array($base, $field['base'] ?? []))) { $this->_addField($doc, $object, $field); } } @@ -607,7 +607,7 @@ public function add($object) $docs = array(); foreach ($this->getClasses() as $searchclass => $options) { - if ($searchclass == $class || ($options['include_children'] && is_subclass_of($class, $searchclass))) { + if ($searchclass == $class || ($options['include_children'] && is_subclass_of($class, $searchclass ?? ''))) { $base = DataObject::getSchema()->baseDataClass($searchclass); $docs[] = $this->_addAs($object, $base, $options); } @@ -619,7 +619,7 @@ public function add($object) public function canAdd($class) { foreach ($this->classes as $searchclass => $options) { - if ($searchclass == $class || ($options['include_children'] && is_subclass_of($class, $searchclass))) { + if ($searchclass == $class || ($options['include_children'] && is_subclass_of($class, $searchclass ?? ''))) { return true; } } @@ -713,7 +713,7 @@ public function search(SearchQuery $query, $offset = -1, $limit = -1, $params = // If using boosting, set the clean term separately for highlighting. // See https://issues.apache.org/jira/browse/SOLR-2632 - if (array_key_exists('hl', $params) && !array_key_exists('hl.q', $params)) { + if (array_key_exists('hl', $params ?? []) && !array_key_exists('hl.q', $params ?? [])) { $params['hl.q'] = implode(' ', $hlq); } @@ -870,7 +870,7 @@ public function search(SearchQuery $query, $offset = -1, $limit = -1, $params = */ protected function applySearchVariants(SearchQuery $query) { - $classes = count($query->classes) ? $query->classes : $this->getClasses(); + $classes = count($query->classes ?? []) ? $query->classes : $this->getClasses(); /** @var SearchVariant_Caller $variantCaller */ $variantCaller = SearchVariant::withCommon($classes); @@ -886,7 +886,7 @@ protected function applySearchVariants(SearchQuery $query) */ public function sanitiseClassName($className, $replaceWith = '\\\\') { - return str_replace('\\', $replaceWith, $className); + return str_replace('\\', $replaceWith ?? '', $className ?? ''); } /** @@ -901,14 +901,14 @@ protected function getQueryComponent(SearchQuery $searchQuery, &$hlq = array()) $q = array(); foreach ($searchQuery->search as $search) { $text = $search['text']; - preg_match_all('/"[^"]*"|\S+/', $text, $parts); + preg_match_all('/"[^"]*"|\S+/', $text ?? '', $parts); $fuzzy = $search['fuzzy'] ? '~' : ''; foreach ($parts[0] as $part) { $fields = (isset($search['fields'])) ? $search['fields'] : array(); if (isset($search['boost'])) { - $fields = array_merge($fields, array_keys($search['boost'])); + $fields = array_merge($fields, array_keys($search['boost'] ?? [])); } if ($fields) { $searchq = array(); @@ -1014,7 +1014,7 @@ protected function getExcludeFiltersComponent(SearchQuery $searchQuery) */ protected function getCriteriaComponent(SearchQuery $searchQuery) { - if (count($searchQuery->getCriteria()) === 0) { + if (count($searchQuery->getCriteria() ?? []) === 0) { return null; } @@ -1095,7 +1095,7 @@ public function uploadConfig($store) // Upload additional files foreach (glob($this->getExtrasPath() . '/*') as $file) { - if (is_file($file)) { + if (is_file($file ?? '')) { $store->uploadFile($this->getIndexName(), $file); } } diff --git a/src/Solr/Stores/SolrConfigStore_File.php b/src/Solr/Stores/SolrConfigStore_File.php index 33689c77..beecc38c 100644 --- a/src/Solr/Stores/SolrConfigStore_File.php +++ b/src/Solr/Stores/SolrConfigStore_File.php @@ -20,8 +20,8 @@ public function getTargetDir($index) { $targetDir = "{$this->local}/{$index}/conf"; - if (!is_dir($targetDir)) { - $worked = @mkdir($targetDir, 0770, true); + if (!is_dir($targetDir ?? '')) { + $worked = @mkdir($targetDir ?? '', 0770, true); if (!$worked) { throw new \RuntimeException( @@ -36,7 +36,7 @@ public function getTargetDir($index) public function uploadFile($index, $file) { $targetDir = $this->getTargetDir($index); - copy($file, $targetDir . '/' . basename($file)); + copy($file ?? '', $targetDir . '/' . basename($file ?? '')); } public function uploadString($index, $filename, $string) diff --git a/src/Solr/Stores/SolrConfigStore_Post.php b/src/Solr/Stores/SolrConfigStore_Post.php index 1dc5f291..cc8251ce 100644 --- a/src/Solr/Stores/SolrConfigStore_Post.php +++ b/src/Solr/Stores/SolrConfigStore_Post.php @@ -43,7 +43,7 @@ public function __construct($config) */ public function uploadFile($index, $file) { - $this->uploadString($index, basename($file), file_get_contents($file)); + $this->uploadString($index, basename($file ?? ''), file_get_contents($file ?? '')); } /** diff --git a/src/Solr/Stores/SolrConfigStore_WebDAV.php b/src/Solr/Stores/SolrConfigStore_WebDAV.php index 22bfe790..272913f7 100644 --- a/src/Solr/Stores/SolrConfigStore_WebDAV.php +++ b/src/Solr/Stores/SolrConfigStore_WebDAV.php @@ -46,7 +46,7 @@ public function getTargetDir($index) public function uploadFile($index, $file) { $targetDir = $this->getTargetDir($index); - WebDAV::upload_from_file($file, $targetDir . '/' . basename($file)); + WebDAV::upload_from_file($file, $targetDir . '/' . basename($file ?? '')); } public function uploadString($index, $filename, $string) diff --git a/src/Solr/Tasks/Solr_Reindex.php b/src/Solr/Tasks/Solr_Reindex.php index 1a087514..f6369419 100644 --- a/src/Solr/Tasks/Solr_Reindex.php +++ b/src/Solr/Tasks/Solr_Reindex.php @@ -86,7 +86,7 @@ protected function doReindex($request) continue; } //check the indexname matches the index passed to the request - if (!strcasecmp(singleton($solrIndexClass)->getIndexName(), $index)) { + if (!strcasecmp(singleton($solrIndexClass)->getIndexName() ?? '', $index ?? '')) { //if we match, set the correct index name and move on $index = $solrIndexClass; break; @@ -104,7 +104,7 @@ protected function doReindex($request) // Run grouped batches (id % groups = group) $group = $request->getVar('group'); $indexInstance = singleton($index); - $state = json_decode($request->getVar('variantstate'), true); + $state = json_decode($request->getVar('variantstate') ?? '', true); $handler->runGroup($this->getLogger(), $indexInstance, $state, $class, $groups, $group); return; diff --git a/src/Solr/Writers/SolrSearchQueryWriterBasic.php b/src/Solr/Writers/SolrSearchQueryWriterBasic.php index 46550d1f..b9832b1f 100644 --- a/src/Solr/Writers/SolrSearchQueryWriterBasic.php +++ b/src/Solr/Writers/SolrSearchQueryWriterBasic.php @@ -20,7 +20,7 @@ public function generateQueryString(SearchCriterion $searchCriterion) return sprintf( '%s(%s%s%s)', $this->getComparisonPolarity($searchCriterion->getComparison()), - addslashes($searchCriterion->getTarget()), + addslashes($searchCriterion->getTarget() ?? ''), $this->getComparisonConjunction(), $searchCriterion->getQuoteValue($searchCriterion->getValue()) ); diff --git a/src/Solr/Writers/SolrSearchQueryWriterIn.php b/src/Solr/Writers/SolrSearchQueryWriterIn.php index 37f62f7a..1d63b31c 100644 --- a/src/Solr/Writers/SolrSearchQueryWriterIn.php +++ b/src/Solr/Writers/SolrSearchQueryWriterIn.php @@ -62,7 +62,7 @@ protected function getInComparisonString(SearchCriterion $searchCriterion) $conditions[] = sprintf( '%s%s%s', - addslashes($searchCriterion->getTarget()), + addslashes($searchCriterion->getTarget() ?? ''), $this->getComparisonConjunction(), $value ); diff --git a/src/Solr/Writers/SolrSearchQueryWriterRange.php b/src/Solr/Writers/SolrSearchQueryWriterRange.php index 098a14e7..aad00f24 100644 --- a/src/Solr/Writers/SolrSearchQueryWriterRange.php +++ b/src/Solr/Writers/SolrSearchQueryWriterRange.php @@ -21,7 +21,7 @@ public function generateQueryString(SearchCriterion $searchCriterion) return sprintf( '%s(%s:%s%s%s%s%s)', $this->getComparisonPolarity($searchCriterion->getComparison()), - addslashes($searchCriterion->getTarget()), + addslashes($searchCriterion->getTarget() ?? ''), $this->getOpenComparisonContainer($searchCriterion->getComparison()), $this->getLeftComparison($searchCriterion), $this->getComparisonConjunction(), diff --git a/src/Utils/CombinationsArrayIterator.php b/src/Utils/CombinationsArrayIterator.php index 25c05313..1cf2806a 100644 --- a/src/Utils/CombinationsArrayIterator.php +++ b/src/Utils/CombinationsArrayIterator.php @@ -18,20 +18,21 @@ public function __construct($args) $this->arrays = array(); $this->keys = array(); - $keys = array_keys($args); - $values = array_values($args); + $keys = array_keys($args ?? []); + $values = array_values($args ?? []); foreach ($values as $i => $arg) { - if (is_array($arg) && count($arg)) { + if (is_array($arg) && count($arg ?? [])) { $this->arrays[] = $arg; $this->keys[] = $keys[$i]; } } - $this->numArrays = count($this->arrays); + $this->numArrays = count($this->arrays ?? []); $this->rewind(); } + #[\ReturnTypeWillChange] public function rewind() { if (!$this->numArrays) { @@ -46,11 +47,13 @@ public function rewind() } } + #[\ReturnTypeWillChange] public function valid() { return $this->isValid; } + #[\ReturnTypeWillChange] public function next() { $this->k++; @@ -68,15 +71,17 @@ public function next() } } + #[\ReturnTypeWillChange] public function current() { $res = array(); for ($i = 0; $i < $this->numArrays; $i++) { - $res[$this->keys[$i]] = current($this->arrays[$i]); + $res[$this->keys[$i]] = current($this->arrays[$i] ?? []); } return $res; } + #[\ReturnTypeWillChange] public function key() { return $this->k; diff --git a/src/Utils/Logging/MonologFactory.php b/src/Utils/Logging/MonologFactory.php index 6b6d7792..af4d1892 100644 --- a/src/Utils/Logging/MonologFactory.php +++ b/src/Utils/Logging/MonologFactory.php @@ -90,7 +90,7 @@ protected function getLoggerFor($name) { return Injector::inst()->createWithArgs( Logger::class, - array(strtolower($name)) + array(strtolower($name ?? '')) ); } diff --git a/src/Utils/MultipleArrayIterator.php b/src/Utils/MultipleArrayIterator.php index 7b4a530d..1d94ee07 100644 --- a/src/Utils/MultipleArrayIterator.php +++ b/src/Utils/MultipleArrayIterator.php @@ -14,7 +14,7 @@ public function __construct() $this->arrays = array(); foreach ($args as $arg) { - if (is_array($arg) && count($arg)) { + if (is_array($arg) && count($arg ?? [])) { $this->arrays[] = $arg; } } @@ -22,6 +22,7 @@ public function __construct() $this->rewind(); } + #[\ReturnTypeWillChange] public function rewind() { $this->active = $this->arrays; @@ -30,16 +31,19 @@ public function rewind() } } + #[\ReturnTypeWillChange] public function current() { return $this->active ? current($this->active[0]) : false; } + #[\ReturnTypeWillChange] public function key() { return $this->active ? key($this->active[0]) : false; } + #[\ReturnTypeWillChange] public function next() { if (!$this->active) { @@ -54,8 +58,9 @@ public function next() } } + #[\ReturnTypeWillChange] public function valid() { - return $this->active && (current($this->active[0]) !== false); + return $this->active && (current($this->active[0] ?? []) !== false); } } diff --git a/src/Utils/WebDAV.php b/src/Utils/WebDAV.php index 12432612..afb84a1c 100644 --- a/src/Utils/WebDAV.php +++ b/src/Utils/WebDAV.php @@ -17,7 +17,7 @@ public static function curl_init($url, $method) public static function exists($url) { // WebDAV expects that checking a directory exists has a trailing slash - if (substr($url, -1) != '/') { + if (substr($url ?? '', -1) != '/') { $url .= '/'; } @@ -42,7 +42,7 @@ public static function exists($url) public static function mkdir($url) { - $ch = self::curl_init(rtrim($url, '/') . '/', 'MKCOL'); + $ch = self::curl_init(rtrim($url ?? '', '/') . '/', 'MKCOL'); curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); @@ -72,13 +72,13 @@ public static function put($handle, $url) public static function upload_from_string($string, $url) { $fh = tmpfile(); - fwrite($fh, $string); + fwrite($fh, $string ?? ''); fseek($fh, 0); return self::put($fh, $url); } public static function upload_from_file($string, $url) { - return self::put(fopen($string, 'rb'), $url); + return self::put(fopen($string ?? '', 'rb'), $url); } } diff --git a/tests/BatchedProcessorTest.php b/tests/BatchedProcessorTest.php index 5b4a935c..b5a6050a 100644 --- a/tests/BatchedProcessorTest.php +++ b/tests/BatchedProcessorTest.php @@ -133,28 +133,28 @@ public function testBatching() $this->assertEquals(9, $data->totalSteps); $this->assertEquals(0, $data->currentStep); $this->assertEmpty($data->isComplete); - $this->assertEquals(0, count($index->getAdded())); + $this->assertEquals(0, count($index->getAdded() ?? [])); // Advance state for ($pass = 1; $pass <= 8; $pass++) { $processor->process(); $data = $processor->getJobData(); $this->assertEquals($pass, $data->currentStep); - $this->assertEquals($pass * 5, count($index->getAdded())); + $this->assertEquals($pass * 5, count($index->getAdded() ?? [])); } // Last run should have two hanging items $processor->process(); $data = $processor->getJobData(); $this->assertEquals(9, $data->currentStep); - $this->assertEquals(42, count($index->getAdded())); + $this->assertEquals(42, count($index->getAdded() ?? [])); $this->assertTrue($data->isComplete); // Check any additional queued jobs $processor->afterComplete(); $service = singleton(QueuedJobService::class); $jobs = $service->getJobs(); - $this->assertEquals(1, count($jobs)); + $this->assertEquals(1, count($jobs ?? [])); $this->assertInstanceOf(SearchUpdateCommitJobProcessor::class, $jobs[0]['job']); } @@ -242,7 +242,7 @@ public function testSoftCap() } $data = $processor->getJobData(); $this->assertEquals(8, $data->currentStep); - $this->assertEquals(42, count($index->getAdded())); + $this->assertEquals(42, count($index->getAdded() ?? [])); $this->assertTrue($data->isComplete); } } diff --git a/tests/SolrIndexSubsitesTest.php b/tests/SolrIndexSubsitesTest.php index 167383f9..00b00b23 100644 --- a/tests/SolrIndexSubsitesTest.php +++ b/tests/SolrIndexSubsitesTest.php @@ -223,7 +223,7 @@ public function testCorrectSubsiteIDOnFileWrite() $subsiteIDs = ['0'] + $this->allFixtureIDs(Subsite::class); $subsiteIDs = array_map(function ($v) { return (string) $v; - }, $subsiteIDs); + }, $subsiteIDs ?? []); $mockWrites = [ '35910:File:a:0:{}' => [ 'base' => File::class, @@ -253,7 +253,7 @@ public function testCorrectSubsiteIDOnFileWrite() $tmpMockWrites = $mockWrites; $variant->extractManipulationWriteState($tmpMockWrites); foreach ($tmpMockWrites as $mockWrite) { - $this->assertCount(count($subsiteIDs), $mockWrite['statefulids']); + $this->assertCount(count($subsiteIDs ?? []), $mockWrite['statefulids']); foreach ($mockWrite['statefulids'] as $statefulIDs) { $this->assertContains( (string) $statefulIDs['state'][SearchVariantSubsites::class], diff --git a/tests/SolrIndexTest.php b/tests/SolrIndexTest.php index ada6dacf..bf55f123 100644 --- a/tests/SolrIndexTest.php +++ b/tests/SolrIndexTest.php @@ -478,7 +478,7 @@ public function testShowInSearch() SolrIndexTest_MyDataObjectOne::class . $objOneA->ID, SolrIndexTest_MyDataObjectTwo::class . $objTwoA->ID ]; - return in_array($this->createSolrDocKey($doc), $validKeys); + return in_array($this->createSolrDocKey($doc), $validKeys ?? []); }; $serviceMock @@ -504,7 +504,7 @@ public function testShowInSearch() ->method('deleteById') ->withConsecutive( [$this->callback(function (string $docID) use ($pageA): bool { - return strpos($docID, $pageA->ID . '-' . SiteTree::class) !== false; + return strpos($docID ?? '', $pageA->ID . '-' . SiteTree::class) !== false; })] ); @@ -578,7 +578,7 @@ public function testCanView() File::class . $fileA->ID, SolrIndexTest_MyDataObjectOne::class . $objOneA->ID ]; - return in_array($this->createSolrDocKey($doc), $validKeys); + return in_array($this->createSolrDocKey($doc), $validKeys ?? []); }; $serviceMock @@ -602,7 +602,7 @@ public function testCanView() ->method('deleteById') ->withConsecutive( [$this->callback(function (string $docID) use ($pageA): bool { - return strpos($docID, $pageA->ID . '-' . SiteTree::class) !== false; + return strpos($docID ?? '', $pageA->ID . '-' . SiteTree::class) !== false; })] ); diff --git a/tests/SolrReindexQueuedTest.php b/tests/SolrReindexQueuedTest.php index 2f586f6c..9a666f94 100644 --- a/tests/SolrReindexQueuedTest.php +++ b/tests/SolrReindexQueuedTest.php @@ -233,9 +233,9 @@ public function testRunGroup() // Check IDs $idMessage = $logger->filterMessages('Updated '); - $this->assertNotEmpty(preg_match('/^Updated (?[,\d]+)/i', $idMessage[0], $matches)); - $ids = array_unique(explode(',', $matches['ids'])); - $this->assertEquals(6, count($ids)); + $this->assertNotEmpty(preg_match('/^Updated (?[,\d]+)/i', $idMessage[0] ?? '', $matches)); + $ids = array_unique(explode(',', $matches['ids'] ?? '')); + $this->assertEquals(6, count($ids ?? [])); foreach ($ids as $id) { // Each id should be % 3 == 0 $this->assertEquals(0, $id % 3, "ID $id Should match pattern ID % 3 = 0"); diff --git a/tests/SolrReindexTest.php b/tests/SolrReindexTest.php index bdf98c17..beb5db66 100644 --- a/tests/SolrReindexTest.php +++ b/tests/SolrReindexTest.php @@ -250,8 +250,8 @@ public function testRunGroup() $state = array(SolrReindexTest_Variant::class => '1'); $this->getHandler()->runGroup($logger, $this->index, $state, SolrReindexTest_Item::class, 6, 2); $idMessage = $logger->filterMessages('Updated '); - $this->assertNotEmpty(preg_match('/^Updated (?[,\d]+)/i', $idMessage[0], $matches)); - $ids = array_unique(explode(',', $matches['ids'])); + $this->assertNotEmpty(preg_match('/^Updated (?[,\d]+)/i', $idMessage[0] ?? '', $matches)); + $ids = array_unique(explode(',', $matches['ids'] ?? '')); // Test successful $this->assertNotEmpty($logger->getMessages('Adding ' . SolrReindexTest_Item::class)); @@ -259,7 +259,7 @@ public function testRunGroup() // Test that items in this variant / group are re-indexed // 120 divided into 6 groups should be 20 at least (max 21) - $c = count($ids); + $c = count($ids ?? []); $this->assertTrue($c === 20 || $c === 21, 'Group size is about 20'); foreach ($ids as $id) { // Each id should be % 6 == 2 @@ -301,12 +301,12 @@ public function testRunAllGroups() // Count all ids updated $ids = array(); foreach ($logger->filterMessages('Updated ') as $message) { - $this->assertNotEmpty(preg_match('/^Updated (?[,\d]+)/', $message, $matches)); - $ids = array_unique(array_merge($ids, explode(',', $matches['ids']))); + $this->assertNotEmpty(preg_match('/^Updated (?[,\d]+)/', $message ?? '', $matches)); + $ids = array_unique(array_merge($ids, explode(',', $matches['ids'] ?? ''))); } // Check ids - $this->assertEquals(120, count($ids)); + $this->assertEquals(120, count($ids ?? [])); } /** @@ -385,7 +385,7 @@ public function testShowInSearch() SolrIndexTest_MyDataObjectOne::class . $objOneA->ID, SolrIndexTest_MyDataObjectTwo::class . $objTwoA->ID ]; - return in_array($this->createSolrDocKey($doc), $validKeys); + return in_array($this->createSolrDocKey($doc), $validKeys ?? []); }; $serviceMock @@ -470,7 +470,7 @@ public function testCanView() SolrIndexTest_MyDataObjectOne::class . $objOneA->ID, ]; $solrDocKey = $this->createSolrDocKey($doc); - return in_array($this->createSolrDocKey($doc), $validKeys); + return in_array($this->createSolrDocKey($doc), $validKeys ?? []); }; $serviceMock diff --git a/tests/SolrReindexTest/SolrReindexTest_RecordingLogger.php b/tests/SolrReindexTest/SolrReindexTest_RecordingLogger.php index 3606e029..c4d18792 100644 --- a/tests/SolrReindexTest/SolrReindexTest_RecordingLogger.php +++ b/tests/SolrReindexTest/SolrReindexTest_RecordingLogger.php @@ -49,9 +49,9 @@ public function clear() public function filterMessages($containing) { return array_values(array_filter( - $this->getMessages(), + $this->getMessages() ?? [], function ($content) use ($containing) { - return stripos($content, $containing) !== false; + return stripos($content ?? '', $containing ?? '') !== false; } )); } @@ -69,6 +69,6 @@ public function countMessages($containing = null) } else { $messages = $this->getMessages(); } - return count($messages); + return count($messages ?? []); } } diff --git a/tests/SolrWritersTest.php b/tests/SolrWritersTest.php index 779dedfc..3fa259bf 100644 --- a/tests/SolrWritersTest.php +++ b/tests/SolrWritersTest.php @@ -185,7 +185,7 @@ public function testComplexPositiveFilterQueryString() $index = new SolrIndexTest_FakeIndex(); - $this->assertTrue(in_array($expected, $index->getFiltersComponent($query))); + $this->assertTrue(in_array($expected, $index->getFiltersComponent($query) ?? [])); } /** @@ -235,6 +235,6 @@ public function testComplexNegativeFilterQueryString() $index = new SolrIndexTest_FakeIndex(); - $this->assertTrue(in_array($expected, $index->getFiltersComponent($query))); + $this->assertTrue(in_array($expected, $index->getFiltersComponent($query) ?? [])); } }