Skip to content

Commit

Permalink
[TranslatorBundle]: Allow importing translations from an external xls…
Browse files Browse the repository at this point in the history
…x, ods, csv file. (#1585)

refactor importtranslationsfromfilecommand

add button in admin to import from file
  • Loading branch information
Numkil authored and sandergo90 committed Apr 27, 2018
1 parent 887bd56 commit b300f99
Show file tree
Hide file tree
Showing 11 changed files with 326 additions and 45 deletions.
Expand Up @@ -11,7 +11,11 @@

/**
* @final since 5.1
* @deprecated since 5.1
* NEXT_MAJOR extend from `Command` and remove `$this->getContainer` usages
* NEXT_MAJOR file will be renamed
*
* Class ImportTranslationsFromCodeCommand
*/
class ImportTranslationsCommand extends ContainerAwareCommand
{
Expand All @@ -38,6 +42,9 @@ public function __construct(/* ImportCommandHandler */ $importCommandHandler = n
$this->importCommandHandler = $importCommandHandler;
}

/**
* Configures this command.
*/
protected function configure()
{
$this
Expand All @@ -51,6 +58,12 @@ protected function configure()
;
}

/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$force = $input->getOption('force');
Expand All @@ -73,6 +86,5 @@ protected function execute(InputInterface $input, OutputInterface $output)
$imported = $this->importCommandHandler->executeImportCommand($importCommand);

$output->writeln(sprintf("Translation imported: %d", $imported));

}
}
@@ -0,0 +1,76 @@
<?php

namespace Kunstmaan\TranslatorBundle\Command;

use Kunstmaan\TranslatorBundle\Service\Command\Importer\Importer;
use Kunstmaan\TranslatorBundle\Service\Translator\Translator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Translation\TranslatorInterface;

/**
* Class ImportTranslationsFromFileCommand
*/
final class ImportTranslationsFromFileCommand extends Command
{
/** @var Importer */
private $importer;

/** @var TranslatorInterface */
private $translator;

/** @var array */
private $locales;

/**
* ImportTranslationsFromFileCommand constructor.
* @param Importer $importer
* @param Translator $translator
* @param $locales
*/
public function __construct(Importer $importer, TranslatorInterface $translator, $locales)
{
parent::__construct();
$this->importer = $importer;
$this->translator = $translator;
$this->locales = explode('|', $locales);
}

/**
* Configures this command
*/
protected function configure()
{
$this
->setName('kuma:translator:import-file')
->setDescription('Import file with translations, supported formats are xlsx, ods, csv')
->addArgument('file', InputArgument::REQUIRED, 'The full path of the file')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Force import, overwrite all existing database entries');
}

/**
* @throws LogicException
*
* @param InputInterface $input
* @param OutputInterface $output
*
* @return void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$file = $input->getArgument('file');
$force = $input->getOption('force');

$this->importer->importFromSpreadsheet($file, $this->locales, $force);
if($force) {
$confirmation = $this->translator->trans('kuma_translator.command.import.flash.force_success');
} else {
$confirmation = $this->translator->trans('kuma_translator.command.import.flash.success');
}
$output->writeln($confirmation);
}
}
111 changes: 77 additions & 34 deletions src/Kunstmaan/TranslatorBundle/Controller/TranslatorController.php
Expand Up @@ -10,15 +10,16 @@
use Kunstmaan\TranslatorBundle\AdminList\TranslationAdminListConfigurator;
use Kunstmaan\TranslatorBundle\Entity\Translation;
use Kunstmaan\TranslatorBundle\Form\TranslationAdminType;
use Kunstmaan\TranslatorBundle\Form\TranslationsFileUploadType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Translation\TranslatorInterface;

Expand Down Expand Up @@ -57,24 +58,23 @@ public function indexAction(Request $request)
);
}

return array(
return [
'adminlist' => $adminList,
'adminlistconfigurator' => $configurator
);
'adminlistconfigurator' => $configurator,
];
}

/**
* The add action
*
* @Route("/add", name="KunstmaanTranslatorBundle_settings_translations_add")
* @Method({"GET", "POST"})
* @Template("KunstmaanTranslatorBundle:Translator:addTranslation.html.twig")
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param Request $request
* @param string $keyword
* @param string $domain
* @param string $locale
* @return array|RedirectResponse
* @throws \Doctrine\ORM\OptimisticLockException
*
* @Route("/add", name="KunstmaanTranslatorBundle_settings_translations_add")
* @Method({"GET", "POST"})
* @Template("KunstmaanTranslatorBundle:Translator:addTranslation.html.twig")
*/
public function addAction(Request $request, $keyword = '', $domain = '', $locale = '')
{
Expand All @@ -89,7 +89,7 @@ public function addAction(Request $request, $keyword = '', $domain = '', $locale
$translation->addText($locale, '');
}

$form = $this->createForm(TranslationAdminType::class, $translation, array('csrf_token_id' => 'add'));
$form = $this->createForm(TranslationAdminType::class, $translation, ['csrf_token_id' => 'add']);
if ('POST' == $request->getMethod()) {
$form->handleRequest($request);

Expand All @@ -115,15 +115,15 @@ public function addAction(Request $request, $keyword = '', $domain = '', $locale

return new RedirectResponse($this->generateUrl(
$indexUrl['path'],
isset($indexUrl['params']) ? $indexUrl['params'] : array()
isset($indexUrl['params']) ? $indexUrl['params'] : []
));
}
}

return array(
return [
'form' => $form->createView(),
'adminlistconfigurator' => $configurator
);
'adminlistconfigurator' => $configurator,
];
}

/**
Expand All @@ -144,7 +144,7 @@ public function editAction(Request $request, $id)
$configurator = $this->getAdminListConfigurator();


$translations = $em->getRepository('KunstmaanTranslatorBundle:Translation')->findBy(array('translationId' => $id));
$translations = $em->getRepository('KunstmaanTranslatorBundle:Translation')->findBy(['translationId' => $id]);
if (count($translations) < 1) {
throw new \InvalidArgumentException('No existing translations found for this id');
}
Expand All @@ -166,7 +166,7 @@ public function editAction(Request $request, $id)
}
}

$form = $this->createForm(TranslationAdminType::class, $translation, array('intention' => 'edit'));
$form = $this->createForm(TranslationAdminType::class, $translation, ['intention' => 'edit']);

if ('POST' == $request->getMethod()) {
$form->handleRequest($request);
Expand All @@ -185,47 +185,84 @@ public function editAction(Request $request, $id)

return new RedirectResponse($this->generateUrl(
$indexUrl['path'],
isset($indexUrl['params']) ? $indexUrl['params'] : array()
isset($indexUrl['params']) ? $indexUrl['params'] : []
));
}
}

return array(
return [
'form' => $form->createView(),
'translation' => $translation,
'adminlistconfigurator' => $configurator
);
'adminlistconfigurator' => $configurator,
];
}

/**
* @Route("upload", name="KunstmaanTranslatorBundle_settings_translations_upload")
* @Method({"POST", "GET"})
* @Template("KunstmaanTranslatorBundle:Translator:addTranslation.html.twig")
*
* @param Request $request
* @return array
*/
public function uploadFileAction(Request $request)
{
/** @var FormBuilderInterface $uploadForm */
$form = $this->createForm(TranslationsFileUploadType::class);
$configurator = $this->getAdminListConfigurator();

if (Request::METHOD_POST === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$locales = explode('|', $this->getParameter('requiredlocales'));
$data = $form->getData();
$file = $data['file'];
$force = $data['force'];
$imported = $this->get('kunstmaan_translator.service.importer.importer')->importFromSpreadsheet($file, $locales, $force);
$this->addFlash(FlashTypes::SUCCESS, sprintf("Translation imported: %d", $imported));
}
}

return [
'form' => $form->createView(),
'adminlistconfigurator' => $configurator,
];
}

/**
* @param $domain
* @param $locale
* @param $keyword
* @return RedirectResponse
*
* @Method({"GET"})
*/
public function editSearchAction($domain, $locale, $keyword)
{
$configurator = $this->getAdminListConfigurator();
$em = $this->getDoctrine()->getManager();
$translation = $em->getRepository('KunstmaanTranslatorBundle:Translation')->findOneBy(
array('domain' => $domain, 'keyword' => $keyword, 'locale' => $locale)
['domain' => $domain, 'keyword' => $keyword, 'locale' => $locale]
);

if ($translation === null) {
$addUrl = $configurator->getAddUrlFor(
array('domain' => $domain, 'keyword' => $keyword, 'locale' => $locale)
['domain' => $domain, 'keyword' => $keyword, 'locale' => $locale]
);

return new RedirectResponse($this->generateUrl($addUrl['path'], $addUrl['params']));
}

$editUrl = $configurator->getEditUrlFor(array('id' => $translation->getId()));
$editUrl = $configurator->getEditUrlFor(['id' => $translation->getId()]);

return new RedirectResponse($this->generateUrl($editUrl['path'], $editUrl['params']));
}

/**
* @param $id
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
* @throws NotFoundHttpException
*
* @Route("/{id}/delete", requirements={"id" = "\d+"}, name="KunstmaanTranslatorBundle_settings_translations_delete")
* @Method({"GET", "POST"})
*/
Expand All @@ -239,9 +276,12 @@ public function deleteAction(Request $request, $id)
$em->getRepository('KunstmaanTranslatorBundle:Translation')->removeTranslations($id);
}

return new RedirectResponse($this->generateUrl($indexUrl['path'], isset($indexUrl['params']) ? $indexUrl['params'] : array()));
return new RedirectResponse($this->generateUrl($indexUrl['path'], isset($indexUrl['params']) ? $indexUrl['params'] : []));
}

/**
* @param $adminListConfigurator
*/
public function setAdminListConfigurator($adminListConfigurator)
{
$this->adminListConfigurator = $adminListConfigurator;
Expand All @@ -255,14 +295,17 @@ public function getAdminListConfigurator()
$locales = $this->container->getParameter('kuma_translator.managed_locales');

if (!isset($this->adminListConfigurator)) {
$this->adminListConfigurator = new TranslationAdminListConfigurator($this->getDoctrine()->getManager()
->getConnection(), $locales);
$this->adminListConfigurator = new TranslationAdminListConfigurator($this->getDoctrine()->getConnection(), $locales);
}

return $this->adminListConfigurator;
}


/**
* @param Request $request
* @return JsonResponse|Response
*
* @Route("/inline-edit", name="KunstmaanTranslatorBundle_settings_translations_inline_edit")
* @Method({"POST"})
*/
Expand All @@ -275,7 +318,7 @@ public function inlineEditAction(Request $request)
throw $this->createAccessDeniedException('Not allowed to edit this translation');
}

$id = isset($values['pk']) ? (int) $values['pk'] : 0;
$id = isset($values['pk']) ? (int)$values['pk'] : 0;
$em = $this->getDoctrine()->getManager();
/**
* @var TranslatorInterface $translator
Expand All @@ -302,10 +345,10 @@ public function inlineEditAction(Request $request)
$em->persist($translation);
$em->flush();

return new JsonResponse(array(
'success' => true,
'uid' => $translation->getId()
), 200);
return new JsonResponse([
'success' => true,
'uid' => $translation->getId(),
], 200);
} catch (\Exception $e) {
return new Response($translator->trans('translator.translator.fatal_error_occurred'), 500);
}
Expand Down
Expand Up @@ -28,6 +28,9 @@ public function load(array $configs, ContainerBuilder $container)
return;
}

if(!$container->hasParameter('requiredlocales')) {
$container->setParameter('requiredlocales', ['nl', 'fr', 'en']);
}
$container->setParameter('kuma_translator.enabled', $config['enabled']);
$container->setParameter('kuma_translator.default_bundle', $config['default_bundle']);
$container->setParameter('kuma_translator.bundles', $config['bundles']);
Expand Down

0 comments on commit b300f99

Please sign in to comment.