Symfony Route Doesn't Show in debug:router - symfony

I can't for the life of me get this route to work:
/***
* #Route("/load_base_data/{projectId}", name="load_base_data", methods={"GET"})
* #return Response
*/
public function loadBaseMeasures(int $projectId, DataLoadService $dataLoadService, ApiService $apiService)
{
$response = $apiService->initResponse();
$dataLoadService->generateFiles($projectId);
return new JsonResponse($response);
}
I've tried php bin/console debug:router and it doesn't show up on the list.
I've tried php bin/console cache:clear
This is the only route I'm having trouble with.

Cerad was right, the problem was the /***. Changed to /** and it worked. Thanks!

Related

PhpStorm Symfony routes missing

I have a rather large Symfony 4.4 project that I recently reopened. Going through the code with PhpStorm 2020.3, adding some new functionality and code cleanup.
I get to a couple of Controllers and I'm getting a "Missing Route" error in PhpStorm. However, the routes do exist when I run php bin/console debug:router.
Is there a cache that I haven't cleared to cause PhpStorm to rescan routes?
Output from: php bin/console debug:router
admin_deviceprofile_index GET ANY ANY /admin/deviceprofile/
admin_deviceprofile_show GET ANY ANY /admin/deviceprofile/{deviceprofile_id}/show
admin_deviceprofile_create GET|POST ANY ANY /admin/deviceprofile/create
admin_deviceprofile_edit GET|POST ANY ANY /admin/deviceprofile/{deviceprofile_id}/edit
admin_deviceprofile_delete DELETE ANY ANY /admin/deviceprofile/{deviceprofile_id}/delete
My snippet of the Controller ...
/**
* #Route("/admin/deviceprofile",
* name="admin_deviceprofile_")
*/
class DeviceProfileController extends AbstractController
{
/**
* Lists all Device Profiles.
* #Route("/",
* name="index",
* methods={"GET"})
* #param Request $request
* #return Response
*/
public function index(Request $request): Response
{ ... }
/**
* Creates a new Device Profile entity.
* #Route("/create",
* name="create",
* methods={"GET", "POST"})
* #param Request $request
* #return Response
*/
public function create(Request $request): Response
{
$profile = new DeviceProfile();
$formProfile = $this->createForm(DeviceProfileType::class, $profile);
$formProfile->handleRequest($request);
if ($formProfile->isSubmitted() && $formProfile->isValid()) {
...
return $this->redirectToRoute('admin_deviceprofile_index');
}
return $this->render(...);
}
}
PhpStorm claims the 'admin_deviceprofile_index' is Missing. However, it is not. Also, this same pattern of having a route for the controller is used elsewhere, yet those routes are fine, the problem appears in just a couple of Controllers.
Also, through debugging this 'problem', I moved the controller route partials to the functions themselves, and PhpStorm still did not see the routes properly.
I have also ran php bin/console cache:clear and have done the PhpStorm: File > Invalidate Caches / Restart to no avail.
Anything I could try to clear this up? I loathe seeing "errors" in the code inspection.
Figured out that if you have a PhpStorm #noinspection tag block and a class-level docblock, it will conflict causing the erroneous "Missing Route" message.
Github issue here

Symfony2: How do I clear all of Symfony's (and all 3rd party plugins) cache in 1 command?

so I've been testing Doctrine queries and other Symfony code and I have to run several commands just to clear Doctrine/Symfony caches. I was searching for the net and came across another command to clear Assetic assets/etc.
From what I've read
php app/console cache:clear
will only clear Symfony cache. it won't include Doctrine and perhaps more.
I know I can create a bash script to clear all my caches but this obviously means I know all the "clear cache" commands. I only found out about the Assetic clear cache/assets by accident. What about those I don't know?
So is there 1 "clear cache" command that can do it for me? This will have to include Symfony/Doctrine/Assetic/Twig and whatever plugins I have installed.
Thanks a lot
What you are looking for is highly dependent on the developer of the bundle that uses the cache. Not even doctrine, that comes with the standard version of symfony has its cache clear command integrated. But what you can do is extend the default symfony command with a listener that runs all the cache clear command you want like this:
<?php
namespace DefaultBundle\Event\Listener;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Process\Process;
class CacheClearListener implements CacheClearerInterface
{
private $environment;
/**
* #return array
*/
private static function getCommands()
{
return array(
'php ./app/console doctrine:cache:clear-metadata --no-debug --flush',
'php ./app/console doctrine:cache:clear-query --no-debug --flush',
'php ./app/console doctrine:cache:clear-result --no-debug --flush'
);
}
public function clear($cacheDir)
{
$output = new ConsoleOutput();
$output->writeln('');
$output->writeln('<info>Clearing Doctrine cache</info>');
foreach (self::getCommands() as $command) {
$command .= ' --env='.$this->environment;
$success = $this->executeCommand($command, $output);
if (!$success) {
$output->writeln(sprintf('<info>An error occurs when running: %s!</info>', $command));
exit(1);
}
}
}
/**
* #param string $command
* #param ConsoleOutput $output
*
* #return bool
*/
private function executeCommand($command, ConsoleOutput $output)
{
$p = new Process($command);
$p->setTimeout(null);
$p->run(
function ($type, $data) use ($output) {
$output->write($data, false, OutputInterface::OUTPUT_RAW);
}
);
if (!$p->isSuccessful()) {
return false;
}
$output->writeln('');
return true;
}
/**
* #param Kernel $kernel
*/
public function setKernel(Kernel $kernel)
{
$this->environment = $kernel->getEnvironment();
}
}
Register the listener like this:
<service id="cache_clear_listener" class="DefaultBundle\Event\Listener\CacheClearListener">
<call method="setKernel">
<argument type="service" id="kernel"/>
</call>
<tag name="kernel.cache_clearer" priority="254" />
</service>
And that is all. Now all you need to do is keep adding your new cache clear command to the getCommands() method. In order to find this commands you can run something like
php app/console | grep cache
to see all available commands that contain the word "cache" in them
After your listener is set, every time you run php app/console cache:clear it will trigger all the command that you listed in the getCommands() method of your listener.
Hope this helps,
Alexandru

I cant generate URL with router service when JMSI18nRoutingBundle is in use - Symfony 2.7

$this->getServiceContainer()->get('router')->getGenerator()->generate('ting_user_reset_password', array(), UrlGeneratorInterface::ABSOLUTE_URL);
When I try to generate a URL with the router service using the route name ting_user_reset_password an exception occurs because with JMSI18nRoutingBundle the route name doesnt exist.
/**
* #Route("/reset-password", name="ting_user_reset_password")
* #Template()
*/
public function resetPasswordAction(){
}
JMSI18nRoutingBundle create the following routes:
us_US_RG_ting_user_reset_password
de_DE_RG_ting_user_reset_password
es_ES_RG_ting_user_reset_password
...
If you disable JMSI18nRoutingBundle for this route, the router service works fine:
/**
* #Route("/reset-password", name="ting_user_reset_password", options={"i18n" = false})
* #Template()
*/
public function resetPasswordAction(){
}
How can I get the URL using the router service by specifying the name of the route?
Thank you.
I have made many tests and the correct way to generate urls when the bundle "JMSI18nRoutingBundle" is used, is as follows :
$this->getServiceContainer()->get('router')->generate('ting_user_reset_password', array(), UrlGeneratorInterface::ABSOLUTE_URL);
without getGenerator()->
thats working fine to me.

Doctrine load fixtures --no-interaction flag is not working when running in a Symfony command

The --no-interaction flag on the doctrine:fixtures:load command is not working running within a Symfony command. It is working however via the terminal. I'm I calling it correctly?
When I run this from a bundle:
/**
* Loads the fixtures
* #param \Symfony\Component\Console\Output\OutputInterface $oOutput
* #return \Symfony\Component\Console\Output\OutputInterface
*/
protected function loadFixturesCommand($oOutput) {
$oOutput->writeln('<fg=white>Attempting to load fixtures</fg=white>');
$updateCommand = $this->getApplication()->find('doctrine:fixtures:load');
$updateArguments = array(
'command' => 'doctrine:fixtures:load',
'--no-interaction' => true,
);
$updateInput = new ArrayInput($updateArguments);
$updateCommand->run($updateInput, $oOutput);
try {
$updateCommand->run($updateInput, $oOutput);
} catch (ContextErrorException $e) {
//..
}
return $this;
}
I get prompted to load the fixtures
But running this:
php app/console doctrine:fixtures:load --no-interaction
Doesn't prompt me.
What am I doing wrong?
I've found the solution.
Simply call:
$input->setInteractive(false);
Like so:
protected function loadFixturesCommand($oOutput) {
$oOutput->writeln('<fg=white>Attempting to load fixtures</fg=white>');
$updateCommand = $this->getApplication()->find('doctrine:fixtures:load');
$updateArguments = array(
'command' => 'doctrine:fixtures:load'
);
$updateInput = new ArrayInput($updateArguments);
$updateInput->setInteractive(false);
$updateCommand->run($updateInput, $oOutput);
try {
$updateCommand->run($updateInput, $oOutput);
} catch (ContextErrorException $e) {
//..
}
return $this;
}
If you make a drop from your database you could also use this command I think, to be confirmed.
By default Doctrine Data Fixtures uses DELETE statements to drop the existing rows from the database.
If you want to use a TRUNCATE statement instead you can use the --purge-with-truncate flag:
php bin/console doctrine:fixtures:load --purge-with-truncate
You can use --append param to suppress interaction.
i.e. doctrine:fixtures:load --append

Issue when trying to reload the fixtures

When I try to reload my fixtures using
php app/console doctrine:fixtures:load
I'm getting this error:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
update a parent row: a foreign key constraint fails (foo_db.Book, CONSTRAINT FK_C29271DD816C6140 FOREIGN KEY (author_id) REFERENCES Author (id))
The error is showed when the status "> purging database" is showed.
This is my code:
class Book{
...
/**
* #ORM\ManyToOne(targetEntity="Author", inversedBy="books")
*/
private $author;
...
}
class Author{
...
/**
* #ORM\OneToMany(targetEntity="Book", mappedBy="author")
*/
private $books;
}
More: my boss has the same code and it doesn't have that error.
Any idea?
sf 2.0.1 (just updated)/ubuntu 10.10.
If I'm guessing correctly, you are using a MySQL database. If yes, then you are facing a bug/problem with the current version of the doctrine-fixtures library for Doctrine2. The problem is that they are using the TRUNCATE command to purge the current database values but this command has problem deleting foreign associations in MySQL.
See this issue and this one on the GitHub repository of the library for more information and workarounds.
In my particular case, I run this command from a script, so to make the command work correctly, I do:
php app/console doctrine:database:drop --force
php app/console doctrine:database:create
php app/console doctrine:schema:update --force
php app/console doctrine:fixtures:load --append
This way, the purging is done by the drop command and appending has the same effect as not appending since the database is empty when the fixtures are loaded.
I must admit I don't know why your boss doesn't have the problem, maybe there is no book associated with an author in his database.
Hope this help.
Regards,
Matt
I've created a simple Event Subscriber class for Symfony 4. All you need to fix the self-referencing foreign keys issue is to add the below class somewhere to your Symfony 4 project.
This subscriber fires before each Symfony CLI command. In case if the command's name is doctrine:fixtures:load, it performs database purge, but doing SET FOREIGN_KEY_CHECKS = 0 first.
This solves the issue without any other modification.
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ConsoleCommandEventSubscriber implements EventSubscriberInterface
{
/**
* #var EntityManagerInterface
*/
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents()
{
return [
ConsoleEvents::COMMAND => 'onCommand',
];
}
public function onCommand(ConsoleCommandEvent $event)
{
if ($event->getCommand()->getName() === 'doctrine:fixtures:load') {
$this->runCustomTruncate();
}
}
private function runCustomTruncate()
{
$connection = $this->entityManager->getConnection();
$connection->exec('SET FOREIGN_KEY_CHECKS = 0');
$purger = new ORMPurger($this->entityManager);
$purger->setPurgeMode(ORMPurger::PURGE_MODE_DELETE);
$purger->purge();
$connection->exec('SET FOREIGN_KEY_CHECKS = 1');
}
}
Add to your composer.json new section script
"scripts": {
"load-fixtures": [
"bin/console doctrine:database:drop --if-exists --force",
"bin/console doctrine:database:create",
"bin/console doctrine:mi:m",
"bin/console doctrine:fixtures:load"
]
}
Then you can run composer install && composer load-fixtures

Resources