How to create a fake Symfony\Component\HttpFoundation\File\UploadedFile in a PHPUnit test? - symfony

I'm unable to create a fake UploadedFile in my PHPUnit test.
I found a solution for Laravel but I couldn't find one for Symfony.
This is my code:
$path = '/tmp';
$originalName = 'MANA-BULL 12-2018 Ali.pdf';
$mimeType = "application/pdf";
$size = 4455;
$error = 0;
$fileRaw = new UploadedFile(
$path,
$originalName,
$mimeType,
$size,
$error,
$test = false
);
return $fileRaw;
I get the following exception:
Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException:
The file "/tmp" does not exist
How can I solve this issue?

In your tests directory, create a folder called fixtures. In that folder, place your test PDF file. From your test, you can now create an upload file like so:
<?php
namespace App\Tests\Functional;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class UploadTest extends WebTestCase
{
public function test_uploadFile()
{
$uploadedFile = new UploadedFile(
__DIR__.'../fixtures/foo.pdf',
'foo.pdf'
);
}
}

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');

GuzzleHttp Client class not found in symfony2

I have loaded in GuzzleHttp from
http://docs.guzzlephp.org/en/5.3/quickstart.html
and have the
use GuzzleHttp\Client;
When i call this action...
public function googlevolumeAction(Request $request)
{
$data = $request->request->all();
$searchStr = $data['search'];
$client = new Client();
$req = $client->request('GET', 'https://www.googleapis.com/books/v1/volumes?q=intitle:' .$searchStr, []);
$decode = json_decode($req->getBody());
$total = $decode->totalItems;
$search = null;
if ($total != 0) {
$search = $decode->items;
}
return $this->render('BloggerBlogBundle:Page:googlevolume.html.twig',
['items' => $search]);
}
I get this error...
Attempted to load class "Client" from namespace "GuzzleHttp".
Did you forget a "use" statement for e.g. "Guzzle\Http\Client",
"Guzzle\Service\Client", "Symfony\Component\BrowserKit\Client",
"Symfony\Component\HttpKernel\Client" or
"Symfony\Bundle\FrameworkBundle\Client"?
Any ideas why?
thanks
Looks like you have a different version of guzzle installed than the docs you are looking at. From the error message you got it seems that if you change your use statement to:
use Guzzle\Http\Client;
It should work.

symfony output in kernel.php

in app.php
$kernel = new AppKernel('prod', false);
in Kernel.php
public function __construct($environment, $debug)
{
print('test');
$this->environment = $environment;
$this->debug = (bool) $debug;
$this->rootDir = $this->getRootDir();
$this->name = $this->getName();
if ($this->debug) {
$this->startTime = microtime(true);
}
$defClass = new \ReflectionMethod($this, 'init');
$defClass = $defClass->getDeclaringClass()->name;
if (__CLASS__ !== $defClass) {
trigger_error(sprintf('Calling the %s::init() method is deprecated since version 2.3 and will be removed in 3.0. Move your logic to the constructor method instead.', $defClass), E_USER_DEPRECATED);
$this->init();
}
}
I want to output this code at the browser for learning purposes . I guess it's buffered, but where can I switch it off and output my print at the browser? Or is there a better way through the console?
Not positive I understand the question but if you look in web/app.php then you will see:
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
The bootstrap.php.cache file is where the cached (buffered?) copy of the Kernel object lives. You can either edit the cache file and add your print statements or just not include the cache file:
$loader = require_once __DIR__.'/../app/autoload.php';

How to get file size in symfony2?

I'm using following code to upload a file submitted through a form. How can I get file size before uploading it? I want the max file size to be 20mb.
$file = $data->getFileName();
if ($file instanceof UploadedFile) {
$uploadManager = $this->get('probus_upload.upload_manager.user_files');
if ($newFileName = $uploadManager->move($file)) {
$data->setFileName(basename($newFileName));
}
}
Oldskool is correct. However if you want to retrieve the exact file size after it has been uploaded, you can use the following:
$fileSize = $file->getClientSize();
Another solution would be to change maximum size of upload file in php.ini. The following will echo the current file size limit.
echo $file->getMaxFilesize();
To get form errors, you should validate the form and print any errors if the validation fails.
//include at the top of controller
use Symfony\Component\HttpFoundation\Response;
$form = $this->createForm(new FileType(), $file);
$form->handleRequest($request);
if ($form->isValid()) {
//store data
$data = "stored successfully";
$statusCode = 200;
} else {
//return errors if form is invalid
$data = $form->getErrors();
$statusCode = 500;
}
return new Response($data, $statusCode);
Simply annotate the File object in your Entity with the maxSize option:
/**
* #Assert\File(
* maxSize = "20M"
* )
*/
protected $userFiles;
Also see the documentation on this for further details.

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