how to make a multypart/data request with browserkit client? - symfony

$data = [
'name' => 'Merry Christamas',
'description' => 'Merry Christamas',
'starts_at' => '2018-9-15 12:45:56',
'ends_at' => '2050-9-15 12:45:56',
'priority' => -1,
'coupon_based' => false,
'action' => [
'type' => 'order_fixed_discount',
'configuration' => [
'amount' => 100
]
],
'rules' => [
[
'type'=> 'item_total',
'configuration' => [
'amount' => 2500,
'base_amount' => 100,
]
]
]
];
$multipartStream = new MultipartStream($this->flatten($data)); //use GuzzleHttp\Psr7\MultipartStream;
I use following method to convert the associative array to MultipartStream needs.
protected function flatten(array $array, string $prefix = '', string $suffix = ''): array
{
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, $this->flatten($value, $prefix . $key . $suffix . '[', ']'));
} else {
if ($value instanceof UploadedFile) {
$result[] = [
'name' => $prefix . $key . $suffix,
'filename' => $value->getClientOriginalName(),
'Mime-Type' => $value->getClientMimeType(),
'contents' => file_get_contents($value->getPathname()),
];
} else {
$result[] = [
'name' => $prefix . $key . $suffix,
'contents' => $value,
];
}
}
}
return $result;
}
then make request with browserkit client
$this->client->request(
'POST',
'/api/admin/promotions',
[],
[],
[
'CONTENT_TYPE' => 'multipart/form-data; boundary=--'.$multipartStream->getBoundary() ,
'HTTP_Authorization'=> "blabla"
],
$multipartStream->getContents()
);
but the request->request->all() is empty, what is the correct way to make a multipart/data request with symfony browserkit client? I have searched a lot , but have no lucky to find an example.

Related

How to add text that there are no search results for such entered word to a custom block?

I have a view that searches for indexed entity fields using context filters. I added a custom block to the view like this:
{{ drupal_block('result_entity_product_categories', {arguments}) }}
This block displays categories that match the entered word in the search. If you enter something for which there are no search results, for example, bbbbb, I need to display something like this:
Sorry
No results for: "bbbbb"
But here are some of our most popular products
P.S. The option to add text to the No Results Behavior view setting is not suitable. It is necessary to add text in the custom block.
The build() method code of my custom block:
public function build() {
$configuration = $this->getConfiguration();
$term = $configuration['arguments']['0'] ?: '';
if (empty($term)) {
return '';
}
$index = $this->entityTypeManager->getStorage('search_api_index')->load('entity_product_index');
$parse_mode = $this->parseModeManager->createInstance('terms');
$parse_mode->setConjunction('AND');
$search_query = $index->query();
$search_query->setParseMode($parse_mode)
->keys($term);
$search_result = $search_query->execute();
$rows = [];
foreach ($search_result->getResultItems() as $item) {
if (($node = $item->getOriginalObject()->getEntity()) && ($node instanceof NodeInterface)) {
$categoryKey = $node->get('field_entity_product_category')->getString();
if ($categoryKey) {
++$rows[$categoryKey];
}
}
}
$build['container'] = [
'#type' => 'container',
'#attributes' => [
'class' => ['category-counter-wrapper'],
],
];
foreach ($rows as $key => $count) {
if ($node = $this->entityTypeManager->getStorage('node')->load($key)) {
$build['container'][$key] = [
'#type' => 'container',
'#attributes' => [
'class' => ['item'],
],
'label' => [
'#type' => 'container',
'#markup' => $node->getTitle(),
'#attributes' => [
'class' => ['label'],
],
],
'count' => [
'#type' => 'container',
'#markup' => $count,
'#attributes' => [
'class' => ['count'],
],
],
'link' => [
'#type' => 'link',
'#url' => Url::fromUserInput($node->get('field_custom_url')->getString(), ['query' => ['text' => $term]]),
'#attributes' => [
'class' => ['link'],
],
],
];
}
}
return $build;
}

Drupal 8: how to generate options based on Ajax callback

In Drupal 8, I want to generate options of second select-box based on Ajax call of first select-box. The result generate a third new select box but I don't need to generate a new one. I want to replace the options of the second select-box. Please see my codes below:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['example_select'] = [
'#type' => 'select',
'#title' => $this->t('Select element'),
'wrapper' => 'first',
'#options' => [
'1' => $this->t('One'),
'2' => $this->t('Two'),
'3' => $this->t('Three'),
'4' => $this->t('From New York to Ger-ma-ny!'),
],
'#ajax' => [
'callback' => '::myAjaxCallback',
'disable-refocus' => FALSE,
'event' => 'change',
'wrapper' => 'edit-output',
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
$form['example_select2'] = [
'#type' => 'select',
'#title' => $this->t('Select element'),
'#prefix' => '<div id="first">',
'#suffix' => '</div>',
'#options' => [
],
'#ajax' => [
'callback' => '::myAjaxCallback2',
'disable-refocus' => FALSE,
'event' => 'change',
'wrapper' => 'edit-output',
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
return $form;
}
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('example_select')) {
$arr = array('1' => 'Nice way', '2' => 'Good way');
$form['example_select2']['#options'] = $arr;
}
return $form['example_select2'];
}
The below code is working well forme.
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('example_select')) {
$arr = array('1' => 'Nice way', '2' => 'Good way');
$form['example_select2']['#options'] = $arr;
}
$form_state->setRebuild(TRUE);
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand("#first", ($form['example_select2'])));
return $response;
}

ZF3 Multiple Controllers in same Module

I am learning ZF3, i am trying to add InfoController to the Album module. would my URL be ....../album/info? I am getting 404 error occurred. I have seen John Deck's post and implemented exactly the same, but still not working
This is my module.config.php
<?php
namespace Album;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return array(
'controllers' => [
'factories' => [
Controller\InfoController::class => function($container) {
return new Controller\InfoController(
$container->get(\Album\Model\InfoTable::class)
);
},
Controller\AlbumController::class => function($container) {
return new Controller\AlbumController(
$container->get(\Album\Model\AlbumTable::class)
);
},
],
'aliases' => [
'index' => AlbumController::class,
'info' => InfoController::class,
]
],
'router' => array(
'routes' => array(
'album' => array(
'type' => Segment::class,
'options' => array(
'route' => '/album[/:action[/:id]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\AlbumController',//Controller::class,
'action' => 'index',
),
),
),
'info' => array(
'type' => Segment::class,
'options' => array(
//'route' => 'Album/Controller/Info[/:action[/:id]]',
'route' => '/InfoController[/:action[/:id]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Info',//::class
'action' => 'index',
),
),
),
),
),
'view_manager' => [
'display_not_found_reason' => false,
'display_exceptions' => false,
'doctype' => 'HTML5',
'template_map' => [
'layout/album' => __DIR__ . '/../view/layout/album_layout.phtml',
'album/album/index' => __DIR__ . '/../view/album/album/index.phtml',
'layout/album' => __DIR__ . '/../view/layout/info_layout.phtml',
'info/info/index' => __DIR__ . '/../view/info/info/index.phtml',
],
'template_path_stack' => [
'Album' => __DIR__ . '/../view',
'Info' => __DIR__ . '/../view',
],
],
);
Here's my Module.php
<?php
namespace Album;
use Album\Model\InfoTable;
use Album\Model\Info;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return array(
'factories' => array(
Model\AlbumTable::class => function($container) {
$tableGateway = $container->get(Model\AlbumTableGateway::class);
return new Model\AlbumTable($tableGateway);
},
Model\AlbumTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
Model\InfoTable::class => function($container) {
$tableGateway = $container->get(Model\InfoTableGateway::class);
return new Model\InfoTable($tableGateway);
},
Model\InfoTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Info());
return new TableGateway('info', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
public function getControllerConfig()
{
return array(
'factories' => array(
Controller\AlbumController::class => function($container) {
return new Controller\AlbumController(
$container->get(Model\AlbumTable::class)
);
},
Controller\InfoController::class => function($container) {
return new Controller\InfoController(
$container->get(Model\InfoTable::class)
);
},
),
);
}
}

WordPress plugin not installing(instagram-auto-poster)

I want to install instagram-auto-poster but it shows error in these lines:
$data = [
'phone_id' => $this->generateUUID(true),
'_csrftoken' => $token[0],
'username' => $this->username,
'guid' => $this->uuid,
'device_id' => $this->device_id,
'password' => $this->password,
'login_attempt_count' => '0',
];
$login = $this->request('accounts/login/', $this->generateSignature(json_encode($data)), true);
if ($login[1]['status'] == 'fail') {
throw new InstagramException($login[1]['message']);
return;
}

symfony test undefined function

i have problem with my test. I don't know why my function is undefined. I add use statetment, phpstorm see this class. But when run test error with undefined.
namespace tests\AppBundle\Parser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use AppBundle\Parser\CommissionDataParser;
class CommissionDataParserTest extends WebTestCase
{
public function testGroupOrdersByWeek()
{
$orders = [
0 => [
'date' => '2016-01-10',
'client_id' => '2',
'client_type'=> 'natural',
'operation_type' => 'cash_in',
'operation_sum' => '200.00',
'operation_currency' => 'EUR',
],
1 => [
'date' => '2016-01-05',
'client_id' => '1',
'client_type'=> 'legal',
'operation_type' => 'cash_out',
'operation_sum' => '300.00',
'operation_currency' => 'EUR',
],
2 => [
'date' => '2016-01-11',
'client_id' => '1',
'client_type'=> 'natural',
'operation_type' => 'cash_out',
'operation_sum' => '30000',
'operation_currency' => 'JPY'
]
];
$expected = [
0 => [
'date' => '2016-01-05',
'client_id' => '2',
'client_type'=> 'natural',
'operation_type' => 'cash_in',
'operation_sum' => '200.00',
'operation_currency' => 'EUR',
],
1 => [
'date' => '2016-01-10',
'client_id' => '1',
'client_type'=> 'legal',
'operation_type' => 'cash_out',
'operation_sum' => '300.00',
'operation_currency' => 'EUR',
],
2 => [
'date' => '2016-01-11',
'client_id' => '1',
'client_type'=> 'natural',
'operation_type' => 'cash_out',
'operation_sum' => '30000',
'operation_currency' => 'JPY'
]
];
$um = new CommissionDataParser();
$result = $um->groupOrdersByWeek($orders);
$this->assertEquals($expected, $result, '**** -->>>>> result array wrong');
}
there is function that i want to test: i put small part of this class, for example
namespace AppBundle\Parser;
class CommissionDataParser
{
public function getData($file)
{
$orders = $this->extractOrders($file);
if (is_array($orders)) {
$orders = $this->groupOrdersByWeek($orders);
}
// ...
}
public function extractOrders($file)
{
$orders = [];
$data = [];
//$lines = explode(PHP_EOL, file_get_contents($file));
if (($handle = fopen($file, "r")) !== FALSE) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($row);
if ($num !== 6) {
return 'Badly structured file';
} else if ($num == 0) {
return 'file is empty';
}
$data[] = $row;
}
fclose($handle);
}
foreach ($data as $row)
{
$orders[] = [
'date' => $row[0],
'client_id' => $row[1],
'client_type' => $row[2],
'operation_type' => $row[3],
'operation_sum' => $row[4],
'operation_currency' => $row[5]
];
}
return $orders;
}
In first, you must check that your phpunit uses app/autoload.php as bootstrap. Open your phpunit.xml.dist file in your project root, and find this line:
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.8/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="app/autoload.php"
>
If u see this line bootstrap="app/autoload.php" in your file, then all right.
Next, check that your file CommissionDataParser.php physically located in this directory AppBundle\Parser. Full path to this file must be YOUR_PROJECT_ROOT\src\AppBundle\Parser\CommissionDataParser.php
If you did everything correctly then it should work. At least I was able to run your code.
yes really have :) i take a picture for example : )

Resources