Removed more functional-php usages

This commit is contained in:
Alejandro Celaya
2023-11-30 14:34:21 +01:00
parent 549c6605f0
commit bff4bd12ae
20 changed files with 156 additions and 91 deletions

View File

@@ -16,10 +16,10 @@ use PUGX\Shortid\Factory as ShortIdFactory;
use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\ShortUrl\Model\ShortUrlMode;
use function array_keys;
use function array_map;
use function array_reduce;
use function date_default_timezone_get;
use function Functional\reduce_left;
use function in_array;
use function is_array;
use function print_r;
@@ -95,10 +95,12 @@ function getNonEmptyOptionalValueFromInputFilter(InputFilter $inputFilter, strin
function arrayToString(array $array, int $indentSize = 4): string
{
$indent = str_repeat(' ', $indentSize);
$names = array_keys($array);
$index = 0;
return reduce_left($array, static function ($messages, string $name, $_, string $acc) use (&$index, $indent) {
return array_reduce($names, static function (string $acc, string $name) use (&$index, $indent, $array) {
$index++;
$messages = $array[$name];
return $acc . sprintf(
"%s%s'%s' => %s",
@@ -199,3 +201,33 @@ function flatten(array $multiArray): array
initial: [],
);
}
/**
* Checks if a callback returns true for at least one item in a collection.
* @param callable(mixed $value, string|number $key): bool $callback
*/
function some(iterable $collection, callable $callback): bool
{
foreach ($collection as $key => $value) {
if ($callback($value, $key)) {
return true;
}
}
return false;
}
/**
* Checks if a callback returns true for all item in a collection.
* @param callable(mixed $value, string|number $key): bool $callback
*/
function every(iterable $collection, callable $callback): bool
{
foreach ($collection as $key => $value) {
if (! $callback($value, $key)) {
return false;
}
}
return true;
}

View File

@@ -13,7 +13,6 @@ use Shlinkio\Shlink\Core\ErrorHandler\Model\NotFoundType;
use Shlinkio\Shlink\Core\Util\RedirectResponseHelperInterface;
use function Functional\compose;
use function Functional\id;
use function str_replace;
use function urlencode;
@@ -23,8 +22,8 @@ class NotFoundRedirectResolver implements NotFoundRedirectResolverInterface
private const ORIGINAL_PATH_PLACEHOLDER = '{ORIGINAL_PATH}';
public function __construct(
private RedirectResponseHelperInterface $redirectResponseHelper,
private LoggerInterface $logger,
private readonly RedirectResponseHelperInterface $redirectResponseHelper,
private readonly LoggerInterface $logger,
) {
}
@@ -73,7 +72,7 @@ class NotFoundRedirectResolver implements NotFoundRedirectResolverInterface
$replacePlaceholderForPattern(self::ORIGINAL_PATH_PLACEHOLDER, $path, $modifier),
);
$replacePlaceholdersInPath = compose(
$replacePlaceholders(id(...)),
$replacePlaceholders(static fn (mixed $v) => $v),
static fn (?string $path) => $path === null ? null : str_replace('//', '/', $path),
);
$replacePlaceholdersInQuery = $replacePlaceholders(urlencode(...));

View File

@@ -9,25 +9,34 @@ use Mezzio\Router\Route;
use Shlinkio\Shlink\Core\Action\RedirectAction;
use Shlinkio\Shlink\Core\Util\RedirectStatus;
use function array_values;
use function count;
use function Functional\partition;
use const Shlinkio\Shlink\DEFAULT_REDIRECT_STATUS_CODE;
/**
* Sets the appropriate allowed methods on the redirect route, based on the redirect status code that was configured.
* * For "legacy" status codes (301 and 302) the redirect URL will work only on GET method.
* * For other status codes (307 and 308) the redirect URL will work on any method.
*/
class ShortUrlMethodsProcessor
{
public function __invoke(array $config): array
{
[$redirectRoutes, $rest] = partition(
$config['routes'] ?? [],
static fn (array $route) => $route['name'] === RedirectAction::class,
);
if (count($redirectRoutes) === 0) {
$allRoutes = $config['routes'] ?? [];
$redirectRoute = null;
$rest = [];
// Get default route from routes array
foreach ($allRoutes as $route) {
if ($route['name'] === RedirectAction::class) {
$redirectRoute ??= $route;
} else {
$rest[] = $route;
}
}
if ($redirectRoute === null) {
return $config;
}
[$redirectRoute] = array_values($redirectRoutes);
$redirectStatus = RedirectStatus::tryFrom(
$config['redirects']['redirect_status_code'] ?? 0,
) ?? DEFAULT_REDIRECT_STATUS_CODE;

View File

@@ -15,8 +15,6 @@ use Shlinkio\Shlink\Rest\ApiKey\Role;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use function array_map;
use function Functional\first;
use function Functional\group;
class DomainService implements DomainServiceInterface
{
@@ -49,12 +47,19 @@ class DomainService implements DomainServiceInterface
{
/** @var DomainRepositoryInterface $repo */
$repo = $this->em->getRepository(Domain::class);
$groups = group(
$repo->findDomains($apiKey),
fn (Domain $domain) => $domain->authority === $this->defaultDomain ? 'default' : 'domains',
);
$allDomains = $repo->findDomains($apiKey);
$defaultDomain = null;
$restOfDomains = [];
return [first($groups['default'] ?? []), $groups['domains'] ?? []];
foreach ($allDomains as $domain) {
if ($domain->authority === $this->defaultDomain) {
$defaultDomain = $domain;
} else {
$restOfDomains[] = $domain;
}
}
return [$defaultDomain, $restOfDomains];
}
/**

View File

@@ -13,7 +13,7 @@ use Shlinkio\Shlink\Core\EventDispatcher\PublishingUpdatesGeneratorInterface;
use Shlinkio\Shlink\Core\Visit\Entity\Visit;
use Throwable;
use function Functional\each;
use function array_walk;
abstract class AbstractNotifyVisitListener extends AbstractAsyncListener
{
@@ -46,7 +46,7 @@ abstract class AbstractNotifyVisitListener extends AbstractAsyncListener
$updates = $this->determineUpdatesForVisit($visit);
try {
each($updates, fn (Update $update) => $this->publishingHelper->publishUpdate($update));
array_walk($updates, fn (Update $update) => $this->publishingHelper->publishUpdate($update));
} catch (Throwable $e) {
$this->logger->debug(
'Error while trying to notify {name} with new visit. {e}',

View File

@@ -6,7 +6,6 @@ namespace Shlinkio\Shlink\Core\ShortUrl\Model;
use Shlinkio\Shlink\Core\Model\DeviceType;
use function Functional\group;
use function trim;
final class DeviceLongUrlPair
@@ -25,27 +24,20 @@ final class DeviceLongUrlPair
* * The first one is a list of mapped instances for those entries in the map with non-null value
* * The second is a list of DeviceTypes which have been provided with value null
*
* @param array<string, string> $map
* @param array<string, string | null> $map
* @return array{array<string, self>, DeviceType[]}
*/
public static function fromMapToChangeSet(array $map): array
{
$toRemove = []; // TODO Use when group is removed
$toKeep = []; // TODO Use when group is removed
$typesWithNullUrl = group($map, static fn (?string $longUrl) => $longUrl === null ? 'remove' : 'keep');
$deviceTypesToRemove = [];
foreach ($typesWithNullUrl['remove'] ?? [] as $deviceType => $_) {
$deviceTypesToRemove[] = DeviceType::from($deviceType);
}
$pairsToKeep = [];
/**
* @var string $deviceType
* @var string $longUrl
*/
foreach ($typesWithNullUrl['keep'] ?? [] as $deviceType => $longUrl) {
$pairsToKeep[$deviceType] = self::fromRawTypeAndLongUrl($deviceType, $longUrl);
$deviceTypesToRemove = [];
foreach ($map as $deviceType => $longUrl) {
if ($longUrl === null) {
$deviceTypesToRemove[] = DeviceType::from($deviceType);
} else {
$pairsToKeep[$deviceType] = self::fromRawTypeAndLongUrl($deviceType, $longUrl);
}
}
return [$pairsToKeep, $deviceTypesToRemove];

View File

@@ -10,10 +10,10 @@ use Shlinkio\Shlink\Core\Model\DeviceType;
use function array_keys;
use function array_values;
use function Functional\every;
use function is_array;
use function Shlinkio\Shlink\Core\contains;
use function Shlinkio\Shlink\Core\enumValues;
use function Shlinkio\Shlink\Core\every;
class DeviceLongUrlsValidator extends AbstractValidator
{

View File

@@ -18,7 +18,7 @@ use Shlinkio\Shlink\Rest\ApiKey\Spec\WithApiKeySpecsEnsuringJoin;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use function array_map;
use function Functional\each;
use function array_walk;
use function Shlinkio\Shlink\Core\camelCaseToSnakeCase;
use const PHP_INT_MAX;
@@ -95,7 +95,8 @@ class TagRepository extends EntitySpecificationRepository implements TagReposito
$nonBotVisitsSubQb = $buildVisitsSubQb(true, 'non_bot_visits');
// Apply API key specification to all sub-queries
each([$tagsSubQb, $allVisitsSubQb, $nonBotVisitsSubQb], $applyApiKeyToNativeQb);
$queryBuilders = [$tagsSubQb, $allVisitsSubQb, $nonBotVisitsSubQb];
array_walk($queryBuilders, $applyApiKeyToNativeQb);
// A native query builder needs to be used here, because DQL and ORM query builders do not support
// sub-queries at "from" and "join" level.

View File

@@ -27,9 +27,8 @@ use Shlinkio\Shlink\Core\Visit\Model\Visitor;
use Shlinkio\Shlink\Core\Visit\Transformer\OrphanVisitDataTransformer;
use Throwable;
use function array_walk;
use function count;
use function Functional\each;
use function Functional\noop;
class NotifyVisitToRabbitMqTest extends TestCase
{
@@ -77,7 +76,7 @@ class NotifyVisitToRabbitMqTest extends TestCase
{
$visitId = '123';
$this->em->expects($this->once())->method('find')->with(Visit::class, $visitId)->willReturn($visit);
each($expectedChannels, function (string $method): void {
array_walk($expectedChannels, function (string $method): void {
$this->updatesGenerator->expects($this->once())->method($method)->with(
$this->isInstanceOf(Visit::class),
)->willReturn(Update::forTopicAndPayload('', []));
@@ -153,7 +152,7 @@ class NotifyVisitToRabbitMqTest extends TestCase
yield 'legacy non-orphan visit' => [
true,
$visit = Visit::forValidShortUrl(ShortUrl::withLongUrl('https://longUrl'), Visitor::emptyInstance()),
noop(...),
static fn () => null,
function (MockObject & PublishingHelperInterface $helper) use ($visit): void {
$helper->method('publishUpdate')->with(self::callback(function (Update $update) use ($visit): bool {
$payload = $update->payload;
@@ -170,7 +169,7 @@ class NotifyVisitToRabbitMqTest extends TestCase
yield 'legacy orphan visit' => [
true,
Visit::forBasePath(Visitor::emptyInstance()),
noop(...),
static fn () => null,
function (MockObject & PublishingHelperInterface $helper): void {
$helper->method('publishUpdate')->with(self::callback(function (Update $update): bool {
$payload = $update->payload;

View File

@@ -32,8 +32,8 @@ use stdClass;
use Symfony\Component\Console\Style\StyleInterface;
use function count;
use function Functional\some;
use function Shlinkio\Shlink\Core\contains;
use function Shlinkio\Shlink\Core\some;
use function sprintf;
use function str_contains;

View File

@@ -20,8 +20,8 @@ use Shlinkio\Shlink\Importer\Model\ImportedShlinkUrl;
use Shlinkio\Shlink\Importer\Sources\ImportSource;
use function array_map;
use function Functional\every;
use function range;
use function Shlinkio\Shlink\Core\every;
use function strlen;
use function strtolower;

View File

@@ -16,9 +16,6 @@ use Psr\Http\Server\RequestHandlerInterface;
use Shlinkio\Shlink\Core\Options\UrlShortenerOptions;
use Shlinkio\Shlink\Core\ShortUrl\Middleware\TrimTrailingSlashMiddleware;
use function Functional\compose;
use function Functional\const_function;
class TrimTrailingSlashMiddlewareTest extends TestCase
{
private MockObject & RequestHandlerInterface $requestHandler;
@@ -34,7 +31,10 @@ class TrimTrailingSlashMiddlewareTest extends TestCase
ServerRequestInterface $inputRequest,
callable $assertions,
): void {
$arg = compose($assertions, const_function(true));
$arg = static function (...$args) use ($assertions): bool {
$assertions(...$args);
return true;
};
$this->requestHandler->expects($this->once())->method('handle')->with($this->callback($arg))->willReturn(
new Response(),
);