Symfony2, PagerFanta results - symfony

How can I take a result as an array from PagerFanta in Symfony2.1.1 ?
$adapter = new \Pagerfanta\Adapter\DoctrineORMAdapter($query);
$pager = new \Pagerfanta\Pagerfanta($adapter);
$pager->setMaxPerPage(45);
$data = $pager->getCurrentPageResults();
Results of print_r($data);
ArrayIterator Object
(
[storage:ArrayIterator:private] => Array
(
[0] => Trucking\MainBundle\Entity\Sparcs Object
(
[id:Trucking\MainBundle\Entity\Sparcs:private] => 77940
[container:Trucking\MainBundle\Entity\Sparcs:private] => MEDUUUU
...
...
...
I want to get results as getQuery->getArrayResult();

I will Do the query
$array = $query->getResult(Query::HYDRATE_ARRAY);
Use the ArrayAdapter
$adapter = new ArrayAdapter($array);
$pagerfanta = new Pagerfanta($adapter);

You must to set hydratation mode to Query from the adapter:
$adapter = new DoctrineORMAdapter($queryBuilder);
$adapter->getQuery()->setHydrationMode(Query::HYDRATE_ARRAY);
$pager = new Pagerfanta($adapter);

Related

symfony queryBuilder Where IN

Hi all i have problem and don't know what to do.
public function getOrderCityByPrefix($data)
{
$queryBuilder = $this->createQueryBuilder('w')
->where('w.orderCity IN (:data)')
->setParameter('data', $data)
->getQuery();
return $queryBuilder->getResult();
}
Controller:
$cities = json_decode($request->get('cities'), true); // if return i get The controller must return a response (Array(0 => 'VLN', 1 => 'KNS') given)
if i get this responce Array(0 => 'VLN', 1 => 'KNS') and put to function i get well result which i need. But if i put variable $cities to function i have empty result.
$cities = json_decode($request->get('cities'), true);
if(!empty($cities)){
$orders = $this->getDoctrine()->getEntityManager()
->getRepository('AppBundle:OrderWork')
->getOrderCityByPrefix([0 => 'VLN', 1 => 'KNS']); // it's good
$orders = $this->getDoctrine()->getEntityManager()
->getRepository('AppBundle:OrderWork')
->getOrderCityByPrefix($cities); // bad
}

Payum Paypal on Symfony3

I'm trying to integrate a payment system of paypal on my webpage under Symfony. After some researches, I ran into Payum which is a apparently the best bundle for this feature.
The issue is that I don't really understand the doc so the final code I have doesn't work.
Somebody already used payum and could help me to understand it ?
I have for example : $paypalRestPaymentDetailsClass which comes from nowhere and I don't know what should be in this class
Here is my code :
namespace PlatformBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Payum\Core\PayumBuilder;
use Payum\Core\Payum;
use PayPal\Api\Amount;
use PayPal\Api\Payer;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use Payum\Core\Request\GetHumanStatus;
class PayumController extends Controller
{
private function config()
{
return (new PayumBuilder())
->addDefaultStorages()
->addGateway('gatewayName', [
'factory' => 'paypal_rest',
'client_id' => 'REPLACE IT',
'client_secret' => 'REPLACE IT',
'config_path' => 'REPLACE IT',
])
->getPayum();
}
public function prepare()
{
$payum = $this->config();
$storage = $payum->getStorage($paypalRestPaymentDetailsClass);
$payment = $storage->create();
$storage->update($payment);
$payer = new Payer();
$payer->payment_method = "paypal";
$amount = new Amount();
$amount->currency = "USD";
$amount->total = "1.00";
$transaction = new Transaction();
$transaction->amount = $amount;
$transaction->description = "This is the payment description.";
$captureToken = $payum->getTokenFactory()->createCaptureToken('paypalRest', $payment, 'create_recurring_payment.php');
$redirectUrls = new RedirectUrls();
$redirectUrls->return_url = $captureToken->getTargetUrl();
$redirectUrls->cancel_url = $captureToken->getTargetUrl();
$payment->intent = "sale";
$payment->payer = $payer;
$payment->redirect_urls = $redirectUrls;
$payment->transactions = array($transaction);
$storage->update($payment);
header("Location: ".$captureToken->getTargetUrl());
}
public function capture()
{
$payum = $this->config();
$token = $payum->getHttpRequestVerifier()->verify($_REQUEST);
$gateway = $payum->getGateway($token->getGatewayName());
if ($reply = $gateway->execute(new Capture($token), true)) {
if ($reply instanceof HttpRedirect) {
header("Location: ".$reply->getUrl());
die();
}
throw new \LogicException('Unsupported reply', null, $reply);
}
$payum->getHttpRequestVerifier()->invalidate($token);
header("Location: ".$token->getAfterUrl());
}
public function done()
{
$payum = $this->config();
$token = $payum->getHttpRequestVerifier()->verify($_REQUEST);
$gateway = $payum->getGateway($token->getGatewayName());
// you can invalidate the token. The url could not be requested any more.
// $payum->getHttpRequestVerifier()->invalidate($token);
// Once you have token you can get the model from the storage directly.
//$identity = $token->getDetails();
//$payment = $payum->getStorage($identity->getClass())->find($identity);
// or Payum can fetch the model for you while executing a request (Preferred).
$gateway->execute($status = new GetHumanStatus($token));
$payment = $status->getFirstModel();
header('Content-Type: application/json');
echo json_encode(array(
'status' => $status->getValue(),
'order' => array(
'total_amount' => $payment->getTotalAmount(),
'currency_code' => $payment->getCurrencyCode(),
'details' => $payment->getDetails(),
),
));
}
}
Thanks

Cannot call a command from a controller in Symfony2

I am trying to run a command from a controller but it does not work. This is my code:
$email = $request->get('email');
if (empty($email))
$email = $request->get('nombres');
if (empty($password))
$password = '123456';
$application = new Application($this->container->get('kernel'));
$application->setAutoExit(false);
$input = new ArrayInput(array(
"command" => "fos:user:create",
"username" => $username,
"email" => $email,
"password" => $password));
$output = new ConsoleOutput();
$retval = $application->run($input, $output);
var_dump(stream_get_contents($output->getStream()));
die();
Simply it does nothing, #retval is 1 and the $output var is empty.
Any help will be appreciated
Thanks
Jaime
Basically you should not use command in controllers. Console command and Controller are two different delivery layers.
Please use services (so you can use it in controllers and in commands) for fos:user:create you can use something like that:
$manipulator = $this->container->get('fos_user.util.user_manipulator');
$manipulator->create($username, $password, $email, $active = true, $superadmin = false);

ZF2 Unit test album module returns routing issue

I am trying out the phpunit in the Zf2 album module. I encountered an error which states about routing.
Below is the debug information. It says 'Route with name "album" not found', but when I checked module.config.php in the album module folder, I see that is correctly set and in the browser the redirection to that route is working fine.
Album\Controller\AlbumControllerTest::testDeleteActionCanBeAccessed
Zend\Mvc\Router\Exception\RuntimeException: Route with name "album" not found
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Router\SimpleRouteStack.php:292
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\Plugin\Url.php:88
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\Plugin\Redirect.php:54
D:\www\zend2\module\Album\src\Album\Controller\AlbumController.php:80
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractActionController.php:87
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php:468
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php:208
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractController.php:108
D:\www\zend2\tests\module\Album\src\Album\Controller\AlbumControllerTest.php:35
C:\wamp\bin\php\php5.4.3\phpunit:46
I understand that the issue in AlbumController.php line 80 is
return $this->redirect()->toRoute('album');
But not sure why it is not working. Any one has encountered and overcome such issues?
To avoid duplicate Code, you can load your Routes from Module Config:
$module = new \YourNameSpace\Module();
$config = $module->getConfig();
$route = \Zend\Mvc\Router\Http\Segment::factory($config['router']['routes']['Home']['options']);
$router = new \Zend\Mvc\Router\SimpleRouteStack();
$router->addRoute('Home', $route);
I hope it will save approx. 30 minutes of searching in the zend framework 2 code:
class AlbumControllerTest extends PHPUnit_Framework_TestCase
{
//...
protected function setUp()
{
$bootstrap = \Zend\Mvc\Application::init(include 'config/application.config.php');
$this->controller = new AlbumController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = $bootstrap->getMvcEvent();
$router = new \Zend\Mvc\Router\SimpleRouteStack();
$options = array(
'route' => '/album[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
);
$route = \Zend\Mvc\Router\Http\Segment::factory($options);
$router->addRoute('album', $route);
$this->event->setRouter($router);
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setEventManager($bootstrap->getEventManager());
$this->controller->setServiceLocator($bootstrap->getServiceManager());
}
}
Actually the easy way is to get the config data from the service manager:
$config = $serviceManager->get('Config');
Full code for the function setUp():
protected function setUp() {
$serviceManager = Bootstrap::getServiceManager();
$this -> controller = new AlbumController();
$this -> request = new Request();
$this -> routeMatch = new RouteMatch(
array(
'controller' => 'index',
)
);
$this -> event = new MvcEvent();
$config = $serviceManager->get('Config');
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$this -> event -> setRouter($router);
$this -> event -> setRouteMatch($this -> routeMatch);
$this -> controller -> setEvent($this -> event);
$this -> controller -> setServiceLocator($serviceManager);
}

Use of entity_extract_ids($entity_type, $entity)

I am trying to use entity_extract_ids($entity_type, $entity) where:
$entity_type = The entity type; e.g. 'node' or 'user'.
$entity = The entity from which to extract values.
I have never used this function and don't understand what the second parameter (i.e. $entity) is supposed to be.
I would love to see an example code with this function being used. Thank you.
This function return array($id, $vid, $bundle);
Example:
// Define $entity_type.
// Could be 'node', 'user', 'file', 'taxonomy_term' etc.
$entity_type = 'node';
// Get $entity object, in our case $node with nid = 1
$entity = node_load(1);
// print_r will give us something like:
// Array
// (
// [0] => 1
// [1] => 4
// [2] => page
// )
// Where [0] is nid, [1] is vid and [2] is bundle name of a node with nid = 1
print_r(entity_extract_ids($entity_type, $entity));
It's better to use function like that:
list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);

Resources