flohw
11/14/2016 - 4:07 PM

SyncUserCommand.php

{
    "require": {
        "mailjet/mailjet-apiv3-php": "^1.1"
        // ...
    }
}
<?php

namespace AppBundle\Command;

use AppBundle\Entity\User;
use Mailjet\Client;
use Mailjet\Resources;
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 SyncUserCommand
 * Sync users in a mailjet contact list
 *
 * @package AppBundle\Command
 */
class SyncUserCommand extends ContainerAwareCommand
{
    /**
     * @var Client
     */
    private $mailjet;

    /**
     * @var \Doctrine\ORM\EntityManagerInterface
     */
    private $em;

    /**
     * @var int
     */
    private $list;

    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        $this
            ->setName('app:user:sync')
            ->setDescription('Synchronize users with mailjet contact list')
            ->addArgument('list', InputArgument::REQUIRED, 'List ID to synchronize with');
    }

    /**
     * {@inheritDoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var User[] $users */
        $users = $this->em->getRepository(User::class)->findAll();
        $body = [
            'Action' => 'addnoforce',
            'Contacts' => [],
        ];
        foreach ($users as $user) {
            $body['Contacts'][] = [
                'Email' => $user->getEmail(),
                'Name' => (string) $user,
                'Properties' => [
                    'nom' => $user->getLastName(),
                    'prenom' => $user->getFirstName(),
                    'nb_commandes' => $user->getOrderCount(),
                ],
            ];
        }

        $response = $this->mailjet->post(Resources::$ContactslistManagemanycontacts, ['id' => $this->list, 'body' => $body]);
        if ($response->success()) {
            $this->processJob($response->getData()[0]['JobID'], $output);
        }
    }

    /**
     * Treat job content
     *
     * @param int             $jobId
     * @param OutputInterface $output
     */
    private function processJob($jobId, OutputInterface $output)
    {
        $response = $this->mailjet->get(Resources::$ContactslistManagemanycontacts, ['id' => $this->list, 'actionid' => $jobId]);
        $status = $response->getData()[0]['Status'];
        switch ($status) {
            case 'Error':
                $response = $this->mailjet->get(Resources::$BatchjobJsonerror, ['id' => $jobId]);
                foreach ($response->getBody()['Contacts'] as $contact) {
                    $output->writeln(sprintf('<comment>Contact "<info>%s</info>" contains error : </comment><error>%s</error>', $contact['Name'], $contact['Error']));
                }
                break;
        }
    }

    /**
     * {@inheritDoc}
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $this->mailjet = new Client(
            $this->getContainer()->getParameter('mailjet.api_key'),
            $this->getContainer()->getParameter('mailjet.api_secret')
        );
        $this->em = $this->getContainer()->get('doctrine')->getManager();
        $this->list = $input->getArgument('list');
    }
}