How to Use Matchers to Enable the Profiler Conditionally
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.2 (the current stable version).
Caution
The possibility to use a matcher to enable the profiler conditionally is deprecated since Symfony 3.4 and will be removed in 4.0.
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\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
use Symfony\Component\Security\Core\Security;
class SuperAdminMatcher implements RequestMatcherInterface
{
protected $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function matches(Request $request)
{
return $this->security->isGranted('ROLE_SUPER_ADMIN');
}
}
Then, you'll need to make sure your class is defined as a service. If you're using the default services.yml configuration, you don't need to do anything!
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: AppBundle\Profiler\SuperAdminMatcher