Replaced in_array by contains

This commit is contained in:
Alejandro Celaya 2018-10-05 18:52:42 +02:00
parent ebf2e459e8
commit e55dbef2fc
6 changed files with 45 additions and 27 deletions

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Common;
use function getenv;
use function in_array;
use function strtolower;
use function trim;
@ -43,5 +44,5 @@ function env($key, $default = null)
function contains($needle, array $haystack)
{
return \in_array($needle, $haystack, true);
return in_array($needle, $haystack, true);
}

View File

@ -6,15 +6,17 @@ namespace Shlinkio\Shlink\Common\Factory;
use Doctrine\Common\Cache;
use Interop\Container\ContainerInterface;
use Interop\Container\Exception\ContainerException;
use Shlinkio\Shlink\Common;
use Memcached;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\Exception\ServiceNotFoundException;
use Zend\ServiceManager\Factory\FactoryInterface;
use function Shlinkio\Shlink\Common\contains;
use function Shlinkio\Shlink\Common\env;
class CacheFactory implements FactoryInterface
{
const VALID_CACHE_ADAPTERS = [
private const VALID_CACHE_ADAPTERS = [
Cache\ApcuCache::class,
Cache\ArrayCache::class,
Cache\FilesystemCache::class,
@ -51,14 +53,12 @@ class CacheFactory implements FactoryInterface
{
// Try to get the adapter from config
$config = $container->get('config');
if (isset($config['cache'], $config['cache']['adapter'])
&& in_array($config['cache']['adapter'], self::VALID_CACHE_ADAPTERS)
) {
if (isset($config['cache']['adapter']) && contains($config['cache']['adapter'], self::VALID_CACHE_ADAPTERS)) {
return $this->resolveCacheAdapter($config['cache']);
}
// If the adapter has not been set in config, create one based on environment
return Common\env('APP_ENV', 'pro') === 'pro' ? new Cache\ApcuCache() : new Cache\ArrayCache();
return env('APP_ENV', 'pro') === 'pro' ? new Cache\ApcuCache() : new Cache\ArrayCache();
}
/**
@ -75,8 +75,8 @@ class CacheFactory implements FactoryInterface
case Cache\PhpFileCache::class:
return new $cacheConfig['adapter']($cacheConfig['options']['dir']);
case Cache\MemcachedCache::class:
$memcached = new \Memcached();
$servers = isset($cacheConfig['options']['servers']) ? $cacheConfig['options']['servers'] : [];
$memcached = new Memcached();
$servers = $cacheConfig['options']['servers'] ?? [];
foreach ($servers as $server) {
if (! isset($server['host'])) {

View File

@ -7,6 +7,11 @@ use Cake\Chronos\Chronos;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use function array_column;
use function array_key_exists;
use function is_array;
use function key;
use function Shlinkio\Shlink\Common\contains;
class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryInterface
{
@ -55,19 +60,19 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI
'shortCode' => 'shortCode',
'dateCreated' => 'dateCreated',
];
$fieldName = \is_array($orderBy) ? \key($orderBy) : $orderBy;
$order = \is_array($orderBy) ? $orderBy[$fieldName] : 'ASC';
$fieldName = is_array($orderBy) ? key($orderBy) : $orderBy;
$order = is_array($orderBy) ? $orderBy[$fieldName] : 'ASC';
if (\in_array($fieldName, ['visits', 'visitsCount', 'visitCount'], true)) {
if (contains($fieldName, ['visits', 'visitsCount', 'visitCount'])) {
$qb->addSelect('COUNT(DISTINCT v) AS totalVisits')
->leftJoin('s.visits', 'v')
->groupBy('s')
->orderBy('totalVisits', $order);
return \array_column($qb->getQuery()->getResult(), 0);
return array_column($qb->getQuery()->getResult(), 0);
}
if (\array_key_exists($fieldName, $fieldNameMap)) {
if (array_key_exists($fieldName, $fieldNameMap)) {
$qb->orderBy('s.' . $fieldNameMap[$fieldName], $order);
}
return $qb->getQuery()->getResult();

View File

@ -9,6 +9,9 @@ use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response;
use Zend\Expressive\Template\TemplateRendererInterface;
use function array_shift;
use function explode;
use function Shlinkio\Shlink\Common\contains;
class NotFoundHandler implements RequestHandlerInterface
{
@ -39,12 +42,12 @@ class NotFoundHandler implements RequestHandlerInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
$accepts = \explode(',', $request->getHeaderLine('Accept'));
$accept = \array_shift($accepts);
$accepts = explode(',', $request->getHeaderLine('Accept'));
$accept = array_shift($accepts);
$status = StatusCodeInterface::STATUS_NOT_FOUND;
// If the first accepted type is json, return a json response
if (\in_array($accept, ['application/json', 'text/json', 'application/x-json'], true)) {
if (contains($accept, ['application/json', 'text/json', 'application/x-json'])) {
return new Response\JsonResponse([
'error' => 'NOT_FOUND',
'message' => 'Not found',

View File

@ -21,7 +21,7 @@ use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Router\RouteResult;
use Zend\I18n\Translator\TranslatorInterface;
use function implode;
use function in_array;
use function Shlinkio\Shlink\Common\contains;
use function sprintf;
class AuthenticationMiddleware implements MiddlewareInterface, StatusCodeInterface, RequestMethodInterface
@ -72,7 +72,7 @@ class AuthenticationMiddleware implements MiddlewareInterface, StatusCodeInterfa
if ($routeResult === null
|| $routeResult->isFailure()
|| $request->getMethod() === self::METHOD_OPTIONS
|| in_array($routeResult->getMatchedRouteName(), $this->routesWhitelist, true)
|| contains($routeResult->getMatchedRouteName(), $this->routesWhitelist)
) {
return $handler->handle($request);
}

View File

@ -9,6 +9,15 @@ use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Shlinkio\Shlink\Rest\Exception\RuntimeException;
use function array_shift;
use function explode;
use function json_decode;
use function json_last_error;
use function json_last_error_msg;
use function parse_str;
use function Shlinkio\Shlink\Common\contains;
use function sprintf;
use function trim;
class BodyParserMiddleware implements MiddlewareInterface, RequestMethodInterface
{
@ -27,17 +36,17 @@ class BodyParserMiddleware implements MiddlewareInterface, RequestMethodInterfac
$currentParams = $request->getParsedBody();
// In requests that do not allow body or if the body has already been parsed, continue to next middleware
if (! empty($currentParams) || \in_array($method, [
if (! empty($currentParams) || contains($method, [
self::METHOD_GET,
self::METHOD_HEAD,
self::METHOD_OPTIONS,
], true)) {
])) {
return $handler->handle($request);
}
// If the accepted content is JSON, try to parse the body from JSON
$contentType = $this->getRequestContentType($request);
if (\in_array($contentType, ['application/json', 'text/json', 'application/x-json'], true)) {
if (contains($contentType, ['application/json', 'text/json', 'application/x-json'])) {
return $handler->handle($this->parseFromJson($request));
}
@ -51,8 +60,8 @@ class BodyParserMiddleware implements MiddlewareInterface, RequestMethodInterfac
private function getRequestContentType(Request $request): string
{
$contentType = $request->getHeaderLine('Content-type');
$contentTypes = \explode(';', $contentType);
return \trim(\array_shift($contentTypes));
$contentTypes = explode(';', $contentType);
return trim(array_shift($contentTypes));
}
/**
@ -67,9 +76,9 @@ class BodyParserMiddleware implements MiddlewareInterface, RequestMethodInterfac
return $request;
}
$parsedJson = \json_decode($rawBody, true);
if (\json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException(\sprintf('Error when parsing JSON request body: %s', \json_last_error_msg()));
$parsedJson = json_decode($rawBody, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException(sprintf('Error when parsing JSON request body: %s', json_last_error_msg()));
}
return $request->withParsedBody($parsedJson);