Skip to content

Instantly share code, notes, and snippets.

@GromNaN
Last active November 24, 2022 12:06
Show Gist options
  • Save GromNaN/3ab352cc6bc348b8405e98006fcc2754 to your computer and use it in GitHub Desktop.
Save GromNaN/3ab352cc6bc348b8405e98006fcc2754 to your computer and use it in GitHub Desktop.
RequestMatcherFactory for Symfony 6.2+, compatible with older versions.
<?php
use Symfony\Component\HttpFoundation\ChainRequestMatcher;
use Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
class RequestMatcherFactory
{
public function getRequestMatcher(array $config): RequestMatcherInterface
{
// Supports Symfony < 6.2
if (!class_exists(ChainRequestMatcher::class)) {
return new RequestMatcher(
$config['path'] ?? null,
$config['host'] ?? null,
$config['methods'] ?? null,
$config['ips'] ?? null,
$config['attributes'] ?? [],
$config['schemes'] ?? null,
$config['port'] ?? null,
);
}
$matchers = [];
if (isset($config['host'])) {
$matchers[] = new RequestMatcher\HostRequestMatcher($config['host']);
}
if (isset($config['path'])) {
$matchers[] = new RequestMatcher\PathRequestMatcher($config['path']);
}
if (isset($config['methods'])) {
$matchers[] = new RequestMatcher\MethodRequestMatcher($config['methods']);
}
if (isset($config['ips'])) {
$matchers[] = new RequestMatcher\IpsRequestMatcher($config['ip']);
}
if (isset($config['attributes'])) {
$matchers[] = new RequestMatcher\AttributesRequestMatcher($config['attributes']);
}
if (isset($config['schemes'])) {
$matchers[] = new RequestMatcher\SchemeRequestMatcher($config['schemes']);
}
if (isset($config['port'])) {
$matchers[] = new RequestMatcher\PortRequestMatcher($config['port']);
}
return new ChainRequestMatcher($matchers);
}
}
@GromNaN
Copy link
Author

GromNaN commented Nov 24, 2022

Symfony\Component\HttpFoundation\RequestMatcher is deprecated since Symfony 6.2: symfony/symfony#47595

Here is a factory compatible with older and newer versions of Symfony.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment