Get list of routes of controller in Symfony? - php

I am able to get list of all routes for controller as mentioned on https://stackoverflow.com/a/15950365/3900206 by #Qoop (Thanks to him for sharing).
And, it shows different routes as configured when run in dev and prod environment. But, I only want to list routes that appears in prod environment in dev environment also.
How can I list only those routes which are configured for prod environment from any environment (dev or prod or test)?
Is it possible as we can list environment specific routes from console as:
php app/console router:debug --env=prod
Update (Improving question):
I am looking for a way to list out routes of production environment from controller in any environment (dev, test or prod)

I don't understand you have the command already, it can take --env option you can use it for dev/prod or test
php app/console router:debug --env=prod/test/dev
Edit2 :
You can create your own AppKernel with the environment that you choose because there is no way that i am aware off that you can set the environment on the current kernel which doesnt make sens.
instantiate a kernel prod for example and get the router service from its container.
for more info on instantiating new environment http://symfony.com/fr/doc/current/cookbook/configuration/environments.html
$kernel = new \AppKernel('prod', true);
$kernel->boot();
/** #var $router \Symfony\Component\Routing\Router */
$router = $kernel->getContainer()->get('router');
$router->setOption('debug', true);
/** #var $collection \Symfony\Component\Routing\RouteCollection */
$collection = $router->getRouteCollection();
$allRoutes = $collection->all();

Related

How to set up a staging environment based on a symlink to prod configuration, without showing debug information?

I would like to setup a staging environment with the same configuration as the prod environment.
According to the docs, I proceed as follow:
I create a staging symlink that points on prod
configure the env in .env: APP_ENV=staging
clear the cache: php bin/console cache:clear
ask for an URL that does not exist to trigger a 404 error: http://localhost:8080/an-url-that-does-not-exists
When the APP_ENV=prod, my custom error page is render properly, but when APP_ENV=staging, the debug message NotFoundHttpException is rendered?
The profiler is not displayed.
What am I missing?
tldr;
Crate an .env.staging file and use it to set APP_DEBUG to 0. Debug mode and environment are set independently.
By default, unless you set it explicitly debug mode (APP_DEBUG) is set from the environment automagically.
This happens in the following steps:
In your front-controller (index.php, usually) you would find this line:
(new Dotenv())->bootEnv(dirname(__DIR__).'/.env');
And on DotEnv::bootEnv() you'll find this:
$debug = $_SERVER[$k] ?? !\in_array($_SERVER[$this->envKey], $this->prodEnvs, true);
This will compare your APP_ENV with an array of "environments" that DotEnv, considers "production-like". By default, this array includes only prod.
You could modify the instance of the DotEnv by calling setProdEnvs():
(new Dotenv())
->setProdEnvs(['prod', 'staging'])
->bootEnv(dirname(__DIR__).'/.env');
... but generally simply disabling debug mode on your .env file would be enough.

I can't turn off debug bar in Laravel on production

I have set
'enabled' = false
in both package and in config/debugbar.php
I cleared cache with
php artisan cache:clear
but I still see it on production environment.
I accidently commited
'enabled' = false
by accident and can't turn it off. I even rolled back commits, but that doesn't help. Any ideas?
#edit the .env has also debug set to false
#edit2 also when I got ot /login route on new browser (or private mode) I don't see the bar, but when I refresh this page, it is there again
Go To .env And Set
DEBUGBAR_ENABLED=false
OR
APP_DEBUG=false
It is not a matter of debugbar, it is general problem with .env. You can change your APP_NAME to see that it is not changing anything.
To apply your new config changes including .env changes you need to run artisan command in your project folder:
php artisan config:cache
Did u try changing it in the .env file?
Look for the value APP_DEBUG in the .env file and set it false.
Out of the box, .env has it set to true.
Solution for 5.5 and above
Install the package with:
composer require barryvdh/laravel-debugbar:dev-master
Because of the package auto-discovery feature, you don't need to add package's service provider to the providers list in config/app.php and Debugbar will only be loaded in the development environment.
Solution for 5.4 and below
Put this code to the AppServiceProvider#register:
if ($this->app->isLocal()) {
$this->app->register('Barryvdh\Debugbar\ServiceProvider');
}
Don't forget to remove Laravel Debugbar line from config/app.php providers section.
After doing this, Laravel Debugbar will only be loaded in a local environment.
if you are on 5.4 you can do under AppServiceProvider as follows:
public function register()
{
/*
* Sets third party service providers that are only needed on local/testing environments
*/
if ($this->app->environment() != 'production') {
/**
* Loader for registering facades.
*/
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
/*
* Load third party local aliases
*/
$loader->alias('Debugbar', \Barryvdh\Debugbar\Facade::class);
}
}
if you want full control under 5.5 you can do in the same AppServiceProvider:
public function register()
{
/*
* Sets third party service providers that are only needed on local/testing environments
*/
if ($this->app->environment() != 'production') {
/**
* Loader for registering facades.
*/
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
/*
* Load third party local providers
*/
$this->app->register(\Barryvdh\Debugbar\ServiceProvider::class);
/*
* Load third party local aliases
*/
$loader->alias('Debugbar', \Barryvdh\Debugbar\Facade::class);
}
}
and under composer.json in the extra:
"extra": {
"laravel": {
"dont-discover": [
"barryvdh/laravel-debugbar"
]
}
},
Then you are good to go and enable and disable via .env, if it's different of production it will be enabled (local, testing, etc..) if it's on production it will be automatically disabled.
Hope it helps, good luck!

symfony2 CLI [Symfony\Component\Debug\Exception\ContextErrorException]

I'm having a problem whilst trying to create a command with Symfony2's Console component, in a full Symfony stack app.
If i try to pass my services in via DI, the command throws the following error when i try to run it:
[Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Trying to get property of non-object
If I create the command with ContainerAwareCommand and try to get my service with
$this->getContainer()->get('mtgu.api.card.list.response.data');
I get
[LogicException]
The container cannot be retrieved as the application instance is not yet set.
My service is defiantly being loaded, as its used in a front end controller. This problem gets stranger, as if I pass a repository service - I don't get this problem!
Is there some trick to setting up a service to be passible by this? Or have I messed up my configuration somehow?
Im "autoloading" all my services by doing this in my DI Extension rather than including them all through the the main services.yml. I thought this or the ordering of the yml includes maybe effecting it - but I have tried manually including everything but still no joy!
$finder = new Finder();
$finder->name('services.yml');
/**
* #var $file SplFileInfo
*/
foreach($finder->in(__DIR__.'/../') as $file) {
$loader = new Loader\YamlFileLoader($container, new FileLocator($file->getPath()));
$loader->load('services.yml');
}
Vendor/Bundle/Command/services.yml
services:
mtgu.command.slugify:
class: MightyStudios\MtguBundle\Command\SlugifyCommand
tags:
- { name: console.command }
arguments:
- #mtgu.api.card.list.response.data
I think this maybe just some config issue, but Google has failed me to find the answer! Has anyone else run into this problem and can they shed any light!?
Many thanks
A better structure would be to put your services files in the Resources/config directory of your bundle (See also all core bundles). However, that's aside.
The problem is described by the exception: The container cannot be retrieved as the application instance is not yet set. Which is thrown in the ContainerAwareCommand#getContainer() method when $this->application is null. The application is set in the first line of the Application#add() method.
This means that you call $this->getContainer() before you add the command to the application. Maybe you use it in your constructor?
If so, remove it and only use the container in Command#execute(), Command#interact() or Command#initialize().

Adding a custom Artisan command with Behat

I've registered a custom Artisan command:
Artisan::add(new MigrateAll);
The class resides in app/commands (default location)
However when I run Behat I get the error:
Class 'MigrateAll' not found
Artisan is called in Behat for setting up the DB:
/**
* #static
* #beforeSuite
*/
public static function setUpDb()
{
Artisan::call('migrate:install');
//...
}
Do I need to give it a namespace? (I could not find the correct way to call the Artisan::add command with a namespaced class)
This is somewhat related to your earlier question. Your Behat test suite runs in a separate process independently of your app and knows nothing about the configuration. This also applies to the autoloading in your bootstrap and the autoloading would be the most likely reason why classes don't get found. This should be easily fixed by using Composer to autoload your own sources and vendor packages (both in your app and in your test suite).
# composer.json
{
"require": {
"…": "…"
},
"autoload": {
"psr-0": {
"": "../src"
}
}
}
// Include composer's autoloader in your `setUp()` / bootstrap / index.php.
include __DIR__ . '../vendor/autoload.php';
Take that process separation as a rule and keep in mind that Laravel like any other framework requires a whole bunch of other configuration. Since you are trying to use the database component, your next issue will be with that, because it won't be configured in your test suite.
The best approach is to create separate bootstrap file for Behat, which would inherit most lines from your normal bootstrap, where you need to pass the necessary configuration and do this:
/**
* #static
* #beforeSuite
*/
public static function setUp()
{
include_once('bootstrap.php');
}
If you configured your behat environment with this tut (Laravel, BDD And You: Let’s Get Started), after you added a new command, you need to $ composer dump-autoload to make behat to know the command.

Laravel 4: loading Service Provider at runtime

On first thought, this may seem unnecessary, as we have defined providers in config/app.php to autoload any ServiceProvider, but it turns out there is a scenario where they will NOT be autoloaded:
When we run a job from Laravel Queue - it would seem my ServiceProvider in config are ignore completely, so DI failed with target ... is not instantiable.
Register my service providers at runtime in the job does work. e.g.
App::register('MyServiceProvider');
Is there a reason that Laravel did not autoload my ServiceProvider in such case?
PS: I opened an issue on github as well, as I am not if this is by design.
If you define your environments by URL, those environments will not be automatically recognised from the command line - I've run into this issue myself when trying to run migrations/seeds.
You can define environments in any way you like since the environment definition accepts a closure but 'out of the box' you can return a regex that matches wither a machine name or a url. examples here - environment config.
One solution would be to define your service providers in the app.php at the route of your config (this is the default config and will be used if no other environments are recognised from the command line) OR if you need different settings for different environments you could try defining your environments by machine name - this is the hostname of your machine - on a unix box you can see what this is with echo $HOSTNAME on the command line.
Another solution from OP
As the OP has discovered, artisan accepts --env flag on just about every command which allows you to force an environment, so you can call php artisan queue:work --env=local to force it to use the local config when working queues.
Hope this helps

Categories