How to Use Matchers to Enable the Profiler Conditionally
Warning: You are browsing the documentation for Symfony 2.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.1 (the current stable version).
The Symfony profiler is only activated in the development environment to not hurt your application performance. However, sometimes it may be useful to conditionally enable the profiler in the production environment to assist you in debugging issues. This behavior is implemented with the Request Matchers.
Using the built-in Matcher
A request matcher is a class that checks whether a given Request
instance
matches a set of conditions. Symfony provides a
built-in matcher
which matches paths and IPs. For example, if you want to only show the profiler
when accessing the page with the 168.0.0.1
IP, then you can use this
configuration:
1 2 3 4 5 6
# app/config/config.yml
framework:
# ...
profiler:
matcher:
ip: 168.0.0.1
You can also set a path
option to define the path on which the profiler
should be enabled. For instance, setting it to ^/admin/
will enable the
profiler only for the URLs which start with /admin/
.
Creating a Custom Matcher
Leveraging the concept of Request Matchers you can define a custom matcher to
enable the profiler conditionally in your application. To do so, create a class
which implements
RequestMatcherInterface. This
interface requires one method:
matches().
This method returns false
when the request doesn't match the conditions and
true
otherwise. Therefore, the custom matcher must return false
to
disable the profiler and true
to enable it.
Suppose that the profiler must be enabled whenever a user with a
ROLE_SUPER_ADMIN
is logged in. This is the only code needed for that custom
matcher:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// src/AppBundle/Profiler/SuperAdminMatcher.php
namespace AppBundle\Profiler;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
class SuperAdminMatcher implements RequestMatcherInterface
{
protected $authorizationChecker;
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}
public function matches(Request $request)
{
return $this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN');
}
}
Then, configure a new service and set it as private
because the application
won't use it directly:
1 2 3 4 5 6
# app/config/services.yml
services:
app.super_admin_matcher:
class: AppBundle\Profiler\SuperAdminMatcher
arguments: ['@security.authorization_checker']
public: false
Once the service is registered, the only thing left to do is configure the profiler to use this service as the matcher:
1 2 3 4 5 6
# app/config/config.yml
framework:
# ...
profiler:
matcher:
service: app.super_admin_matcher