Passing custom-header arguments to Knp SnappyBundle - php

I'm using Knp SnappyBundle in Symfony 4.
I'm having trouble passing the custom-header argument (--custom-header <name> <value>) to wkhtmltopdf through yaml or as option in request.
Here is what I'm trying, which seems to fail:
knp_snappy:
temporary_folder: "%kernel.cache_dir%/snappy"
pdf:
enabled: true
binary: xvfb-run wkhtmltopdf
options:
- { name: 'custom-header', value: '%app_auth_header_name%' '%app_auth_header_token%' }
I've also tried passing the values as an array, but that also fails.

I have solved it partially, unfortunately not by yaml, but direcly in code example:
public function getPdfBinary($url, Pdf $pdfService): PdfResponse
{
$url = urldecode($url);
$res = new PdfResponse($pdfService->getOutput($url, ['custom-header' =>
[ 'X-Authorization' => 'mytoken' ] ]),'output.pdf');
return $res;
yaml expect scalar value of custom-header...

Related

Symfony generatUrl problem .... must match "[^/]++" ("my string with special chars" given) to generate a corresponding URL."

I am trying to use the google indexer api with symfony and therefore i need to generate the same URLs dynamically from my job-entity (in the database) like i am already using in the frontend.
My controller function looks (reduced) like this
/**
*
* #Route({
* "de": "/profile/{name}-{id}/career/{jobname}-{jobid}",
* }, name="somename")
*/
public function detailfunction($name, $id, $jobname, $jobid)
{ // some code
}
In my frontend i get the following url rendered by twig (path function):
https://www.mydomain.xy/profile/This+is+a+company+name-23/career/Worker+Montage+%2528mwd%2529-135
So now i need to send the exact same url to google so it updates the index whenever this page is modified.
I try to generate this url in the controller of my "google indexer" function like this:
$job = $this->getDoctrine()->getRepository(Jobs::class)->findBy(....);
$url = $this->generateUrl('somename', array('name' => $job->getCompany()->getName(),
'id' => $job->getCompany()->getid(),
'jobname" => $job->getTitle(),
'jobid' => $job->getId()));
// Debug
echo $url;
Unfortunately it outputs "ERROR : Parameter "jobname" for route "somename" must match "[^/]++" ("Worker Montage (m/w/d)" given) to generate a corresponding URL"
So it doesn´t encode the data that comes from the database for the url generator. I have been wondering how symfony (or twig as well) actually encodes internally but i am completely lost and very thankful for a hint.
Although i am still not sure of how exactly symfony / twig encodes the url, i wrote a small workaround function and call it before passing it to the generateURL function.
array('name' => $this->urlcleaner($job->getCompany()->getName()),
'id' => $job->getCompany()->getId(),
private function urlcleaner($string){
$string = preg_replace('/[^A-Za-z0-9\-ığşçöüÖÇŞİıĞ()\/]/', ' ', $string);
$string = str_replace("/","",$string);
$string = str_replace("-","",$string);
$string = urlencode($string);
return $string;
}

Overwrite Environment Variable Params with export BEHAT_PARAMS

I am trying to use environment-variable-behat-params to overwrite the following value in my YAML:
my_profile:
suites:
domain:
contexts:
- MyContext:
- my_config:
setting_setting: data
other_setting_setting: other_data
This is the export command:
export BEHAT_PARAMS='{"suites":{"domain":{"contexts":{"MyContext":{"my_config":{"my_setting":"on"}}}}}}'
And this is the PHP code:
/** #BeforeSuite */
public static function prepare(BeforeSuiteScope $scope) {
$my_settings = $scope->getEnvironment()
->getContextClassesWithArguments()['MyContext'][0];
if (isset($my_settings['my_setting']) && $my_settings['my_setting'] == 'on') {
//do something here
}
}
It seems to match the documentation, but my_setting remains off instead of being updated to on.
If I try to use a key which is at the root level of my_profile like this:
my_profile:
my_config:
setting_setting: data
With this is the export command:
export BEHAT_PARAMS='{"my_config":{"my_setting":"on"}}'
Then I get this error:
In ArrayNode.php line 311:
[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
Unrecognized option "my_settings" under "testwork"
Exception trace:
Symfony\Component\Config\Definition\ArrayNode->normalizeValue() at /sites/scorecards/vendor/symfony/config/Definition/BaseNode.php:368
Symfony\Component\Config\Definition\BaseNode->normalize() at /sites/scorecards/vendor/symfony/config/Definition/Processor.php:35
Symfony\Component\Config\Definition\Processor->process() at /sites/scorecards/vendor/behat/behat/src/Behat/Testwork/ServiceContainer/ContainerLoader.php:81
Behat\Testwork\ServiceContainer\ContainerLoader->processConfig() at /sites/scorecards/vendor/behat/behat/src/Behat/Testwork/ServiceContainer/ContainerLoader.php:65
Behat\Testwork\ServiceContainer\ContainerLoader->load() at /sites/scorecards/vendor/behat/behat/src/Behat/Testwork/Cli/Application.php:185
Behat\Testwork\Cli\Application->createContainer() at /sites/scorecards/vendor/behat/behat/src/Behat/Testwork/Cli/Application.php:161
Behat\Testwork\Cli\Application->createCommand() at /sites/scorecards/vendor/behat/behat/src/Behat/Testwork/Cli/Application.php:122
Behat\Testwork\Cli\Application->doRun() at /sites/scorecards/vendor/symfony/console/Application.php:148
Symfony\Component\Console\Application->run() at /sites/scorecards/vendor/behat/behat/bin/behat:34
.. how can I fix this?
you just need to remove my_setting from your yaml file
because it super-cedes any environment variable
from the documentation link you provided
in order to specify a parameter in an environment variable, the value must not exist in your behat.yml

Maatwerk Excel Laravel how to set CSV EXPORT delimeter?

Hi i'm using Maatwerk Excel laravel package to export data to XLSX and CSV.
In 2 instances a comma is good.
But now i need to make a CSV where the delimeter is not a comma but something different (a tab or pipe symbol).
I cannot find where to set this.
I tried:
Config::set('Excel::csv.delimeter','|');
Excel::create('CSV Products', function($excel) use ($exports_arr) {
$excel->setTitle('Products');
$excel->setCreator('Me')->setCompany('My company');
$excel->setDescription('Products');
$excel->sheet('sheet1', function($sheet) use ($exports_arr) {
$sheet->fromArray($exports_arr, null, 'A1', false, false);
});
})->download('csv');
But if i look in the config/Excel.php file the comments suggest that this delimeter is only for reading.
Is it even possible to change the Delimeter for EXPORTING CSV files?
Thanks in advance.
The comment states that excel.csv.delimiter is used for reading out a csv file, but in Writers/LaravelExcelWriter.php (line 578) the CSV delimiter is taken from the config, and set as , by default:
$this->writer->setDelimiter(config('excel.csv.delimiter', ','));
Are you sure the Config::set statement works properly?
Try to use:
Config::set('excel.csv.delimeter','|');
and check the value with
Config::get('excel.csv.delimeter');
UPDATE:
As mentioned in this answer, the service provider is registered before the request takes place. Updating the config key during the request won't affect the value that is read earlier by Maatwerk/Excel. A solution is given in the answer, by creating a deferred provider.
I know this is a bit outdated but I was having the same problem recently.
In order to set a custom delimiter while exporting multiple CSV files, you can create a new instance of the use Maatwebsite\Excel\Excel class without using the facade.
Try this:
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Writer;
use Maatwebsite\Excel\QueuedWriter;
use Maatwebsite\Excel\Reader;
...
$reader = new Reader(app()->make('filesystem'));
$writer = new Writer;
$queued_writer = new QueuedWriter($writer);
$writer->setDelimiter('|');
$excel = new Excel($writer, $queued_writer, $reader, app()->make('filesystem'));
$excel->create( ... );
An update on this question: If you are using Laravel Excel 3, you can set it in the config/excel.php file:
return [
'exports' => [
'csv' => [
'delimiter' => '|',
]
]
]
Or if you want to set it dynamically:
\Config::set('excel.exports.csv.delimiter', '|');
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
use Maatwebsite\Excel\Concerns\WithCustomQuerySize;
class MyExportClass implements FromView, WithCustomQuerySize, WithCustomCsvSettings
{
use Exportable;
public string $filePath;
public string $disk;
public function getCsvSettings(): array
{
return [
'delimiter' => ",",
];
}
....
}
From documentation:
enter link description here

Pass Arguments To Extension

The desired result is:
class SomeExtension extends Extension{
public static function add_to_class($class, $extensionClass, $args = null){
//$args = ["some_key"=>"some value"];
}
}
My config.yml is (incorrectly formatted) like so:
SomeClass:
extensions:
- SomeExtension
some_key: "some value"
This yml doesn't parse, but is it possible to inject args into an extension like this? I can't find any documentation on how to use the 3rd parameter of Extension::add_to_class
You can pass the arguments in parentheses, like so:
SomeClass:
extensions:
- "SomeExtension('arg1','arg2')"

Mustache php gettext()

I am experimenting with kostache, "mustache for kohana framework".
Is there any way I can use simple PHP functions in mustache template files.
I know logic and therefore methods are against logic-less design principle, but I'm talking about very simple functionality.
For example:
gettext('some text') or __('some text')
get the base url; in kohana -> Url::site('controller/action')
Bobthecow is working on an experimental feature that will allow you to call a function as a callback.
Check out the higher-order-sections branch of the repository and the ticket to go with it.
You could use "ICanHaz" http://icanhazjs.com/
and then you can declare your mustache templates as
<script id="welcome" type="text/html">
<p>Welcome, {{<?php echo __('some text') ?>}}! </p>
</script>
Well, you can do this now with Bobthecow's implementation of Mustache Engine. We need anonymous functions here, which are passed to the Template Object along with other data.
Have a look at the following example:
<?php
$mustache = new Mustache_Engine;
# setting data for our template
$template_data = [
'fullname' => 'HULK',
'bold_it' => function($text){
return "<b>{$text}</b>";
}
];
# preparing and outputting
echo $mustache->render("{{#bold_it}}{{fullname}}{{/bold_it}} !", $template_data);
In the above example, 'bold_it' points to our function which is pasalong withwith other data to our template. The value of 'fullname' is being passed as a parameter to this function.
Please note that passing parameters is not mandatory in Mustache. You can even call the php function wothout any parameters, as follows:
<?php
# setting data for our template
$template_data = [
'my_name' => function(){
return 'Joe';
}
];
# preparing and outputting
echo $mustache->render("{{my_name}} is a great guy!", $template_data); # outputs: Joe is a great guy!
Credits: http://dwellupper.io/post/24/calling-php-functions-for-data-in-mustache-php

Categories