I try to give '$_REQUEST['vider']' to an other controller like this :
return $this->forward('TestBundle:Rapport:bo', array('vider' => 'vider'));
//, array ($_REQUEST['vider'] => 'vider) doesn't work too
But in my function Rapport:bo, $_REQUEST['vider'] is null, i give it in the array, where i failed ?
edit :
my Rapport:bo function :
public function boAction(Request $request) {
var_dump($_REQUEST['vider']); // is null
if ( isset($_REQUEST['vider']) ) ) {
var_dump('test');
}
}
Try with:
public function boAction($vider) {
your logic...
Related
Here is the method to test.
public function performPoolRequest(RecreationRequestsCollection $requests): RecreatedPaymentsPoolReading
{
$count_request = count($requests);
if($count_request) {
$pool_recreate_payments = new RecreatedPaymentsPool();
$this->http_client->sendPoolRequest(
$this->generateRequests($requests),
$count_request,
function (ResponseInterface $response, $index) use ($requests, $pool_recreate_payments) {
$this->successHandler($response, $requests, $index, $pool_recreate_payments);
},
function (BadResponseException $reason, $index) use ($requests, $pool_recreate_payments) {
$this->failureHandler($reason, $requests, $index, $pool_recreate_payments);
}
);
return $pool_recreate_payments;
} else {
throw new PoolRequestException('Incorrect amount of requests: ' . $count_request);
}
}
Difficulties arose with this piece of code:
$this->http_client->sendPoolRequest(
$this->generateRequests($requests),
$count_request,
function (ResponseInterface $response, $index) use ($requests, $pool_recreate_payments) {
$this->successHandler($response, $requests, $index, $pool_recreate_payments);
},
function (BadResponseException $reason, $index) use ($requests, $pool_recreate_payments) {
$this->failureHandler($reason, $requests, $index, $pool_recreate_payments);
}
);
I made a mock object $this->http_client
But I don't know how to test methods in the argumets ($this->successHandler, $this->failureHandler, this->generateRequests($requests)) that are sent to the method sendPoolRequest.
All of these methods are protected. I understand how to test them using a reflection object, but I want to know if there is an option to test them within a single test by checking the values in $ pool_recreate_payments.
You have to fake what the http client is doing in some way. That means: actually calling the callback functions. While it might be possible to do that with a PHPUnit mock object, writing own test doubles is often easier.
Here are a few examples to get you started.
public function testAllFailing()
{
$client = new class implements HttpClient {
public function sendPoolRequest(array $requests, int $numRequests, callable $successHandler, callable $errorHandler)
{
foreach ($requests as $index => $request) {
$errorHandler(new BadResponseException(/*...*/), $index);
}
}
};
$myService = new MyService($client);
$result = $myService->performPoolRequest(/*...*/);
self::assertEquals(/*...*/, $result);
}
public function testAllSucceeding()
{
$client = new class implements HttpClient {
public function sendPoolRequest(array $requests, int $numRequests, callable $successHandler, callable $errorHandler)
{
foreach ($requests as $index => $request) {
$successHandler(new Response(/*...*/), $index);
}
}
};
$myService = new MyService($client);
$result = $myService->performPoolRequest(/*...*/);
self::assertEquals(/*...*/, $result);
}
public function testEveryOtherFails()
{
$client = new class implements HttpClient {
public function sendPoolRequest(array $requests, int $numRequests, callable $successHandler, callable $errorHandler)
{
foreach ($requests as $index => $request) {
if ($index % 2 === 0) {
$successHandler(new Response(/*...*/), $index);
} else {
$errorHandler(new BadResponseException(/*...*/), $index);
}
}
}
};
$myService = new MyService($client);
$result = $myService->performPoolRequest(/*...*/);
self::assertEquals(/*...*/, $result);
}
Since Guzzle is used as the http client, I decided to use its capabilities in terms of creating stubs for the response object. Here is a link to the documentation Guzzle documentation. The solution turned out to be simple and allowed us to extensively test the business logic of the response.
I am working on a SilverStripe project. In my project, I am trying to create a GridField custom button. I followed the official documentation. Following is the class form the SilverStripe official page.
class GridFieldCustomAction implements GridField_ColumnProvider, GridField_ActionProvider, GridField_ActionMenuItem
{
public function getTitle($gridField, $record, $columnName)
{
return 'Custom action';
}
public function getCustomAction($gridField, $record)
{
if (!$record->canEdit()) {
return;
}
return GridField_FormAction::create(
$gridField,
'CustomAction'.$record->ID,
'Custom action',
"docustomaction",
['RecordID' => $record->ID]
)->addExtraClass(
'action-menu--handled'
);
}
public function getExtraData($gridField, $record, $columnName)
{
$field = $this->getCustomAction($gridField, $record);
if (!$field) {
return;
}
return $field->getAttributes();
}
public function getGroup($gridField, $record, $columnName)
{
return GridField_ActionMenuItem::DEFAULT_GROUP;
}
public function augmentColumns($gridField, &$columns)
{
if (!in_array('Actions', $columns)) {
$columns[] = 'Actions';
}
}
public function getColumnAttributes($gridField, $record, $columnName)
{
return ['class' => 'grid-field__col-compact'];
}
public function getColumnMetadata($gridField, $columnName)
{
if ($columnName === 'Actions') {
return ['title' => ''];
}
}
public function getColumnsHandled($gridField)
{
return ['Actions'];
}
public function getColumnContent($gridField, $record, $columnName)
{
$field = $this->getCustomAction($gridField, $record);
if (!$field) {
return;
}
return $field->Field();
}
public function getActions($gridField)
{
return ['docustomaction'];
}
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
if ($actionName !== 'docustomaction') {
return;
}
// perform your action here
// output a success message to the user
Controller::curr()->getResponse()->setStatusCode(
200,
'Do Custom Action Done.'
);
}
}
I am struggling to add the custom icon for the button or specify the style class of the button. I can change the column class name. But I cannot find a way for the button. How can I do that?
you can achieve this using ->setAttribute('classNames', 'font-icon-<your-icon>');
i.e. for "edit" icon the code would looks like this:
return GridField_FormAction::create(
$gridField,
'CustomAction'.$record->ID,
'Custom action',
"docustomaction",
[
'RecordID' => $record->ID
]
)
->addExtraClass('action-menu--handled')
->setAttribute('classNames', 'font-icon-edit');
You can find all available icons on this page:
https://gbaumeister.github.io/ss4-icons/
I have this issue where I'm attempting to create a subrequest in Silex and basically forward my parameters to another controllers. Exhibit A is broken below (after attempts to refactor), and Exhibit B, the original version, works:
Exhibit A ($this->app is lost after creating the request):
class EntriesController {
private $app;
private $req;
public function __construct($app, $req) {
$this->app = $app;
$this->req = $req;
}
public function updateAction() {
//...
//$url defined here (eyesore-ingly long, so not shown)
$subRequest = Request::create($url, 'GET', $params, $this->req->cookies->all(), array(), $this->req->server->all());
//$this->app **no longer** exists here
return $this->app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}
}
EntriesController instance is created below:
class AppControllerProvider implements ControllerProviderInterface {
public function connect(Application $app) {
$controllers = $app['controllers_factory'];
//...
$controllers->patch('/edit', function (Request $req) use ($app) {
$entriesCtrl = new \EntriesController($app, $req);
return $entriesCtrl->updateAction();
});
//...
}
Exhibit B (works just fine):
class AppControllerProvider implements ControllerProviderInterface {
public function connect(Application $app) {
$controllers = $app['controllers_factory'];
$controllers->patch('/edit', function (Request $req) use ($app) {
//...
//$url defined here
$subRequest = Request::create($url, 'GET', $params, $this->req->cookies->all(), array(), $this->req->server->all());
return $this->app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}
//...
});
I basically just reorganized the logic from Exhibit B's 'PATCH' /edit method body into a controller class, and I passed the Silex Application instance $app to a new instance of the controller class.
The only difference between Exhibit A and Exhibit B as far as I can tell is that you instantiate a controller object in the path method callback. Maybe there is something wrong with how this controller is setup or a namespace issue? Shootin' in the dark here.
I can confirm that in my silex application the following code does not produce a null $app container:
GlobalControllerProvider.php
<?php
namespace Dev\Pub\Provider\Controller;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
class GlobalControllerProvider implements ControllerProviderInterface
{
public function connect(Application $app)
{
$controllers = $app['controllers_factory'];
$controllers
->get('/', 'Dev\Pub\Controller\GlobalController::indexAction')
->bind('homepage')
;
$controllers
->patch('/edit', function (Request $req) use ($app) {
$entriesCtrl = new \Dev\Pub\Controller\GlobalController();
return $entriesCtrl->updateAction($app, $req);
});
return $controllers;
}
}
GlobalController.php
<?php
namespace Dev\Pub\Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class GlobalController
{
public function indexAction(Application $app, Request $request)
{
return new Response($app['twig']->render('index.html.twig'));
}
public function updateAction(Application $app, Request $request)
{
$url = 'http://silex.local/index_dev.php/';
$params = array();
$subRequest = Request::create($url, 'GET', $params, $request->cookies->all(), array(), $request->server->all());
// outputs: 'Silex\Application'
error_log(print_r(get_class($app),1).' '.__FILE__.' '.__LINE__,0);
// outputs: 1
error_log(print_r(is_object($app),1).' '.__FILE__.' '.__LINE__,0);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}
}
index.main.js
$(function(){
console.log('index.main.js');
$.ajax({
url: "http://silex.local/index_dev.php/edit",
method: "PATCH"
}).done(function( data ) {
console.log(data);
}).fail(function( data ) {
console.log(data);
});
});
I would like to factorize some code in my models repositories.
A really basic example
public function getPlayers()
{
$qb = $this->createQueryBuilder('p')
->innerJoin(...) // whatever the request
->where(...)
// I want to factorize this line because a lot of function use it
->andWhere('p.active = true');
return (...);
}
So I create a private function
private function getActivePlayer() {
return $this->andWhere('p.active = true');
}
And I would like to use it like that in any function
$qb = $this->createQueryBuilder('p')
->innerJoin(...)
->where(...)
->getActivePlayer()
But of course I have this error
Attempted to call method "getActivePlayer" on class "Doctrine\ORM\QueryBuilder"
It's possible to achieve this kind of factorization? What will be the syntaxe?
Thanks
You can try something like:
public function getPlayers()
{
$qb = $this->createQueryBuilder('p')
->innerJoin(...)
->where(...);
$qb = $this->getPlayerType($qb);
}
private function getActivePlayer(QueryBuilder $qb)
{
return $qb->andWhere('p.active = true');
}
Using the -> operator in the context of a QueryBuilder object will only call methods within the QueryBuilder class. You must define your own class that extends the QueryBuilder. Something like:
class MyQueryBuilder extends \Doctrine\ORM\QueryBuilder {
public function getActivePlayer() {
return $this->andWhere('p.active = true');
}
}
Then implement that builder instead of the default Query Builder:
$qb = new MyQueryBuilder();
$qb->select('p')
->from(...)
->innerJoin(...)
->where(...)
->getActivePlayer()
// ...
Note that the above code is just simple demonstration to show you what length of effort it takes to achieve exactly what you want to do - in actual practice, you'll need to do more than this.
You are best off starting with a basic QueryBuilder in a particular private method then amending it in your public getters:
private function getPlayerQueryBuilder()
{
$qb = $this->createQueryBuilder('p')
->innerJoin(...) // whatever the request
->where(...)
return $qb;
}
public function getActivePlayers() {
$result = $this->getPlayerQueryBuilder()
->andWhere('p.active = true')
->getQuery()->getResult();
return $result;
}
public function getAllPlayers() {
$result = $this->getPlayerQueryBuilder()
->getQuery()->getResult();
return $result;
}
I'm trying to write a Twig filter to be able to sort a Doctrine ArrayCollection, but the returned array is not sorted :( Can you please help me to fix this:
class SortExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('sortby', array($this, 'sortByFilter')),
);
}
public function sortbyname( $a, $b )
{
if ($a->getName() === $b->getName()) {
return 0;
}
if ( $a->getName() < $b->getName() ) {
return 1;
}
return -1;
}
public function sortByFilter($collection)
{
$iterator = $collection->getIterator();
$iterator->uasort(array($this, 'sortbyname'));
return $collection;
}
I'm not quite sure if the returned collection in sortByFilter is changed.
This is because you are getting the iterator and sorting it.
The method getIterator creates a new ArrayIterator which makes a copy of the array.
Then, you are returning the collection, which is not sorted.
Here is a little sample of what happens.
You just have to replace
return $collection;
By
return $iterator;