Menu
  • HOME
  • TAGS

WebTestCase, Silex and $_GET

Tag: symfony2,silex,web-testing

I'm experiencing some issues on a WebTestCase using Silex: on one of my controller's action, I need a parameter passed through a normal $_GET (I have to as it's an URL, and Apaches interprets the %2F if it's outside of the query string -- see Url Variables with %2f not handled by silex for example)

Here's how my route is defined:

$controller
   ->get('/get', <controller action>)
   ->value('url', (!empty($_GET['url']) ? $_GET['url'] : false));

It works fine in browser, but it doesn't seem to be working inside a WebTestCase like this one: $_GET stays empty...

$client = $this->createClient();
$client->request('GET', '/get?url=' . urlencode($url));

edit

I just did a quick experiment: if I do the following in my route:

$controller
        ->get('/get/{url}', <action>)
        ->assert('url', '.*');

And this in the test:

$client = $this->createClient();
$client->request('GET', '/get/' . urlencode($url));

Everything if fine, $url gets passed to the controller... but well, it doesn't work on the browser anymore as it passes through Apache.

Best How To :

The server globals (like $_GET) are populated by Apache. When running the functional test, Apache is skipped so $_GET is not populated anymore. Instead of using the server globals, you should use the Request object to extract the GET parameters. This way, the framework will intercept both the PHPUnit injected variables and the Apache injected variables; it will then make them available in your action method via a Request object that can be injected as a function parameter.

Sample how to extract the url parameter:

$url = $request->query->get('url');

Using crontab to call wget every 5 minutes

php,symfony2,crontab,wget

use the console component make it run your hello.php script call the command in your crontab bash /your/dir/app/console yourcommand or even simpler run php your/dir/hello.php...

Set Auth Token manually for different firewall

symfony2

This may be a little hacky, but manually wiriting the token to the session achieved what I wanted $token = new UsernamePasswordToken($user, null, 'account', $user->getRoles()); $this->get('session')->set('_security_account',serialize($token)); // Needed to prepend "_security_" to the firewall name to get "_security_account" Didnt even need to call lines such as //Didnt seem to need...

OAuth HwioBundle, different socialNetWork

php,symfony2,oauth,hwioauthbundle

If user's email is similar in both social accounts, you can use email field to identify user. You should create user provider class. If user with provided social token won't be found in database, user provider will try to find user by email and add new social token for specified...

Symfony2 move app.php from web directory to root directory

symfony2

In your composer.json you have these lines: "extra": { "symfony-app-dir": "app", "symfony-web-dir": "web", You need to update those and run composer update to make your bootstrap.php.cache file ready for the new structure....

Validation of a form before submission

php,validation,symfony2,form-submit

In place of: $form->submit($request->request->get($form->getName())); Try: $form->submit(array(), false); ...

Unable to configure Symfony (3rd party) bundle

php,symfony2,rss

I havent tried this bundle yet, but i think you need to tell doctrine that you want to save your newly created feed into the database: $feeds = new Feed; $reader->readFeed($url, $feeds, $date); $em = $this->getDoctrine()->getManager(); $em->persist($feeds); $em->flush(); return $this->render('default/index.html.twig'); UPDATE According to the docs if you want to use...

Deserializing or parse XML response in Symfony2

php,xml,symfony2,deserialization,jmsserializerbundle

It depends on your intention. If you want to directly push part or all of the XML to an entity/document object for saving to a database then the JMSSerializerBundle can do this very smartly and is definitely the best way to do it. If however you just want to extract...

Dependencies in forms Symfony2

php,forms,symfony2,events,entities

Create a form type CardAttributeValueType for CardAttributeValue entity, inside this form add fields depending on passed attribute type: class CardAttributeValueType extends AbstractType public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) { $value = $event->getData(); $form = $event->getForm(); if (!$value) { return; } switch ($value->getCardAttribute()->getType()) { case 'text': $form->add('valueVarchar',...

Redirecting all ip to maintenance page except some ips

apache,.htaccess,symfony2

mod_rewrite doesn’t know a %{REMOTE_URI} variable. Probably you mean %{REQUEST_URI}.

Store entity from session doesn't work => $em->persist()

php,symfony2,doctrine2

When you store doctrine entities in the session they become detached from the EntityManager. You need to merge any entities which are already in the database back into the EntityManager. Something like this (checking for null where necessary): foreach($contactPersons as $key => $contactPerson) { $mergedCountry = $em->merge($contactPerson->getAddress()->getCountry()); $contactPerson->getAddress()->setCountry($mergedCountry); $em->persist($contactPerson); }...

With a OneToMany relation between entities, how create the right queryBuilder with Doctrine (on the Inversed Side entity)

php,symfony2,doctrine2,one-to-many,query-builder

When you specify multiple FROMs, later one will overwrite the previous ones. So, instead of writing: $queryBuilder ->select('pm', 'c') ->from('MySpaceMyBundle:PointsComptage', 'pc') ->from('MySpaceMyBundle:ParametresMesure', 'pm') ->leftJoin('MySpaceMyBundle:Compteurs', 'c', 'WITH', 'pm.compteurs = c.id') ->where('pc.id = c.pointsComptage ') ->andWhere('pc.id = :id') ->setParameter('id', $id); I believe you need something like this: $queryBuilder ->select('pc', 'c', 'pm') ->from('MySpaceMyBundle:PointsComptage',...

Symfony change validation message globally

php,symfony2,symfony-2.3

The easiest way is to define an translations file. # app/Resources/translations/validators.es.yml This value should not be blank.: Campo obligatorio This value is not a valid email address.: e-mail no válido ...

How to create a console command in Symfony2 application

php,symfony2,symfony-2.6,symfony-components,symfony-console

You are reading article about Console Component. This is slightly different than registering a command in your bundle. First, your class should live in Namespace Command, and it must include the Command prefix in classname. You've mostly done that. I will show you a sample command to grasp the idea...

Symfony2: changing the request class and updating the test environment

php,symfony2,request,phpunit

I think you have to override the class for test.client which, by default, uses Symfony\Bundle\FrameworkBundle\Client. Something like: <parameters> <parameter name="test.client.class">My\Bundle\AppBundle\Test\Client</parameter> </parameters> First, take a look at the base class Symfony\Component\BrowserKit\Client. If you look at the request method of this class you will find this: public function request(/* ... */) {...

Symfony2 creating and persisting entity relationships

php,mysql,symfony2,doctrine2

When you create two entities with a one-to-one relationship, both entities need to be persisted either explicitly or by using cascade persist on one side of the relationship. You also need to explicitly set both sides of the relationship. Doctrine - Working with Associations - Transitive persistence / Cascade Operations...

Setup VPS with a Symfony2 project from git repository

symfony2,vps

Here are my deployment steps: git clone project go to project directory php composer.phar install (and if composer is not in the project directory curl -sS https://getcomposer.org/installer | php) app/console doctrine:database:create app/console schema:update --force app/console assets:install web --symlink chmod 777 -R app/cache app/logs web/media/cache (I often use liip imagine, it...

Symfony2 relationship between two entities

php,mysql,entity-framework,symfony2

It's normal that the creation of a new email is not associated to a skin object. How could it ? The relation is unidirectional, and only works when you create a skin and you give it an email. To create an email and give it a skin, you have to...

Silex namespace : class MainController does not exist

php,class,namespaces,autoload,silex

I believe your problem is caused by the way you named your directory controllers. According to the documentation about PSR-4 standard: 5) Alphabetic characters in the fully qualified class name MAY be any combination of lower case and upper case. 6) All class names MUST be referenced in a case-sensitive...

Symfony 2 unable to pass entity repository to form

php,forms,symfony2,runtime-error

You have not included the Symfony EnityRepository class at the top of your form file so PHP is looking for it in the same directory as your form class. Hence the error message. Add this to your form class (or qualify EntityRepository inline): use Doctrine\ORM\EntityRepository; ...

How adapt the path to the previous and next article

php,symfony2

If you have a variable defining active/inactive status, you can use a PHP "if" or "if/else" command to only perform your concatenation when the variable defining active status is of a certain value.

Symfony Crawler: how to check that a link to a particular page exists

php,symfony2,phpunit,functional-testing

You can use Crawler::filterXPath() to check for the presence or even absence of html elements matching all sorts of criteria. To check for the presence of a link I prefer to use the element id as that is most likely to remain constant. For example, if you modify your link...

Unique Entity Error message

api,symfony2,exception-handling,doctrine

The Symfony validator service can be used directly to validate any object for which validation constraints are defined. For example in a controller: $validator = $this->get('validator'); $errors = $validator->validate($test); To perform validation within a service you can pass the validator service into your service....

order attribute of an object in Synfony

php,symfony2

You could add a hidden field to you query that sorting things in the order that you wanted so that you don't need to process the complete ArrayCollection to sort. public function findByArticleInOrderOfState() { return $this->createQueryBuilder('c') ->select('c') ->addSelect(' CASE WHEN c.state = :state_new THEN 1 WHEN c.state = :state_viewed THEN...

comparison operator is not working in twig

php,symfony2

try to not convert the dates to string with twigs date filter e.g {% set upcoming_days =daysdiff(event_startdate) %} instead of {% set upcoming_days =daysdiff(event_startdate)|date("d.m.y") %} ...

Update session in symfony2 for shoppingg cart

php,symfony2,symfony-2.1,php-5.3,symfony-2.3

You can simplify your code to, i guess your session array would look something like array( '11' =>array('id'=>'11','title'=>'some product','product_quantity'=>2), '12' =>array('id'=>'12','title'=>'some product','product_quantity'=>1), '13' =>array('id'=>'13','title'=>'some product','product_quantity'=>3), ); key in your cart array will be product id so there will be no chance of duplicate product in array now in below code...

Symfony/Twig how to render a Route set by anotation?

php,symfony2,routing,twig,url-routing

When you omit the name it's being autogenerated for you. The autogenerated name is a lowercase concatenation of bundle + controller + action. For example, if you have: Bundle AppBundle Controller MyController Action: testAction() the name would be app_my_test. You can list all routes using Terminal: php app/console router:debug All...

Symfony files which are included in CSS are not found when using assetic

css,symfony2,twig,assetic

From the Symfony docs and this section as well: Notice that in the original example that included JavaScript files, you referred to the files using a path like @AppBundle/Resources/public/file.js, but that in this example, you referred to the CSS files using their actual, publicly-accessible path: bundles/app/css. You can use either,...

ClassNotFoundException Symfony UserBundle

symfony2,fosuserbundle

When you try to clear cache but its not getting cleared you should use --no-warmup option, this will make sure that you cache is re-generated and cache is not warmed up only. I think this can help you: php app/console cache:clear --env=prod --no-warmup or php app/console cache:clear --env=dev --no-warmup ...

Symfony\Component\Config\Exception\FileLoaderLoadException] error

php,symfony2,twig,swiftmailer

As noted by redbirdo, you have = instead of : in your parameters.yml, which should be like this: parameters: database_driver: pdo_mysql database_host: 127.0.0.1 database_port: null database_name: symblog_db database_user: root database_password: null mailer_transport: "gmail" mailer_encryption: "ssl" mailer_auth_mode: "login" mailer_host: "smtp.gmail.com" mailer_user: "[email protected]" mailer_password: "xxxxxxxxx" secret: JaTylkoTrenuje ...

WebTestCase, Silex and $_GET

symfony2,silex,web-testing

The server globals (like $_GET) are populated by Apache. When running the functional test, Apache is skipped so $_GET is not populated anymore. Instead of using the server globals, you should use the Request object to extract the GET parameters. This way, the framework will intercept both the PHPUnit injected...

Symfony2: ajax call redirection if session timedout

ajax,symfony2,session

Found a working solution : Add a function in my global controller which check if session is still active and responds with "ok" if yes, "ko" if not. public function pingAction() { $securityContext = $this->container->get('security.context'); if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') || $securityContext->isGranted('IS_AUTHENTICATED_FULLY')) { return new Response("ok"); } return new Response("ko"); } and i...

Force Uppercase on Symfony2 form text field

php,forms,symfony2

I’m not sure if you ask for server-side validation or assistance for client-side uppercase input. In case of the latter: you could add a CSS class or a data-* attribute (something like ->add('PID', 'text', ['label'=>'License Number', 'required' => FALSE, 'attr' => ['data-behavior' => 'uppercase']])) to the PID element. Then, you...

AngularJS execute some action in all application instances

angularjs,symfony2

You can use angular.service Services Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app. click here for More details ...

Class inheritance in Symfony2

php,symfony2,doctrine2

Usually this error occurs when you forget to specify the repository class inside your entity class. Try modifying to the Entity annotation of your entity class to: /** * @ORM\Entity(repositoryClass="AppBundle\Entity\CategoryRepository") */ class Category {} ...

symfony twig render dynamic twig code

symfony2,twig

You will have to use twig core or may be customized view rendering Check below code $loader = new Twig_Loader_Array(array( 'index.html' => 'Hello {{ name }}!', )); $twig = new Twig_Environment($loader); echo $twig->render('index.html', array('name' => 'Fabien')); check here for documentation: http://twig.sensiolabs.org/doc/api.html#built-in-loaders...

Symfony Entity query builder that checks for free spots

php,mysql,symfony2,doctrine2,dql

A having will work fine like so: $qb->select('s') ->from('FooChallengeBundle:Slot', 's') ->join('s.teams', 't') ->groupBy('s') ->having('count(t) < s.amount') ->getQuery() ->getResult(); ...

Setting cookie for AngularJS translate locale using PHP

php,angularjs,symfony2,angular-translate

Set the cookie via PHP: <?php setcookie("_locale", "en"); ?> and retrieve it from angular with ngCookies: angular.module('app', ['ngCookies']) .controller('ExampleController', ['$cookies', function($cookies) { // Retrieving the cookie var locale = $cookies.get('_locale'); // Do something with locale }]); ...

Remove automaticaly entity in BD when choice value not selected (or null selected)

php,forms,symfony2,doctrine

You could use a doctrine entity listener: https://symfony.com/doc/current/bundles/DoctrineBundle/entity-listeners.html http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#entity-listeners And have something like this in it: public function postUpdateHandler(Vote $vote, LifecycleEventArgs $event) { if (null === $vote->getValue()) { // Following two lines could be avoided with a onDelete: "SET NULL" in Picture orm mapping $picture = $vote->getPicture(); $picture->removeVote($vote); $this->em->remove($vote);...

Symfony2 service unable to find template

php,email,symfony2,templates,twig

Even if your service lies in the same namespace as it's your template, that does not mean that you can call it directly like that. Did you tried the way you render normal controller templates, like this: ->setBody($this->twig->render( 'AppBundle:Emails:email-voucher.html.twig', [ 'order' => $order, 'voucher' => $voucher, 'customer' => $customer ]...

Symfony2/Twig - iterate over select options

php,symfony2,twig

<select name="country"data-width="100%"> {% for key,val in form.country.vars.choices %} <option value="{{ val.value }}" {{ form.country.vars.value == '' and key==0 ? ' selected ' :(val.value == form.country.vars.value ? ' selected ' : '') }}>{{ val.label | trans }}</option> {% endfor %} </select> ...

Symfony/Twig radio style formbuilder

php,symfony2,twig,formbuilder

I solved this problem by editing, contoller: ->add('categoryId', 'entity', array( 'class' => 'MyBundle:Category', 'property' => 'name', 'expanded' => true, 'multiple' => false, 'choices' => $this->getDoctrine() ->getRepository('MyBundle:Category') ->findAll(), 'required' => true, )) And in my twig gallery: <div class="row"> {% for child in form.categoryId %} <div class="radio i-checks col-md-3"> <label>{{ form_widget(child,...

Adding own action to SonataAdminBundle dropdown menu

symfony2,sonata

One way would be to override the template that is used when editing. Now, what you need to do is: Create new directory (if you already haven't) in app/Resources called SonataAdminBundle. Inside, create another one called views. This would create a path like app/Resources/SonataAdminBundle/views. This is Symfony basic template overriding....

Symfony 2 - Class “Mingle\StandardBundle\Entity\Product” is not a valid entity or mapped superclass

php,symfony2,doctrine,entity,bundle

Annotations have to be placed inside /** */ comment block, otherwise they are not recognized.

Symfony2 Catchable Fatal Error: Argument 1 passed to entity Catchable Fatal Error: Argument 1 passed to entity

php,forms,symfony2,entity,symfony-2.6

Set data_class option for your InYourMindFriendType Checkout http://symfony.com/doc/current/reference/forms/types/form.html#data-class...

I can't do update with an entity in my select symfony 2

symfony2

Add this method to your Tecnicos entity: public function __toString() { return $this->name; // could be anything that returns a string, even a string itself (but wouldn't be relevant). } ...

How to write and use Monolog handlers and channels

php,symfony2,monolog,symfony-2.6

You can try that way, monolog: channels: ["testchannel"] handlers: test: # log all messages (since debug is the lowest level) level: debug type: stream path: "%kernel.logs_dir%/testchannel.log" channels: ["testchannel"] And in the controller you can get the logger and do your thing; class DefaultController extends Controller { public function indexAction() {...

Symfony one-to-one, unidirectional relation

symfony2,doctrine2

There's no change you can make to your annotations to make this work with your existing relationships. You have defined a nullable one-to-one relationship between the Contact and User entities. From a class perspective this means that a Contact's $user must either point to an instance of User or be...

wkhtmltopdf on openSuSE: cannot connect to X server

php,symfony2,pdf-generation,twig,wkhtmltopdf

The solution for openSuSE: Install xvfb-run (on other *nix-systems maybe "xvfb") Change in the config part of the bundle (in app/config/config.yml) the binary option from "wkhtmltopdf" to xvfb-run -a -s "-screen 0 640x480x16" wkhtmltopdf Check the folder permissions. For german users: http://www.antondachauer.de/2015/06/19/wkhtmltopdf-unter-opensuse-mit-symfony-knpsnappybundle/...

Logs an entire array using Monolog [closed]

php,symfony2,monolog,symfony-2.6

If you check the logger interface (https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php) you will see all of the logging methods gets message as a string, thus you get a warning when you try to log with a variable type other than string. I tried to use a processor to format the array in a custom...