Skip to content

Commit

Permalink
Merge pull request #450 from creative-commoners/pulls/3/php81
Browse files Browse the repository at this point in the history
ENH PHP 8.1 compatibility
  • Loading branch information
GuySartorelli authored Apr 22, 2022
2 parents 4f7e836 + 180ac1b commit eced2e2
Show file tree
Hide file tree
Showing 42 changed files with 114 additions and 114 deletions.
2 changes: 1 addition & 1 deletion src/Auth/BasicAuthAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,6 @@ public function isApplicable(HTTPRequest $request)
*/
protected function hasAuthHandler($servervar)
{
return isset($_SERVER[$servervar]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$servervar]);
return isset($_SERVER[$servervar]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$servervar] ?? '');
}
}
10 changes: 5 additions & 5 deletions src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ protected function validateOrigin($origin, $allowedOrigins)
if ($allowedOrigin === '*') {
return true;
}
if (strcasecmp($allowedOrigin, $origin) === 0) {
if (strcasecmp($allowedOrigin ?? '', $origin ?? '') === 0) {
return true;
}
}
Expand Down Expand Up @@ -347,7 +347,7 @@ protected function getRequestOrigin(HTTPRequest $request)
$referer = $request->getHeader('Referer');
if ($referer) {
// Extract protocol, hostname, and port
$refererParts = parse_url($referer);
$refererParts = parse_url($referer ?? '');
if (!$refererParts) {
return null;
}
Expand Down Expand Up @@ -394,7 +394,7 @@ protected function handleOptions(HTTPRequest $request)
protected function getRequestQueryVariables(HTTPRequest $request)
{
$contentType = $request->getHeader('content-type');
$isJson = preg_match('#^application/json\b#', $contentType);
$isJson = preg_match('#^application/json\b#', $contentType ?? '');
if ($isJson) {
$rawBody = $request->getBody();
$data = json_decode($rawBody ?: '', true);
Expand All @@ -404,7 +404,7 @@ protected function getRequestQueryVariables(HTTPRequest $request)
} else {
$query = $request->requestVar('query');
$id = $request->requestVar('id');
$variables = json_decode($request->requestVar('variables'), true);
$variables = json_decode($request->requestVar('variables') ?? '', true);
}

if ($id) {
Expand Down Expand Up @@ -515,7 +515,7 @@ public static function flush()
$routes = Director::config()->get('rules');
foreach ($routes as $pattern => $controllerInfo) {
$routeClass = (is_string($controllerInfo)) ? $controllerInfo : $controllerInfo['Controller'];
if (stristr($routeClass, Controller::class) !== false) {
if (stristr($routeClass ?? '', Controller::class) !== false) {
try {
$inst = Injector::inst()->convertServiceProperty($routeClass);
if ($inst instanceof Controller) {
Expand Down
2 changes: 1 addition & 1 deletion src/FieldCreator.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ protected function getResolver()

return function () use ($resolver) {
$args = func_get_args();
$result = call_user_func_array($resolver, $args);
$result = call_user_func_array($resolver, $args ?? []);

return $result;
};
Expand Down
2 changes: 1 addition & 1 deletion src/InterfaceTypeCreator.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ protected function getTypeResolver()

return function () use ($resolver) {
$args = func_get_args();
return call_user_func_array($resolver, $args);
return call_user_func_array($resolver, $args ?? []);
};
}

Expand Down
26 changes: 13 additions & 13 deletions src/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ protected function callMiddleware(Schema $schema, $query, $context, $params, cal
// Reverse middlewares
$next = $last;
// Filter out any middlewares that are set to `false`, e.g. via config
$middlewares = array_reverse(array_filter($this->getMiddlewares()));
$middlewares = array_reverse(array_filter($this->getMiddlewares() ?? []));
/** @var QueryMiddleware $middleware */
foreach ($middlewares as $middleware) {
$next = function ($schema, $query, $context, $params) use ($middleware, $next) {
Expand Down Expand Up @@ -205,20 +205,20 @@ public function applyConfig(array $config)
$this->extend('updateConfig', $config);

// Bootstrap schema class mapping from config
if (array_key_exists('typeNames', $config)) {
if (array_key_exists('typeNames', $config ?? [])) {
StaticSchema::inst()->setTypeNames($config['typeNames']);
}
if (array_key_exists('fieldFormatter', $config)) {
if (array_key_exists('fieldFormatter', $config ?? [])) {
StaticSchema::inst()->setFieldFormatter($config['fieldFormatter']);
}
if (array_key_exists('fieldAccessor', $config)) {
if (array_key_exists('fieldAccessor', $config ?? [])) {
StaticSchema::inst()->setFieldAccessor(Injector::inst()->get($config['fieldAccessor']));
} else {
StaticSchema::inst()->setFieldAccessor(Injector::inst()->get(NaiveFieldAccessor::class));
}

// Types (incl. Interfaces and InputTypes)
if (array_key_exists('types', $config)) {
if (array_key_exists('types', $config ?? [])) {
foreach ($config['types'] as $name => $typeCreatorClass) {
$typeCreator = Injector::inst()->create($typeCreatorClass, $this);
if (!($typeCreator instanceof TypeCreator)) {
Expand All @@ -234,7 +234,7 @@ public function applyConfig(array $config)
}

// Queries
if ($config && array_key_exists('queries', $config)) {
if ($config && array_key_exists('queries', $config ?? [])) {
foreach ($config['queries'] as $name => $queryCreatorClass) {
$queryCreator = Injector::inst()->create($queryCreatorClass, $this);
if (!($queryCreator instanceof QueryCreator)) {
Expand All @@ -251,7 +251,7 @@ public function applyConfig(array $config)
}

// Mutations
if ($config && array_key_exists('mutations', $config)) {
if ($config && array_key_exists('mutations', $config ?? [])) {
foreach ($config['mutations'] as $name => $mutationCreatorClass) {
$mutationCreator = Injector::inst()->create($mutationCreatorClass, $this);
if (!($mutationCreator instanceof MutationCreator)) {
Expand All @@ -274,7 +274,7 @@ public function applyConfig(array $config)
}
if (isset($config['scaffolding_providers'])) {
foreach ($config['scaffolding_providers'] as $provider) {
if (!class_exists($provider)) {
if (!class_exists($provider ?? '')) {
throw new InvalidArgumentException(sprintf(
'Scaffolding provider %s does not exist.',
$provider
Expand Down Expand Up @@ -315,7 +315,7 @@ public function schema()
'fields' => function () {
return array_map(function ($query) {
return is_callable($query) ? $query() : $query;
}, $this->queries);
}, $this->queries ?? []);
},
]);
} else {
Expand All @@ -330,7 +330,7 @@ public function schema()
'fields' => function () {
return array_map(function ($mutation) {
return is_callable($mutation) ? $mutation() : $mutation;
}, $this->mutations);
}, $this->mutations ?? []);
},
]);
}
Expand Down Expand Up @@ -491,7 +491,7 @@ public function setSchemaKey($schemaKey)
__CLASS__
));
}
if (preg_match('/[^A-Za-z0-9_-]/', $schemaKey)) {
if (preg_match('/[^A-Za-z0-9_-]/', $schemaKey ?? '')) {
throw new InvalidArgumentException(sprintf(
'%s schemaKey may only contain alphanumeric characters, dashes, and underscores',
__CLASS__
Expand Down Expand Up @@ -519,7 +519,7 @@ public static function formatError(Error $exception)
if (!empty($locations)) {
$error['locations'] = array_map(function (SourceLocation $loc) {
return $loc->toArray();
}, $locations);
}, $locations ?? []);
}

$previous = $exception->getPrevious();
Expand Down Expand Up @@ -619,7 +619,7 @@ public function serialiseResult($executionResult)
if (!empty($executionResult->errors)) {
return [
'data' => $executionResult->data,
'errors' => array_map($this->errorFormatter, $executionResult->errors),
'errors' => array_map($this->errorFormatter, $executionResult->errors ?? []),
];
} else {
return [
Expand Down
6 changes: 3 additions & 3 deletions src/Middleware/CSRFMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ public function process(Schema $schema, $query, $context, $params, callable $nex
protected function isMutation($query)
{
// Simple string matching as a first check to prevent unnecessary static analysis
if (stristr($query, Manager::MUTATION_ROOT) === false) {
if (stristr($query ?? '', Manager::MUTATION_ROOT ?? '') === false) {
return false;
}

// If "mutation" is the first expression in the query, then it's a mutation.
if (preg_match('/^\s*'.preg_quote(Manager::MUTATION_ROOT, '/').'/', $query)) {
if (preg_match('/^\s*'.preg_quote(Manager::MUTATION_ROOT ?? '', '/').'/', $query ?? '')) {
return true;
}

Expand All @@ -52,7 +52,7 @@ protected function isMutation($query)
NodeKind::OPERATION_DEFINITION,
NodeKind::OPERATION_TYPE_DEFINITION
];
if (!in_array($statement->kind, $options, true)) {
if (!in_array($statement->kind, $options ?? [], true)) {
continue;
}
if ($statement->operation === Manager::MUTATION_ROOT) {
Expand Down
2 changes: 1 addition & 1 deletion src/Middleware/HTTPMethodMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function process(Schema $schema, $query, $context, $params, callable $nex
throw new Exception('Request method must be POST or GET');
}

if (preg_match('/^\s*mutation/', $query)) {
if (preg_match('/^\s*mutation/', $query ?? '')) {
if (!$isPOST) {
throw new Exception('Mutations must use the POST request method');
}
Expand Down
2 changes: 1 addition & 1 deletion src/Pagination/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ protected function applySort($list, $sortBy)
foreach ($sortBy as $sortInput) {
if (isset($sortInput['field'])) {
$direction = isset($sortInput['direction']) ? $sortInput['direction'] : 'ASC';
if (!array_key_exists($sortInput['field'], $sortableFields)) {
if (!array_key_exists($sortInput['field'], $sortableFields ?? [])) {
throw new InvalidArgumentException(sprintf(
'"%s" is not a valid sort column',
$sortInput['field']
Expand Down
4 changes: 2 additions & 2 deletions src/Pagination/SortInputTypeCreator.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public function getAttributes()
public function attributes()
{
return [
'name' => ucfirst($this->inputName) .'SortInputType',
'name' => ucfirst($this->inputName ?? '') .'SortInputType',
'description' => 'Define the sorting',
];
}
Expand All @@ -95,7 +95,7 @@ public function fields()
}

$sortableField = new EnumType([
'name' => ucfirst($this->inputName) . 'SortFieldType',
'name' => ucfirst($this->inputName ?? '') . 'SortFieldType',
'description' => 'Field name to sort by.',
'values' => $values,
]);
Expand Down
6 changes: 3 additions & 3 deletions src/PersistedQuery/FileProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ public function getQueryMapping($schemaKey = 'default')
return [];
}

$path = trim($pathWithKey[$schemaKey]);
$contents = trim(file_get_contents($path));
$result = json_decode($contents, true);
$path = trim($pathWithKey[$schemaKey] ?? '');
$contents = trim(file_get_contents($path ?? '') ?? '');
$result = json_decode($contents ?? '', true);
if (!is_array($result)) {
return [];
}
Expand Down
2 changes: 1 addition & 1 deletion src/PersistedQuery/GuzzleHTTPClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function getURL($url, $timeout = 5)

try {
$response = $client->send($request, ['timeout' => $timeout]);
$contents = trim($response->getBody()->getContents());
$contents = trim($response->getBody()->getContents() ?? '');
} catch (RuntimeException $e) {
user_error($e->getMessage(), E_USER_WARNING);
return null;
Expand Down
4 changes: 2 additions & 2 deletions src/PersistedQuery/HTTPProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,11 @@ public function getQueryMapping($schemaKey = 'default')
return [];
}

$url = trim($urlWithKey[$schemaKey]);
$url = trim($urlWithKey[$schemaKey] ?? '');
$map = null;
try {
$contents = $this->getClient()->getURL($url, $this->config()->get('timeout'));
$map = json_decode($contents, true);
$map = json_decode($contents ?? '', true);
} catch (Exception $e) {
user_error($e->getMessage(), E_USER_WARNING);
$map = [];
Expand Down
4 changes: 2 additions & 2 deletions src/PersistedQuery/JSONStringProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function getQueryMapping($schemaKey = 'default')
}

$mapping = $mappingWithKey[$schemaKey];
$result = json_decode($mapping, true);
$result = json_decode($mapping ?? '', true);
if (!is_array($result)) {
return [];
}
Expand Down Expand Up @@ -87,7 +87,7 @@ public function setSchemaMapping(array $mapping)
'setSchemaMapping accepts an array of schema keys to JSON strings'
);
}
if (json_decode($queryMap) === null) {
if (json_decode($queryMap ?? '') === null) {
throw new InvalidArgumentException(
'setSchemaMapping passed an invalid string of JSON. Got error: ' . json_last_error()
);
Expand Down
18 changes: 9 additions & 9 deletions src/QueryFilter/DataObjectQueryFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public function addDefaultFilters($field)
*/
public function addAllFilters()
{
$fields = array_keys($this->getDataObjectInstance()->searchableFields());
$fields = array_keys($this->getDataObjectInstance()->searchableFields() ?? []);
foreach ($fields as $fieldName) {
$this->addDefaultFilters($fieldName);
}
Expand Down Expand Up @@ -289,7 +289,7 @@ public function getFiltersForField($fieldName)
*/
public function getFilterIdentifiersForField($fieldName)
{
return array_keys($this->getFiltersForField($fieldName));
return array_keys($this->getFiltersForField($fieldName) ?? []);
}


Expand All @@ -316,7 +316,7 @@ public function isFieldFiltered($fieldName)
public function fieldHasFilter($fieldName, $id)
{
if ($this->isFieldFiltered($fieldName)) {
return in_array($id, $this->getFilterIdentifiersForField($fieldName));
return in_array($id, $this->getFilterIdentifiersForField($fieldName) ?? []);
}

return false;
Expand Down Expand Up @@ -379,7 +379,7 @@ public function applyConfig(array $config)
protected function getFieldFilters(array $filters)
{
foreach ($filters as $key => $val) {
$pos = strrpos($key, self::SEPARATOR);
$pos = strrpos($key ?? '', self::SEPARATOR ?? '');
// falsy is okay here because a leading __ is invalid.
if (!$pos) {
throw new InvalidArgumentException(sprintf(
Expand All @@ -388,12 +388,12 @@ protected function getFieldFilters(array $filters)
self::SEPARATOR
));
}
$parts = explode(self::SEPARATOR, $key);
$parts = explode(self::SEPARATOR ?? '', $key ?? '');
$filterIdentifier = array_pop($parts);
// If the field segment contained __, that implies relationship (dot notation)
$field = implode('.', $parts);
// The Field key is written with self::SEPARATOR
$fieldName = implode(self::SEPARATOR, $parts);
$fieldName = implode(self::SEPARATOR ?? '', $parts);
$filter = $this->getFieldFilterByIdentifier($fieldName, $filterIdentifier);
if (!$filter instanceof FieldFilterInterface) {
$filter = $this->getFilterRegistry()->getFilterByIdentifier($filterIdentifier);
Expand All @@ -417,11 +417,11 @@ protected function getFieldFilters(array $filters)
protected function getDBField($field)
{
$dbField = null;
if (stristr($field, self::SEPARATOR) !== false) {
$relationNames = explode(self::SEPARATOR, $field);
if (stristr($field ?? '', self::SEPARATOR ?? '') !== false) {
$relationNames = explode(self::SEPARATOR ?? '', $field ?? '');
$relationField = array_pop($relationNames);
// reverse array so we can use the faster array_pop
$relationNames = array_reverse($relationNames);
$relationNames = array_reverse($relationNames ?? []);
// initialize current class
$class = get_class($this->getDataObjectInstance());
do {
Expand Down
2 changes: 1 addition & 1 deletion src/QueryFilter/FieldFilterRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function addFilter(FieldFilterInterface $filter, $identifier = null)
));
}
$id = $identifier ?: $filter->getIdentifier();
if (!preg_match('/^[A-Za-z0-9_]+$/', $id)) {
if (!preg_match('/^[A-Za-z0-9_]+$/', $id ?? '')) {
throw new InvalidArgumentException(sprintf(
'Filter %s has an invalid identifier. Only alphanumeric characters and underscores allowed.',
get_class($filter)
Expand Down
4 changes: 2 additions & 2 deletions src/Scaffolding/Scaffolders/CRUD/Create.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function getName()
return $name;
}

return 'create' . ucfirst($this->getTypeName());
return 'create' . ucfirst($this->getTypeName() ?? '');
}

/**
Expand Down Expand Up @@ -126,7 +126,7 @@ public function resolve($object, array $args, $context, ResolveInfo $info)

// Extension points that return false should kill the create
$results = $this->extend('augmentMutation', $newObject, $args, $context, $info);
if (in_array(false, $results, true)) {
if (in_array(false, $results ?? [], true)) {
return null;
}

Expand Down
Loading

0 comments on commit eced2e2

Please sign in to comment.