MINOR Reduce some code complexity, update array syntax and injected SQLSelect etc

This commit is contained in:
Robbie Averill 2018-09-27 16:40:23 +02:00
parent 89df5515ae
commit adb4d1f92d
8 changed files with 89 additions and 88 deletions

View File

@ -125,24 +125,24 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
$list->dataQuery = $res;
}
return $list;
} else {
$list = clone $this;
$list->inAlterDataQueryCall = true;
try {
$res = call_user_func($callback, $list->dataQuery, $list);
if ($res) {
$list->dataQuery = $res;
}
} catch (Exception $e) {
$list->inAlterDataQueryCall = false;
throw $e;
}
$list->inAlterDataQueryCall = false;
return $list;
}
$list = clone $this;
$list->inAlterDataQueryCall = true;
try {
$res = call_user_func($callback, $list->dataQuery, $list);
if ($res) {
$list->dataQuery = $res;
}
} catch (Exception $e) {
$list->inAlterDataQueryCall = false;
throw $e;
}
$list->inAlterDataQueryCall = false;
return $list;
}
/**
@ -170,8 +170,8 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
$clone = clone $this;
if (is_array($keyOrArray)) {
foreach ($keyOrArray as $key => $val) {
$clone->dataQuery->setQueryParam($key, $val);
foreach ($keyOrArray as $key => $value) {
$clone->dataQuery->setQueryParam($key, $value);
}
} else {
$clone->dataQuery->setQueryParam($keyOrArray, $val);
@ -186,7 +186,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
* @param array $parameters Out variable for parameters required for this query
* @return string The resulting SQL query (may be paramaterised)
*/
public function sql(&$parameters = array())
public function sql(&$parameters = [])
{
return $this->dataQuery->query()->sql($parameters);
}
@ -330,11 +330,11 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
list($col, $dir) = func_get_args();
// Validate direction
if (!in_array(strtolower($dir), array('desc','asc'))) {
if (!in_array(strtolower($dir), ['desc', 'asc'])) {
user_error('Second argument to sort must be either ASC or DESC');
}
$sort = array($col => $dir);
$sort = [$col => $dir];
} else {
$sort = func_get_arg(0);
}
@ -342,7 +342,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
return $this->alterDataQuery(function (DataQuery $query, DataList $list) use ($sort) {
if (is_string($sort) && $sort) {
if (stristr($sort, ' asc') || stristr($sort, ' desc')) {
if (false !== stripos($sort, ' asc') || false !== stripos($sort, ' desc')) {
$query->sort($sort);
} else {
$list->applyRelation($sort, $column, true);
@ -393,7 +393,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
break;
case 2:
$filters = array($arguments[0] => $arguments[1]);
$filters = [$arguments[0] => $arguments[1]];
break;
default:
@ -415,7 +415,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
foreach ($filterArray as $expression => $value) {
$filter = $this->createSearchFilter($expression, $value);
$list = $list->alterDataQuery(array($filter, 'apply'));
$list = $list->alterDataQuery([$filter, 'apply']);
}
return $list;
@ -448,7 +448,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
public function filterAny()
{
$numberFuncArgs = count(func_get_args());
$whereArguments = array();
$whereArguments = [];
if ($numberFuncArgs == 1 && is_array(func_get_arg(0))) {
$whereArguments = func_get_arg(0);
@ -606,7 +606,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
public function exclude()
{
$numberFuncArgs = count(func_get_args());
$whereArguments = array();
$whereArguments = [];
if ($numberFuncArgs == 1 && is_array(func_get_arg(0))) {
$whereArguments = func_get_arg(0);
@ -644,7 +644,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
public function excludeAny()
{
$numberFuncArgs = count(func_get_args());
$whereArguments = array();
$whereArguments = [];
if ($numberFuncArgs == 1 && is_array(func_get_arg(0))) {
$whereArguments = func_get_arg(0);
@ -695,7 +695,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
* @param array $parameters Any additional parameters if the join is a parameterised subquery
* @return static
*/
public function innerJoin($table, $onClause, $alias = null, $order = 20, $parameters = array())
public function innerJoin($table, $onClause, $alias = null, $order = 20, $parameters = [])
{
return $this->alterDataQuery(function (DataQuery $query) use ($table, $onClause, $alias, $order, $parameters) {
$query->innerJoin($table, $onClause, $alias, $order, $parameters);
@ -714,7 +714,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
* @param array $parameters Any additional parameters if the join is a parameterised subquery
* @return static
*/
public function leftJoin($table, $onClause, $alias = null, $order = 20, $parameters = array())
public function leftJoin($table, $onClause, $alias = null, $order = 20, $parameters = [])
{
return $this->alterDataQuery(function (DataQuery $query) use ($table, $onClause, $alias, $order, $parameters) {
$query->leftJoin($table, $onClause, $alias, $order, $parameters);
@ -731,7 +731,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
{
$query = $this->dataQuery->query();
$rows = $query->execute();
$results = array();
$results = [];
foreach ($rows as $row) {
$results[] = $this->createDataObject($row);
@ -747,7 +747,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
*/
public function toNestedArray()
{
$result = array();
$result = [];
foreach ($this as $item) {
$result[] = $item->toMap();
@ -1014,7 +1014,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
*/
public function setByIDList($idList)
{
$has = array();
$has = [];
// Index current data
foreach ($this->column() as $id) {
@ -1048,7 +1048,7 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
public function getIDList()
{
$ids = $this->column("ID");
return $ids ? array_combine($ids, $ids) : array();
return $ids ? array_combine($ids, $ids) : [];
}
/**
@ -1137,7 +1137,6 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
* list manipulation
*
* @param mixed $item
* @param array|null $extraFields Any extra fields, if supported by this list
*/
public function add($item)
{

View File

@ -3112,9 +3112,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
if ($cache) {
return self::$_cache_get_one[$callerClass][$cacheKey] ?: null;
} else {
return $item;
}
return $item;
}
/**

View File

@ -42,7 +42,7 @@ class HasManyList extends RelationList
}
/**
* @param null|int $id
* @param null|int|array|string $id
* @return array
*/
protected function foreignIDFilter($id = null)
@ -54,9 +54,10 @@ class HasManyList extends RelationList
// Apply relation filter
$key = DataObject::getSchema()->sqlColumnForField($this->dataClass(), $this->getForeignKey());
if (is_array($id)) {
return array("$key IN (" . DB::placeholders($id) . ")" => $id);
} elseif ($id !== null) {
return array($key => $id);
return ["$key IN (" . DB::placeholders($id) . ")" => $id];
}
if ($id !== null) {
return [$key => $id];
}
return null;
}

View File

@ -39,7 +39,7 @@ class ManyManyList extends RelationList
/**
* @var array $_compositeExtraFields
*/
protected $_compositeExtraFields = array();
protected $_compositeExtraFields = [];
/**
* Create a new ManyManyList object.
@ -59,7 +59,7 @@ class ManyManyList extends RelationList
*
* @example new ManyManyList('Group','Group_Members', 'GroupID', 'MemberID');
*/
public function __construct($dataClass, $joinTable, $localKey, $foreignKey, $extraFields = array())
public function __construct($dataClass, $joinTable, $localKey, $foreignKey, $extraFields = [])
{
parent::__construct($dataClass);
@ -97,13 +97,13 @@ class ManyManyList extends RelationList
*/
protected function appendExtraFieldsToQuery()
{
$finalized = array();
$finalized = [];
foreach ($this->extraFields as $field => $spec) {
$obj = Injector::inst()->create($spec);
if ($obj instanceof DBComposite) {
$this->_compositeExtraFields[$field] = array();
$this->_compositeExtraFields[$field] = [];
// append the composite field names to the select
foreach ($obj->compositeDatabaseFields() as $subField => $subSpec) {
@ -130,12 +130,12 @@ class ManyManyList extends RelationList
public function createDataObject($row)
{
// remove any composed fields
$add = array();
$add = [];
if ($this->_compositeExtraFields) {
foreach ($this->_compositeExtraFields as $fieldName => $composed) {
// convert joined extra fields into their composite field types.
$value = array();
$value = [];
foreach ($composed as $subField) {
if (isset($row[$fieldName . $subField])) {
@ -165,7 +165,7 @@ class ManyManyList extends RelationList
* Return a filter expression for when getting the contents of the
* relationship for some foreign ID
*
* @param int|null $id
* @param int|null|string|array $id
*
* @return array
*/
@ -178,9 +178,10 @@ class ManyManyList extends RelationList
// Apply relation filter
$key = "\"{$this->joinTable}\".\"{$this->foreignKey}\"";
if (is_array($id)) {
return array("$key IN (" . DB::placeholders($id) . ")" => $id);
} elseif ($id !== null) {
return array($key => $id);
return ["$key IN (" . DB::placeholders($id) . ")" => $id];
}
if ($id !== null) {
return [$key => $id];
}
return null;
}
@ -217,11 +218,11 @@ class ManyManyList extends RelationList
* Column names should be ANSI quoted.
* @throws Exception
*/
public function add($item, $extraFields = array())
public function add($item, $extraFields = [])
{
// Ensure nulls or empty strings are correctly treated as empty arrays
if (empty($extraFields)) {
$extraFields = array();
$extraFields = [];
}
// Determine ID of new record
@ -251,7 +252,7 @@ class ManyManyList extends RelationList
// Apply this item to each given foreign ID record
if (!is_array($foreignIDs)) {
$foreignIDs = array($foreignIDs);
$foreignIDs = [$foreignIDs];
}
foreach ($foreignIDs as $foreignID) {
// Check for existing records for this item
@ -259,28 +260,28 @@ class ManyManyList extends RelationList
// With the current query, simply add the foreign and local conditions
// The query can be a bit odd, especially if custom relation classes
// don't join expected tables (@see Member_GroupSet for example).
$query = new SQLSelect("*", "\"{$this->joinTable}\"");
$query = SQLSelect::create("*", "\"{$this->joinTable}\"");
$query->addWhere($foreignFilter);
$query->addWhere(array(
$query->addWhere([
"\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID
));
]);
$hasExisting = ($query->count() > 0);
} else {
$hasExisting = false;
}
// Blank manipulation
$manipulation = array(
$this->joinTable => array(
$manipulation = [
$this->joinTable => [
'command' => $hasExisting ? 'update' : 'insert',
'fields' => array()
)
);
'fields' => [],
],
];
if ($hasExisting) {
$manipulation[$this->joinTable]['where'] = array(
$manipulation[$this->joinTable]['where'] = [
"\"{$this->joinTable}\".\"{$this->foreignKey}\"" => $foreignID,
"\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID
);
];
}
if ($extraFields && $this->extraFields) {
@ -334,7 +335,7 @@ class ManyManyList extends RelationList
throw new InvalidArgumentException("ManyManyList::removeById() expecting an ID");
}
$query = new SQLDelete("\"{$this->joinTable}\"");
$query = SQLDelete::create("\"{$this->joinTable}\"");
if ($filter = $this->foreignIDWriteFilter($this->getForeignID())) {
$query->setWhere($filter);
@ -342,9 +343,9 @@ class ManyManyList extends RelationList
user_error("Can't call ManyManyList::remove() until a foreign ID is set");
}
$query->addWhere(array(
$query->addWhere([
"\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID
));
]);
$query->execute();
}
@ -375,13 +376,13 @@ class ManyManyList extends RelationList
// Use a sub-query as SQLite does not support setting delete targets in
// joined queries.
$delete = new SQLDelete();
$delete = SQLDelete::create();
$delete->setFrom("\"{$this->joinTable}\"");
$delete->addWhere($this->foreignIDFilter());
$subSelect = $selectQuery->sql($parameters);
$delete->addWhere(array(
$delete->addWhere([
"\"{$this->joinTable}\".\"{$this->localKey}\" IN ($subSelect)" => $parameters
));
]);
$delete->execute();
}
@ -396,7 +397,7 @@ class ManyManyList extends RelationList
*/
public function getExtraData($componentName, $itemID)
{
$result = array();
$result = [];
// Skip if no extrafields or unsaved record
if (empty($this->extraFields) || empty($itemID)) {
@ -407,20 +408,20 @@ class ManyManyList extends RelationList
throw new InvalidArgumentException('ManyManyList::getExtraData() passed a non-numeric child ID');
}
$cleanExtraFields = array();
$cleanExtraFields = [];
foreach ($this->extraFields as $fieldName => $dbFieldSpec) {
$cleanExtraFields[] = "\"{$fieldName}\"";
}
$query = new SQLSelect($cleanExtraFields, "\"{$this->joinTable}\"");
$query = SQLSelect::create($cleanExtraFields, "\"{$this->joinTable}\"");
$filter = $this->foreignIDWriteFilter($this->getForeignID());
if ($filter) {
$query->setWhere($filter);
} else {
throw new BadMethodCallException("Can't call ManyManyList::getExtraData() until a foreign ID is set");
}
$query->addWhere(array(
$query->addWhere([
"\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID
));
]);
$queryResult = $query->execute()->current();
if ($queryResult) {
foreach ($queryResult as $fieldName => $value) {

View File

@ -154,7 +154,7 @@ class ManyManyThroughList extends RelationList
{
// Ensure nulls or empty strings are correctly treated as empty arrays
if (empty($extraFields)) {
$extraFields = array();
$extraFields = [];
}
// Determine ID of new record

View File

@ -53,7 +53,7 @@ class ManyManyThroughQueryManipulator implements DataQueryManipulator
/**
* Build query manipulator for a given join table. Additional parameters (foreign key, etc)
* will be infered at evaluation from query parameters set via the ManyManyThroughList
* will be inferred at evaluation from query parameters set via the ManyManyThroughList
*
* @param string $joinClass Class name of the joined dataobject record
* @param string $localKey The key in the join table that maps to the dataClass' PK.

View File

@ -128,8 +128,8 @@ class PolymorphicHasManyList extends HasManyList
$foreignKey = $this->foreignKey;
if (empty($foreignID)
|| (is_array($foreignID) && in_array($item->$foreignKey, $foreignID))
|| $foreignID == $item->$foreignKey
|| (is_array($foreignID) && in_array($item->$foreignKey, $foreignID))
) {
$item->$foreignKey = null;
$item->$classForeignKey = null;

View File

@ -29,7 +29,7 @@ class Member_GroupSet extends ManyManyList
* Recursively selects all groups applied to this member, as well as any
* parent groups of any applied groups
*
* @param array|integer $id (optional) An ID or an array of IDs - if not provided, will use the current
* @param array|int|string|null $id (optional) An ID or an array of IDs - if not provided, will use the current
* ids as per getForeignID
* @return array Condition In array(SQL => parameters format)
*/
@ -41,24 +41,24 @@ class Member_GroupSet extends ManyManyList
// Find directly applied groups
$manyManyFilter = parent::foreignIDFilter($id);
$query = new SQLSelect('"Group_Members"."GroupID"', '"Group_Members"', $manyManyFilter);
$query = SQLSelect::create('"Group_Members"."GroupID"', '"Group_Members"', $manyManyFilter);
$groupIDs = $query->execute()->column();
// Get all ancestors, iteratively merging these into the master set
$allGroupIDs = array();
$allGroupIDs = [];
while ($groupIDs) {
$allGroupIDs = array_merge($allGroupIDs, $groupIDs);
$groupIDs = DataObject::get("SilverStripe\\Security\\Group")->byIDs($groupIDs)->column("ParentID");
$groupIDs = DataObject::get(Group::class)->byIDs($groupIDs)->column("ParentID");
$groupIDs = array_filter($groupIDs);
}
// Add a filter to this DataList
if (!empty($allGroupIDs)) {
$allGroupIDsPlaceholders = DB::placeholders($allGroupIDs);
return array("\"Group\".\"ID\" IN ($allGroupIDsPlaceholders)" => $allGroupIDs);
} else {
return array('"Group"."ID"' => 0);
return ["\"Group\".\"ID\" IN ($allGroupIDsPlaceholders)" => $allGroupIDs];
}
return ['"Group"."ID"' => 0];
}
public function foreignIDWriteFilter($id = null)
@ -81,7 +81,7 @@ class Member_GroupSet extends ManyManyList
}
// Check if this group is allowed to be added
if ($this->canAddGroups(array($itemID))) {
if ($this->canAddGroups([$itemID])) {
parent::add($item, $extraFields);
}
}
@ -106,13 +106,13 @@ class Member_GroupSet extends ManyManyList
// Use a sub-query as SQLite does not support setting delete targets in
// joined queries.
$delete = new SQLDelete();
$delete = SQLDelete::create();
$delete->setFrom("\"{$this->joinTable}\"");
$delete->addWhere(parent::foreignIDFilter());
$subSelect = $selectQuery->sql($parameters);
$delete->addWhere(array(
$delete->addWhere([
"\"{$this->joinTable}\".\"{$this->localKey}\" IN ($subSelect)" => $parameters
));
]);
$delete->execute();
}