<?php

namespace AppBundle\Command;

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

/**
 * Met à jour le slug des menus d'après leur titre
 */
class GenerateMenuSlugCommand extends ContainerAwareCommand
{
    /**
     * 
     */
    protected function configure()
    {
        $this
            ->setName('cgenial:generate:menuslug')
            ->setDescription("Mise à jour des slugs des menus d'après leur titre");
    }

    /**
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get("doctrine.orm.entity_manager");
        $slugify = new Slugify();

        $menus = $em->getRepository('AppBundle:Menu')->findAll();

        foreach ($menus as $menu) {
            $title = $menu->getTitle();
            $slugOld = $menu->getSlug();
            $slugNew = $slugify->slugify($title);

            $menu->setSlug($slugNew);
            $em->persist($menu);

            $output->writeln('('.$menu->getId().') '.$slugOld. ' => '.$slugNew);
        }

        $em->flush();
    }
}
