Pierstoval
8/11/2015 - 1:37 PM

A basic facebook endpoint accessor in command line for Symfony

A basic facebook endpoint accessor in command line for Symfony

Facebook endpoints command for Symfony

Requires facebook SDK with the main service class. Before, it was 4.1.*, but renamed to 5.x.y to use semver

composer require facebook/php-sdk-v4:"~5.0"

Copy FacebookService.php in src/AppBundle/Facebook/ directory.

Copy FacebookEndpointCommand.php in src/AppBundle/Command/ directory.

Add this to your services config:

# app/config/services.yml
services:
    facebook:
        class: AppBundle\Facebook\FacebookService
        arguments:
            - %facebook_app_id%
            - %facebook_app_secret%

And this to your parameters:

# app/config/parameters.yml
# Update your parameters.yml.dist too
parameters:
    # ...
    facebook_app_id:     YourFacebookAppId
    facebook_app_secret: YourFacebookAppSecret

Example

$ php app/console fb:get "/facebook_id_1" "/facebook_id_2" "/facebook_id_3"
> Will show the JSON response of all three users you specified

This can be used to access to any endpoint your app is authorized to get/post.

<?php

namespace AppBundle\Facebook;

use Facebook\Authentication\AccessToken;
use Facebook\Facebook;

class FacebookService extends Facebook
{
    public function __construct($appId, $appSecret)
    {
        parent::__construct(array(
            'app_id'     => $appId,
            'app_secret' => $appSecret,
            'cookie'     => true,
        ));
        $this->setDefaultAccessToken($this->getAccessToken());
    }

    /**
     * @return AccessToken
     */
    public function getAccessToken()
    {
        return $this->getApp()->getAccessToken();
    }
}

<?php

namespace AppBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class FacebookEndpointCommand extends ContainerAwareCommand
{

    protected function configure()
    {
        $this
            ->setName('fb:get')
            ->setDescription('Show raw result from specified end points')
            ->addArgument('end_points', InputArgument::IS_ARRAY);
    }


    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $fb = $this->getContainer()->get('facebook');

        $endPoints = $input->getArgument('end_points');

        if (count($endPoints)) {
            foreach ($endPoints as $endPoint) {
                $output->writeln('Accessing end point <comment>'.$endPoint.'</comment>');
                $output->writeln(json_encode(json_decode($fb->get($endPoint, $fb->getAccessToken())->getBody()), 480));
            }
            return 0;
        }

        return 1;
    }
}