How to see error $application->run($input, $output); - symfony

i create a controller to update database in symfony because i can't use command line
/**
* #Route("admin/database/update", name="adyax_database")
*/
public function refreshdatabaseRoutes()
{
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 300);
$kernel = $this->container->get('kernel');
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'doctrine:schema:update --force',
]);
$output = new BufferedOutput();
$application->run($input, $output);
return $this->redirectToRoute('homepage');
}
i think it don't work but no error given. How i can understand if some error is given ??

First of all, if you want to get command's result, you should use $output variable. You can get the output content with $output->fetch().
Anyway, you've done a mistake in your $input. In command array's element there should be only command's name, so it's just doctrine:schema:update. Any parameters should be passed as separate elements of this array. If the parameter doesn't take any value (like --force), simply set true as the value.
So in the end you should be fine with:
$input = new ArrayInput([
'command' => 'doctrine:schema:update',
'--force' => true,
]);

Related

Support PHP 8's attributes for my routes in custom Symfony framework

I've followed the Symfony Tutorial Series to create my own Symfony framework. Currently I have the following code to define my routes and add them to the UrlMatcher:
$request = Request::createFromGlobals();
$routes = include __DIR__.'/../src/app.php';
$context = new Routing\RequestContext();
$matcher = new Routing\Matcher\UrlMatcher($routes, $context);
Here's my app.php file for reference:
<?php
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing;
$routes = new Routing\RouteCollection();
$routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', [
'year' => null,
'_controller' => 'App\Controller\LeapYearController::index',
]));
return $routes;
What's the simplest way this can be modified to support PHP 8's attributes against the LeapYearController's actions for my routes instead of defining them in the app.php file?
It's been a while since I last looked at Symfony and a lot has changed in the framework aswell as in PHP itself and so far everything I have found is no longer supported.
I've managed to get the following working:
$loader = new AnnotationDirectoryLoader(
new FileLocator(),
new class() extends AnnotationClassLoader {
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, object $annot) {
$route->setDefault('_controller', $class->getName() . '::' . $method->getName());
}
}
);
$routes = $loader->load(__DIR__ . '/../src/App/Controller');
Alternatively this works using the Psr4DirectoryLoader introduced in version 6.2:
$loader = new DelegatingLoader(
new LoaderResolver([
new Psr4DirectoryLoader(
new FileLocator()
),
new class() extends AnnotationClassLoader {
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, object $annot) {
$route->setDefault('_controller', $class->getName() . '::' . $method->getName());
}
}
])
);
$routes = $loader->load(['path' => __DIR__ . '/../src/App/Controller', 'namespace' => 'App\Controller'], 'attribute');

swiftmail symfony duplicate check for error log / email before sending

I would like to run a duplicate content check just before firing off an email whcih uses swiftmailer inside my symph2 app to send me dev ERROR log entries.
this functionality sits right next to my error log to database function, where it too has a duplicate check, although that one is much easier, it uses sql.
for this one, i want to maintain the last mail sent body for atleast the next 10 emails sent, so that if my error log goes out of control, it wont keep firing me duplicate emails of the same error.
should i just collect this body onto an object that holds last 10 email bodies, and attach this to the swift mailer class? or is there an easier way, like using something that is already embedded in swift mailer for this kind of post sending use? Or maybe a session..
Edit, i call swift mailer from a backend helper class, so think i can pretty much do anything there so long as its atleast semi-elegant.
EDIT this is a refined version of the method that calls both the persist and firing of email
<?php
class someWierdClass
{
public function addLogAction(Request $request, $persist = TRUE, $addEmail = TRUE)
{
$responseAdd = array();
if ($this->getRequest()->request->all() !== null) {
$data = $this->getRequest()->request->get('data') ? $this->getRequest()->request->get('data') : 'no_data';
$duplicate = $this->getRequest()->request->get('duplicate', null);
}
if ($addEmail) {
$responseAdd[] = 'firedIt';
$this->fireEmailString('You have an error log here. <br>' . $data);
}
if ($persist)
{
$responseAdd[] = 'persistedIt';
$this->persistLog($data, $duplicate);
}
if ($responseAdd)
{
$body = implode(', ', $responseAdd);
return new Response($body);
}
}
}
Log emails in a table and check that there it isn't a duplicate every time you send an email.
To do this, you should create a helper function that queries the emails table for entries who's body matches the body you would like to send. If the query returns nothing, then you know that isn't a duplicate. You would then send the email and log it the database. Otherwise, if it returned (a) record(s), you would send a dev ERROR log entry.
If you would like to only check against the last 10 emails, you would do this by querying for both $body == $new_body and $id >= ($total_rows-10)
You would then inject this into the container and call it using something like this
$this->container->get('helper')->sendEmail($body, $subject, $recipients);
Ok, thanks Dan for the idea as to using the database to do the dup check. If you notice, per your suggestion, i was already doing the dup check, but it made me think. It helped me connect the dots.
What i have done is return the answer if its a duplicate on the response when it does the updating the database, then using that response as a flag to determine if email fires or not. (in my case, i go further to check the updated stamp is at least +1 hour old, as opposed to the 'last 10 emails content' idea)
Heres the code.. Enjoy..
<?php
namespace Acme\AcmeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
Acme\AcmeBundle\Entity\Log,
Symfony\Component\HttpFoundation\JsonResponse,
Symfony\Component\HttpFoundation\Response,
Symfony\Component\Config\Definition\Exception\Exception,
Symfony\Component\HttpFoundation\Request,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class someWierdClass
{
/**
* #var array
*/
protected $senderArray = array('no-reply#yorudomain.com' => 'Your Website Name');
/**
* #param Request $request
* #param bool $persist
* #param bool $addEmail
* #return Response
*/
public function addLogAction(Request $request, $persist = TRUE, $addEmail = TRUE)
{
$responseAdd = array();
if ($this->getRequest()->request->all() !== null) {
$data = $this->getRequest()->request->get('data') ? $this->getRequest()->request->get('data') : 'no_data';
$type = $this->getRequest()->request->get('type') ? $this->getRequest()->request->get('type') : 'no_type';
$duplicate = $this->getRequest()->request->get('duplicate', null);
}
if ($addEmail) {
$responseAdd[] = 'firedIt';
$this->fireEmailString('You have an error log here. <br>' . $data);
}
if ($persist) {
$responseAdd[] = 'persistedIt';
$persistResponse = $this->persistLog( $type = $data, $duplicate);
if ($persistResponse) {
// a dup check is done here and results of this is on the response. (e.g. $content->passesCutoff)
$content = json_decode($persistResponse->getContent());
}
}
if ( $addEmail && ( isset($content->passesCutoff) && $content->passesCutoff ))
{
//fire off an email also, because its kind of hard to look in teh logs all the time, sometimes we just want an email.
$successEmail = $this->fireEmailString($data);
if( ! $successEmail )
{
$responseAdd[] = 'firedIt';
}
}
if ($responseAdd) {
$body = implode(', ', $responseAdd);
return new Response($body);
}
}
/**
* #param $emailStringData
* #param null $emailSubject
* #param null $emailTo
* #return mixed
*/
protected function fireEmailString($emailStringData, $emailSubject = null, $emailTo=null){
$templateName = 'AcmeBundle:Default:fireEmailString.html.twig';
if( ! $emailSubject )
{
$emailSubject = 'An email is being fired to you!' ;
}
if( ! $emailTo )
{
$emailTo = 'youremail#gmail.com';
}
$renderedView = $this->renderView(
$templateName, array(
'body' => $emailStringData,
));
$mailer = $this->get('mailer');
$message = $mailer->createMessage()
->setSubject( $emailSubject)
->setBody($emailStringData, 'text/plain')
->addPart($renderedView, 'text/html')
->setFrom($this->senderArray)
->setSender($this->senderArray)
->setTo($emailTo);
$results = $mailer->send($message);
return $results;
}
/**
* #param $type
* #param $data
* #param $duplicate
* #return JsonResponse
*/
protected function persistLog($type, $data, $duplicate) {
$em = $this->getDoctrine()->getManager();
$count = null;
$passesCutoff = null;
$mysqlNow = new \DateTime(date('Y-m-d G:i:s'));
//only two conditions can satisy here, strings '1' and 'true'.
if($duplicate !== '1' && $duplicate !== 'true' /*&& $duplicate != TRUE*/)
{
//in order to check if its unique we need to get the repo
//returns an object (findByData() would return an array)
$existingLog = $em->getRepository('AcmeBundle:Log')->findOneByData(
array('type' => $type, 'data' => $data)
);
if($existingLog)
{
$timeUpdatedString = strtotime($existingLog->getTimeupdated()->format('Y-m-d H:i:s'));
$cutoffStamp = strtotime('+1 hour', $timeUpdatedString); //advance 1 hour (customize this to the amount of time you want to go by before you consider this a duplicate. i think 1 hour is good)
$passesCutoff = time() >= $cutoffStamp ? TRUE : FALSE; //1 hour later
$count = $existingLog->getUpdatedcount();
$existingLog->setUpdatedcount($count + 1); // '2014-10-11 03:52:20' // date('Y-m-d G:i:s')
$em->persist($existingLog);
}
else
{
//this record isnt found, must be unique
$newLog = new Log(); //load our entity
//set in new values
$newLog->setType($type);
$newLog->setData($data);
$newLog->setUpdatedcount(0);
$newLog->setTimeupdated($mysqlNow);
$em->persist($newLog);
}
}
else
{
//we dont care if unique or not, we just want a new row
$newLog = new Log(); //load our entity
$newLog->setType($type);
$newLog->setData($data);
//time updated has been set to auto update to current timestamp in the schema, test first, then remove this
$newLog->setUpdatedcount(0);
$newLog->setTimeupdated($mysqlNow);
$em->persist($newLog);
}
$em->flush();
$response = new JsonResponse();
$response->setData(
array(
'data' => 'persistedIt',
'existingLog' => $count,
'passesCutoff' => $passesCutoff,
));
return $response;
}
}
In hindsight, i would have just passed the last update timestamp back on the response from the persist method, then do the cutoff calculation inside the fire email method obviously, but the above code does work as a starting point.. :-)

Symfony2 Console Output without OutputInterface

I am trying to print some Information to the Console in a Symfony Console Command. Regularly you would do something like this:
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
if ($name) {
$text = 'Hello '.$name;
} else {
$text = 'Hello';
}
if ($input->getOption('yell')) {
$text = strtoupper($text);
}
$output->writeln($text);
}
For the full Code of the Example - Symfony Documentation
Unfortunately I can't access the OutputInterface. Is it possible to print a Message to the Console?
Unfortunately I can't pass the OutputInterface to the Class where I want to print some Output.
Understanding the matter of ponctual debugging, you can always print debug messages with echo or var_dump
If you plan to use a command without Symfony's application with global debug messages, here's a way to do this.
Symfony offers 3 different OutputInterfaces
NullOutput - Will result in no output at all and keep the command quiet
ConsoleOutput - Will result in console messages
StreamOutput - Will result in printing messages into a given stream
Debugging to a file
Doing such, whenever you call $output->writeln() in your command, it will write a new line in /path/to/debug/file.log
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;
$params = array();
$input = new ArrayInput($params);
$file = '/path/to/debug/file.log';
$handle = fopen($file, 'w+');
$output = new StreamOutput($handle);
$command = new MyCommand;
$command->run($input, $output);
fclose($handle);
Debugging in the console
It is quietly the same process, except that you use ConsoleOutput instead
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;
$params = array();
$input = new ArrayInput($params);
$output = new ConsoleOutput();
$command = new MyCommand;
$command->run($input, $output);
No debugging
No message will be printed
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;
$params = array();
$input = new ArrayInput($params);
$output = new NullOutput();
$command = new MyCommand;
$command->run($input, $output);
Look at JMSAopBundle https://github.com/schmittjoh/JMSAopBundle and check out this great article http://php-and-symfony.matthiasnoback.nl/2013/07/symfony2-rich-console-command-output-using-aop/

Return Image from Controller symfony2

I would like to know how can i return an image from the controller without any template.
I would like to use it for pixel tracking in a newsletter.
I start with this code
$image = "1px.png";
$file = readfile("/path/to/my/image/1px.png");
$headers = array(
'Content-Type' => 'image/png',
'Content-Disposition' => 'inline; filename="'.$file.'"');
return new Response($image, 200, $headers);
But on the navigator i have a broken link (file not found...)
According to the Symfony Docs when serving files you could use a BinaryFileResponse:
use Symfony\Component\HttpFoundation\BinaryFileResponse;
$file = 'path/to/file.txt';
$response = new BinaryFileResponse($file);
// you can modify headers here, before returning
return $response;
This BinaryFileResponse automatically handles some HTTP request headers and spares you from using readfile() or other file functions.
Right now you return the filename as response body and write the file-content to the filename property of Content-Disposition.
return new Response($image, 200, $headers);
should be:
return new Response($file, 200, $headers);
... and ...
'Content-Disposition' => 'inline; filename="'.$file.'"');
should be ...
'Content-Disposition' => 'inline; filename="'.$image.'"');
right?
Further take a look at this question.
This works fine for me.
$filepath = "/path/to/my/image/chart.png";
$filename = "chart.png";
$response = new Response();
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Type', 'image/png');
$response->setContent(file_get_contents($filepath));
return $response;
file_get_contents is a bad idea. Reading a large list of images via file_get_contents killed my little server. I had to find another solution and this works now perfect and very fast for me.
The key is to use readfile($sFileName) instead of file_get_contents. The Symfony Stream Response is able to take a callback function which will be executed while sending ($oResponse->send()). So this is a good place to use readfile().
As a little benefit I wrote down a way of caching.
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ImageController
{
public function indexAction(Request $oRequest, Response $oResponse)
{
// Get the filename from the request
// e.g. $oRequest->get("imagename")
$sFileName = "/images_directory/demoimage.jpg";
if( ! is_file($sFileName)){
$oResponse->setStatusCode(404);
return $oResponse;
}
// Caching...
$sLastModified = filemtime($sFileName);
$sEtag = md5_file($sFileName);
$sFileSize = filesize($sFileName);
$aInfo = getimagesize($sFileName);
if(in_array($sEtag, $oRequest->getETags()) || $oRequest->headers->get('If-Modified-Since') === gmdate("D, d M Y H:i:s", $sLastModified)." GMT" ){
$oResponse->headers->set("Content-Type", $aInfo['mime']);
$oResponse->headers->set("Last-Modified", gmdate("D, d M Y H:i:s", $sLastModified)." GMT");
$oResponse->setETag($sEtag);
$oResponse->setPublic();
$oResponse->setStatusCode(304);
return $oResponse;
}
$oStreamResponse = new StreamedResponse();
$oStreamResponse->headers->set("Content-Type", $aInfo['mime']);
$oStreamResponse->headers->set("Content-Length", $sFileSize);
$oStreamResponse->headers->set("ETag", $sEtag);
$oStreamResponse->headers->set("Last-Modified", gmdate("D, d M Y H:i:s", $sLastModified)." GMT");
$oStreamResponse->setCallback(function() use ($sFileName) {
readfile($sFileName);
});
return $oStreamResponse;
}
}
Quick anwser
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
class AnotherController extends Controller {
public function imagesAction($img = 'my_pixel_tracking.png'){
$filepath = '/path/to/images/'.$img;
if(file_exists($filepath)){
$response = new Response();
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $img);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Type', 'image/png');
$response->setContent(file_get_contents($filepath));
return $response;
}
else{
return $this->redirect($this->generateUrl('my_url_to_site_index'));
}
}
}
Also, I had to change:
$file = readfile("/path/to/my/image/1px.png");
to this:
$file = file_get_contents("/path/to/my/image/1px.png");
Seemed like readfile was echoing contents as it read it forcing headers to output early and negating the forced Content-Type header.

How can I run symfony 2 run command from controller

I'm wondering how can I run Symfony 2 command from browser query or from controller.
Its because I don't have any possibility on hosting to run it and every cron jobs are setted by admin.
I don't even have enabled exec() function so when I want to test it, I must copy all content from command to some testing controller and this is not best solution.
See official documentation on this issue for newer versions of Symfony
You don't need services for command execution from controller and, I think, it is better to call command via run method and not via console string input, however official docs suggest you to call command via it's alias. Also, see this answer. Tested on Symfony 2.1-2.6.
Your command class must extend ContainerAwareCommand
// Your command
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
class MyCommand extends ContainerAwareCommand {
// …
}
// Your controller
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
class SomeController extends Controller {
// …
public function myAction()
{
$command = new MyCommand();
$command->setContainer($this->container);
$input = new ArrayInput(array('some-param' => 10, '--some-option' => true));
$output = new NullOutput();
$resultCode = $command->run($input, $output);
}
}
In most cases you don't need BufferedOutput (from Jbm's answer) and it is enough to check that $resultCode is 0, otherwise there was an error.
Register your command as a service and don't forget to call setContainer
MyCommandService:
class: MyBundle\Command\MyCommand
calls:
- [setContainer, ["#service_container"] ]
In your controller, you'll just have to get this service, and call the execute method with the rights arguments
Set the input with setArgument method:
$input = new Symfony\Component\Console\Input\ArgvInput([]);
$input->setArgument('arg1', 'value');
$output = new Symfony\Component\Console\Output\ConsoleOutput();
Call the run method of the command:
$command = $this->get('MyCommandService');
$command->run($input, $output);
In my environment ( Symony 2.1 ) I had to do some modifications to #Reuven solution to make it work. Here they are:
Service definition - no changes.
In controller:
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
...
public function myAction() {
$command = $this->get('MyCommandService');
$input = new ArgvInput(array('arg1'=> 'value'));
$output = new ConsoleOutput();
$command->run($input, $output);
}
You can just simply create an instance of your command and run it:
/**
* #Route("/run-command")
*/
public function someAction()
{
// Running the command
$command = new YourCommand();
$command->setContainer($this->container);
$input = new ArrayInput(['--your_argument' => true]);
$output = new ConsoleOutput();
$command->run($input, $output);
return new Response();
}
Here's an alternative that lets you execute commands as strings the same way you would on the console (there is no need for defining services with this one).
You can check this bundle's controller to see how it's done with all the details. Here I'm going to summarize it ommiting certain details (such as handling the environment, so here all commands will run in the same environment they are invoked).
If you want to just run commands from the browser, you can use that bundle as it is, but if you want to run commands from an arbitrary controller here is how to do it:
In your controller define a function like this:
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\StringInput;
private function execute($command)
{
$app = new Application($this->get('kernel'));
$app->setAutoExit(false);
$input = new StringInput($command);
$output = new BufferedOutput();
$error = $app->run($input, $output);
if($error != 0)
$msg = "Error: $error";
else
$msg = $output->getBuffer();
return $msg;
}
Then you can invoke it from an action like this:
public function dumpassetsAction()
{
$output = $this->execute('assetic:dump');
return new Response($output);
}
Also, you need to define a class to act as output buffer, because there is none provided by the framework:
use Symfony\Component\Console\Output\Output;
class BufferedOutput extends Output
{
public function doWrite($message, $newline)
{
$this->buffer .= $message. ($newline? PHP_EOL: '');
}
public function getBuffer()
{
return $this->buffer;
}
}
same as #malloc
but
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
...
public function myAction() {
$command = $this->get('MyCommandService');
// $input[0] : command name
// $input[1] : argument1
$input = new ArgvInput(array('my:command', 'arg1'));
$output = new ConsoleOutput();
$command->run($input, $output);
}
If you have to pass arguments (and/or options), then in v2.0.12 (and may be true for later versions), you need to specify InputDefinition first before instantiating an input object.
use // you will need the following
Symfony\Component\Console\Input\InputOption,
Symfony\Component\Console\Input\InputArgument,
Symfony\Component\Console\Input\InputDefinition,
Symfony\Component\Console\Input\ArgvInput,
Symfony\Component\Console\Output\NullOutput;
// tell symfony what to expect in the input
$inputDefinition = new InputDefinition(array(
new InputArgument('myArg1', InputArgument::REQUIRED),
new InputArgument('myArg2', InputArgument::REQUIRED),
new InputOption('debug', '0', InputOption::VALUE_OPTIONAL),
));
// then pass the values for arguments to constructor, however make sure
// first param is dummy value (there is an array_shift() in ArgvInput's constructor)
$input = new ArgvInput(
array(
'dummySoInputValidates' => 'dummy',
'myArg2' => 'myValue1',
'myArg2' => 'myValue2'),
$inputDefinition);
$output = new NullOutput();
As a side note, if you are using if you are using getContainer() in your command, then the following function may be handy for your command.php:
/**
* Inject a dependency injection container, this is used when using the
* command as a service
*
*/
function setContainer(\Symfony\Component\DependencyInjection\ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* Since we are using command as a service, getContainer() is not available
* hence we need to pass the container (via services.yml) and use this function to switch
* between conatiners..
*
*/
public function getcontainer()
{
if (is_object($this->container))
return $this->container;
return parent::getcontainer();
}
You can use this bundle to run Symfony2 commands from controller (http request) and pass options/parameters in URL.
https://github.com/mrafalko/CommandRunnerBundle
If you run a command that need the env option like assetic:dump
$stdout->writeln(sprintf('Dumping all <comment>%s</comment> assets.', $input->getOption('env')));
You have to create a Symfony\Component\Console\Application and set the definition like that:
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\NullOuput;
// Create and run the command of assetic
$app = new Application();
$app->setDefinition(new InputDefinition([
new InputOption('env', '', InputOption::VALUE_OPTIONAL, '', 'prod')
]));
$app->add(new DumpCommand());
/** #var DumpCommand $command */
$command = $app->find('assetic:dump');
$command->setContainer($this->container);
$input = new ArgvInput([
'command' => 'assetic:dump',
'write_to' => $this->assetsDir
]);
$output = new NullOutput();
$command->run($input, $output);
You can't set the option env to the command because it isn't in its definition.

Resources