Symfony: how to customize output of available commands? - symfony

We are building a console application using symfony/console (great library by the way). The available commands show up as such:
Available commands:
check-deps Get a report of resolved and missing (if any) dependencies.
gen-docs Rebuild the API / code documentation
help Displays help for a command
list Lists commands
restart Restart the Nginx and PHP-FPM processes.
show-changes Show all local changes to the source code since the last push.
test Run the unit tests
test-coverage Run the unit tests and include a coverage report.
The name of the command shows up in green and the description shows up in white.
Currently, Available commands is the only section. Is there a simple way using OOP to create multiple sections for commands?
Alternatively, is there a way to change the green color for the command label?

You can create a new section by using colon notation.
$this
->setName('newSection:greet') //<--- This line does the trick
->setDescription('Greet someone')
->addArgument(
'name',
InputArgument::OPTIONAL,
'Who do you want to greet?'
)
->addOption(
'yell',
null,
InputOption::VALUE_NONE,
'If set, the task will yell in uppercase letters'
);
However in that case you need to run your command with new section name added as namespace,
> php app.php newSection:greet Avindra.
If you name your section with a whitespace like "New Section" you need to call your command like,
> php app.php "New Section:greet" Avindra.
And this is how you can change the color of info annotation of the application itself.
#!/usr/bin/env php
<?php
require __DIR__.'/vendor/autoload.php';
use Command\GreetCommand;
use Command\HelloCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
$application = new Application();
$application->add(new GreetCommand());
$application->add(new HelloCommand());
//Create a new OutputFormatter
$formatter = new OutputFormatter();
//Change info annotation color by blue
$formatter->setStyle('info', new OutputFormatterStyle('blue'));
//Construct output interface with new formatter
$output = new ConsoleOutput(OutputInterface::VERBOSITY_NORMAL, null, $formatter);
//Run your application with your new output interface
$application->run(null, $output);
You can check the related source code for more options here;
https://github.com/symfony/Console/blob/5f241906889f0a3e7b1854b42e7c92a0ea8516ce/Formatter/OutputFormatter.php#L51
https://github.com/symfony/Console/blob/b6b351d326e2fb2fe673a808630f938c2881a473/Formatter/OutputFormatterStyle.php#L21
Hope it helps.

Related

Symfony4 how to call a file in public folder?

I need to display a yaml file as an array but i but I can't display it.
I have create a service, and my controller call this service.
In my service i try to call my yaml like this :
$value = Yaml::parseFile('public\assets\organizations.yaml');
return $value;
But that return me that error :
File "public\assets\organizations.yaml" does not exist.
You are specifying the file with a relative path. This will not be resolved relative to the file it is in but relative to the current working directory you are in when executing the script. Since this depends on various factors it will always be troublesome.
Thus you should always use absolute paths. In symfony you can get the base path of your project via the kernel.project_dir configuration parameter.
Your code does not provide enough context to understand how or where you are using it. But if it is inside a controller extending AbstractController you can use getParameter():
$projectDir = $this->getParameter('kernel.project_dir');
$absolutePath = $projectDir . '/public/assets/organizations.yml';
$value = Yaml::parseFile($absolutePath);
return $value;
Also note that using \ as the directory separator won't work under Linux/Unix-like systems where / is used as directory separator!
Since / will work as directory separator under Windows, too, it is easiest to use it for cross-OS compatibility. Alternatively use the DIRECTORY_SEPARATOR constant.

Using a Composer class in functions.php

I'm trying to add a shortcode to my Wordpress site to pull a piece of data from a Google spreadsheet and drop it into a page. To do this, I'm trying to use Sheetsu. The php libraries for Sheetsu are managed through Composer.
I've got a working piece of standalone code, but when I drop it in functions.php, like this...
function do_sheetsu() {
require('vendor/autoload.php');
use Sheetsu\Sheetsu;
$sheetsu = new Sheetsu(['sheetId' => '8b297aa81110']);
$response = $sheetsu->search(['id' => '2.05.1']);
$collection = $response->getCollection();
echo $collection->get(0)->answer;
}
add_shortcode('sheetsu','do_sheetsu');
...it blanks my site. If I comment out the use Sheetsu\Sheetsu; line, my site comes back, but I get no output, and the error "PHP Fatal error: Class 'Sheetsu' not found" which I suppose makes perfectly good sense.
I know enough php to be able to break things, apparently, and my knowledge of Composer comes mostly from messing around with Flarum a little bit.
I'm sure I'm missing something obvious here, I'm guessing involving namespace declarations or something, but I can't put the pieces together.
I'm looking suspiciously at my composer.json file, as well—something doesn't seem right, but I'm not sure what to fix.
For the record, my composer.json, composer.lock, and vendor folder are in my theme folder with functions.php. My composer.json file looks like this:
{
"require": {
"emilianozublena/sheetsu-php": "^0.0.6"
}
}
and I'm not sure it should.
But what's more troubling is finding a way around that use Sheetsu\Sheetsu line that seems to totally break Wordpress...
Thanks for any help!
I assume here you have installed the package using command line running composer install or composer require emilianozublena/sheetsu-php.
You cannot use the use php keyword inside function. The use keyword must be declared in the outermost scope of a file (the global scope). Refer to this answer for more detail here
So, in this condition you can chain the namespace while instantiating your class. In our case new Sheetsu(['sheetId' => '8b297aa81110']) becomes new \Sheetsu\Sheetsu(['sheetId' => '8b297aa81110']);
Try this code below
function do_sheetsu() {
require('vendor/autoload.php');
$sheetsu = new \Sheetsu\Sheetsu(['sheetId' => '8b297aa81110']);
$response = $sheetsu->search(['id' => '2.05.1']);
$collection = $response->getCollection();
echo $collection->get(0)->answer;
}
add_shortcode('sheetsu','do_sheetsu');

Console Clear - Symfony Console Component

I'm writing a console app using Symfony 2 Console Component, and I want to run a console clear command before (or as) the first line of my app.
I have done some research and am struggling to find if this is possible.
I have been looking for similar functionality. There is nothing built-in to the symfony console that can clear the screen as far as I can tell, but you can still achieve the clear behavior by using the escape code for resetting the terminal like so:
$output->write(sprintf("\033\143"));
See the post "Clear the Ubuntu bash screen for real" and "What commands can I use to reset and clear my terminal?" for a more extensive explanation of the codes, and this symfony console pull request, where I got the code from, that attempted to emulate the clear functionality.
As the doc says, you can use something like this:
$kernel = $this->getContainer()->get('kernel');
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput(array(
'command' => 'cache:clear',
));
// You can use NullOutput() if you don't need the output
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
As your are using a command, your command must extends ContainerAwareCommand so you can access the container and your services.

how to use ACL in Symfony2

I am trying to use ACL for my project, I have not done it before. I know only the concepts, what it is and why to use it.
I run this command :
$ php app/console init:acl
and I got five tables in my database .
My question is how to use these tables, means how data will be inserted in these tables .
I also have followed steps from here
and still not getting the hang of it , please help me out .
You should'nt use table directly (but you already know), but ACL Entities instead (but it's tricky).
Some people worked on bunbles to simplify those actions. Here is an example on how to use it :
https://github.com/Problematic/ProblematicAclManagerBundle
$comment = new Comment(); // create some entity
$aclManager = $this->get('problematic.acl_manager');
// Adds a permission no matter what other permissions existed before
$aclManager->addObjectPermission($comment, MaskBuilder::MASK_OWNER, $userEntity);
// Replaces all current permissions with this new one
$aclManager->setObjectPermission($comment, MaskBuilder::MASK_OWNER, $userEntity);
$aclManager->revokePermission($comment, MaskBUILDER::MASK_DELETE, $userEntity);
$aclManager->revokeAllObjectPermissions($comment, $userEntity);
You can apply permission on objects or directly on classes (upper level)

Drupal - Get image from url and import it into node

Im writing a module for drupal, Im trying to create a node from my module, everything is fine , I only have 1 problem with creating an image , The image exist on different server, so I want to grab the page and insert it , I install module http://drupal.org/project/filefield_sources , which has remote option , I search in the module code , I could not find the function that he used for this process, module work very nice from interface , but how i make it do the job from code ? which function should i call and what parameter should i pass .
I'm over Drupal 6.
Hopefully you're using Drupal 7...
The system_retrieve_file() function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file_managed table if you want it to be managed.
$managed = TRUE; // Whether or not to create a Drupal file record
$path = system_retrieve_file($url, 'public://my_files/', $managed);
If you want to get the file object immediately after you've done this, the following is the only way I've found so far:
$file = file_load(db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField());
get fid using $path->fid. no need to mysql

Resources