Convert Bundle:Controller:Filename to actual file path - symfony

Is there a way to convert Symfony filename notation Bundle:Controller:Filename to a real file path /var/www/whatever/src/Bundle/Resources/views/Controller/Filename?

Tak a look at this question: Resolve local file path from Twig template name . Accepted answer says:
"If you want to retrieve path from a controller you can use this code:
$parser = $this->container->get('templating.name_parser');
$locator = $this->container->get('templating.locator');
$path = $locator->locate($parser->parse('AcmeProjectBundle::home.html.twig'));
For more info take a look at code of:
Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser::parse
Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator::locate
"

Related

Add Color Scheme JSON list to Scss file in Angular 8 Environment

I'm building a Web based project with Angular 8. At the starting of the Application, I need to retrieve a list of predefined colour scheme defined in a JSON file and I have to add them dynamically to the Application. The colour scheme JSON looks like as below:
{
"bar": "#FFFFFF",
"text_small": "#FFFFFF",
"text_nav_header": "#FFFFFF"
............ ...........
........... ...........
}
I have gone through few links as below but somehow I'm missing the point to import this JSON to the SCSS processing.
https://scotch.io/tutorials/angular-shortcut-to-importing-styles-files-in-components
https://medium.com/#dmitriy.borodiy/easy-color-theming-with-scss-bc38fd5734d1
https://css-tricks.com/making-sass-talk-to-javascript-with-json/
https://www.viget.com/articles/sharing-data-between-sass-and-javascript-with-json/
Please refer to the below link that I want to achieve with SCSS
Sample code with gist on SassMeister.
Can somebody through some light that what I'm missing here? Also, I'm not an expect in CSS but can understand the basic use of the CSS and media queries.
Thanks in Advance
Are you sure that these color variables have to be inside a json file?
If the values are generated: then change the output format to a scss file.
If the values are defined once (or not very often) : copy/paste them to a scss file.
Here are the steps that I work out with the Angular and backend script to achieve it.
After Angular App is started. I downloaded the JSON in the background and written a file with few changes as mentioned below.
Convert the JSON to JSONString.
Add a string ':root' before the JSONString.
In Python:
data = ":root %s" % jsonString
In PHP:
$data = ":root ". $jsonString;
Replace few character in the string as below:
In Python
data = data.replace('\"', '')
data = data.replace(',', ';')
In PHP:
$data = str_replace('\"', '', $data);
$data = str_replace(',', ';', $data);
Write a file to the src folder of the Angular project.
In Python:
f = open("src/themes.scss", "w+")
f.write(data)
f.close()
In PHP:
$fp = fopen('src/themes.scss', 'w');
fwrite($fp, $data);
fclose($fp);
Import the filename.scss in your styles.css file of your Angular project.
#import "themes.scss";
Thus how I have generated the dynamic scss file with a JSON of color codes. It look weird but yes, it works like a charm.
Note: It works in production environment of Angular as well

symfony translation resource path

I can't make my translator to load a resource yams file.
I have a file admin.ru.yml inside AppBundle/Resources/config/translations/
I have in my other bundle the following lines
$translator = new Translator('ru_RU', new MessageSelector());
$translator->addLoader('yaml', new FileLoader());
$translator->addResource('yaml', 'admin.ru.yml', 'ru_RU', 'admin');
$tt = $translator->trans('Category', array(), 'admin');
It does not load the yml file.
I even have specified in my app/config.yml file of the whole application
translator:
paths:
- '%kernel.root_dir%/../src/AppBundle/Resources/config/translations'
but with no result. I tried many paths but can't find the right way. Any suggestions of what am I doing wrong?
you have to rename your file #AppBundle.ru.yml, the file path is not necessary

External environment variable as array

How to set external environment variable as array?
If I have environment variable
SYMFONY__NSQLOOKUPD__HOSTS=["localhost:4161"]
and in config.yml:
socloz_nsq:
lookupd_hosts: %nsqlookupd.hosts%
Then I got an error:
Invalid type for path "socloz_nsq.lookupd_hosts". Expected array, but got string
I've found solution. Here it is:
in config.yml add to the imports section:
imports:
- { resource: parameters.php }
then create parameters.php file at the same directory where config.yml exists, and look at the following example:
<?php
$nsqlookupdhosts = getenv('SYMFONY__NSQLOOKUPD__HOSTS');
$nsqdhosts = getenv('SYMFONY__NSQD__HOSTS');
$container->setParameter('nsqlookupd.hosts.parsed', explode(',', $nsqlookupdhosts));
$container->setParameter('nsqd.hosts.parsed', explode(',', $nsqdhosts));
use comma as delimiter in environment variable (you are not restricted to comma, use any)
SYMFONY__NSQLOOKUPD__HOSTS=localhost:4161,some.server:2222
You can use a built-in "json" environment variable processor to decode a JSON string into an array:
SYMFONY__NSQLOOKUPD__HOSTS='["localhost:4161"]'
$nsqlookupdhosts: '%env(json:SYMFONY__NSQLOOKUPD__HOSTS)%'

php - Is php caching classes before creation?

Background Information:
I'm using Symfony Console Component to write a console application that is wrapped into a Shell object. I wrote a command named console:reload that empties the array of commands from the Application object, and re-adds commands classes listed under certain directory.
This command is run when the shell starts, so, the Application is loaded with the available commands. The classes being loaded are located in a special directory and should follow a simple name rule: <CommandName>Command.php:
// Inside ReloadCommand->execute() method...
$pamperoApp = $this->getApplication();
$pamperoApp->clearCommands();
$namespace = "pampero\\cli\\modules";
foreach(glob(MODULES_DIR . "/*/*Command.php") as $command) {
$class = str_replace(".php", "", $namespace . "\\" . basename(dirname($command)) . "\\" . basename($command));
$this->getApplication()->add(new $class);
}
The autoload provided by Symfony (Composer?) ClassLoader is used:
// Main entry point...
loader = require_once __DIR__ . '/../vendor/autoload.php';
$loader->set('pampero', __DIR__ . '/../..');
I read the code from ClassLoader class and what it does is to store file name path, so no object caching there.
Here's the problem:
I launch the app: php packages.php. The shell appears after ReloadCommand command being executed. A list of available and loaded commands are ready to be used.
If I create a new file, let's say: ExampleCommand.php, and then I type: console:reload, the new command will indeed be added. Now, If I modify the code inside ExampleCommand.php and run console:reload again, the changes made to the class won't take effect.
But that's not all. If I remove the example file, call console:reload, create the file again and run: console:reload the command will be added.
Reading:
I have read APC related things, and before creating new classes I have done things like:
// Prior adding commands in ReloadCommand
apc_clear_cache();
apc_clear_cache('user');
apc_clear_cache('opcode');
Without luck. I've also run apc.php and enabled/disabled apc.enable_cli option. None of those things creates the object represented by the modified file.
So my hints and clues about the problems turns to be classes caching when a file/class is found. But how to avoid that for this special case? I don't want to restart the shell if some extra funcionality is added through classes.
Any ideas?
I will answer my own question as I found a solution.
Ok, clues were fine. The problem was that PHP including a file binds the symbols for later use while parsing the file.
So, I needed some kind of instrospection. After reading/googling/searching for all night, finally I've ended up finding Runkit.
Runkit documentation can be found here. I know that is not the best thing you can do with your code design. But for my project needs, the truth is that Reflection was needed.
Here is the modified code using Runkit:
protected function execute(InputInterface $input, OutputInterface $output)
{
// Gets a reference to the console application and removes all commands
$pamperoApp = $this->getApplication();
$pamperoApp->clearCommands();
// Adds default commands and add this command
$pamperoApp->addCommands($pamperoApp->getDefaultCommands());
$pamperoApp->add($this);
$namespace = "pampero\\cli\\modules";
foreach(glob(MODULES_DIR . "/*/*Command.php") as $filename) {
$className = str_replace(".php", "", $namespace . "\\" . basename(dirname($filename)) . "\\" . basename($filename));
// Do not add this command again. This command shouldn't be modified on-the-fly
if (get_class($this) !== $className) {
$class = new $className();
// Redefines the class definition
runkit_import($filename, RUNKIT_IMPORT_CLASSES | RUNKIT_OVERRIDE_OBJECTS | RUNKIT_IMPORT_OVERRIDE);
$pamperoApp->add($class);
}
}
}

Symfony 2 file upload: guessExtension() doesn't work for .docx files

public function preUpload()
{
if (null !== $this->file) {
$this->path = $this->file->guessExtension();
}
}
This doesn't work for .docx files.
I get a file stored under the name "myfile." -> no extension.
How to handle this?
I think you must use:
getClientOriginalExtension()
because you want to get the extension of the original name not the temporary name that the file has in your server.
http://api.symfony.com/2.4/Symfony/Component/HttpFoundation/File/UploadedFile.html
use
getExtension()
as a fallback?
Symfony API
I found a bug in symfony core files where It was missing a mimeType for the .xls files.
We had the same behaviour: GuessExtension would return null.
My team and I narrowed it down to an array which lists symfony's mime types.
Here is a link to the same solution I answered on another question:
https://stackoverflow.com/a/36435844/3980097
You will find the exact path to MimeTypeExtensionGuesse.php
In your case, the missing mime Type might be:
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
I hope this helps!

Resources