Please note that this service is under alpha statement, we are actively working on it. It may be unstable and might completely change without warning. Help us by reporting!
diff --git a/Admin/ImportableAdminTrait.php b/Admin/ImportableAdminTrait.php
index f26c266e60c362e717d54f89c554205d5a5d5205..bb4cec1a034a89bfade9af1e7548764251690e76 100644
--- a/Admin/ImportableAdminTrait.php
+++ b/Admin/ImportableAdminTrait.php
@@ -1,21 +1,30 @@
<?php
+/*
+ * This file is part of the Sonata Project package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Sigmapix\Sonata\ImportBundle\Admin;
-use Symfony\Bridge\Doctrine\Form\Type\EntityType;
+use Port\Steps\Step\ValueConverterStep;
+use Port\Steps\StepAggregator;
+use Port\ValueConverter\DateTimeValueConverter;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
-use Symfony\Component\Form\Form;
-use Symfony\Component\HttpFoundation\File\UploadedFile;
-use Symfony\Component\HttpFoundation\Request;
+use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
+use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\HttpFoundation\File\UploadedFile;
+use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
-use Port\Steps\StepAggregator;
-use Port\Steps\Step\ValueConverterStep;
-use Port\ValueConverter\DateTimeValueConverter;
trait ImportableAdminTrait
{
@@ -24,15 +33,6 @@ trait ImportableAdminTrait
*/
private $importForm;
- protected function configureRoutes(RouteCollection $collection)
- {
- /* @var AbstractAdmin $this */
- $collection
- ->add('import', 'upload/{fileName}')
- ->add('upload')
- ;
- }
-
/**
* {@inheritdoc}
*/
@@ -42,7 +42,7 @@ trait ImportableAdminTrait
$this->formOptions['data_class'] = $this->getClass();
$formBuilder = $this->getFormContractor()->getFormBuilder(
- "import_form", $this->formOptions
+ 'import_form', $this->formOptions
);
$this->defineImportFormBuilder($formBuilder, $headers);
@@ -50,15 +50,6 @@ trait ImportableAdminTrait
return $formBuilder;
}
- protected function buildImportForm(array $headers)
- {
- if ($this->importForm) {
- return;
- }
-
- $this->importForm = $this->getImportFormBuilder($headers)->getForm();
- }
-
// todo: use defineFormBuilder for import Action and upload Action
public function defineImportFormBuilder(FormBuilderInterface $formBuilder, array $headers)
@@ -69,31 +60,33 @@ trait ImportableAdminTrait
$trans = $this->getConfigurationPool()->getContainer()->get('translator');
$oldValue = ini_get('mbstring.substitute_character');
- ini_set('mbstring.substitute_character', "none");
+ ini_set('mbstring.substitute_character', 'none');
foreach ($formBuilder as $field) {
/* @var FormBuilder $field */
- if ($field->getType()->getInnerType() instanceof EntityType) continue;
+ if ($field->getType()->getInnerType() instanceof EntityType) {
+ continue;
+ }
if ($field->getPropertyPath() && $field->getPropertyPath()->getLength() > 1) {
$mapper->add(
- (string)$field->getPropertyPath(), 'choice', array(
- 'choices' => $headers,
- 'data' => $this->nearest($field->getOption("label"), $headers, $trans),
+ (string) $field->getPropertyPath(), 'choice', [
+ 'choices' => $headers,
+ 'data' => $this->nearest($field->getOption('label'), $headers, $trans),
'mapped' => false,
- 'label' => $field->getOption("label")
- ));
- } else if ((string)$field->getPropertyPath() === 'id') {
- $mapper->add($field->getName(), 'choice', array(
- 'choices' => $headers,
- 'data' => $this->nearest($field->getOption("label"), $headers, $trans),
+ 'label' => $field->getOption('label'),
+ ]);
+ } elseif ('id' === (string) $field->getPropertyPath()) {
+ $mapper->add($field->getName(), 'choice', [
+ 'choices' => $headers,
+ 'data' => $this->nearest($field->getOption('label'), $headers, $trans),
'mapped' => false,
- 'label' => $field->getOption("label")
- ));
+ 'label' => $field->getOption('label'),
+ ]);
} else {
- $mapper->add($field->getName(), 'choice', array(
- 'choices' => $headers,
- 'data' => $this->nearest($field->getOption("label"), $headers, $trans),
- 'label' => $field->getOption("label")
- ));
+ $mapper->add($field->getName(), 'choice', [
+ 'choices' => $headers,
+ 'data' => $this->nearest($field->getOption('label'), $headers, $trans),
+ 'label' => $field->getOption('label'),
+ ]);
}
}
ini_set('mbstring.substitute_character', $oldValue);
@@ -106,9 +99,9 @@ trait ImportableAdminTrait
{
$buttonList = parent::configureActionButtons($admin, $object);
- $buttonList['import'] = array(
+ $buttonList['import'] = [
'template' => 'SigmapixSonataImportBundle:Button:import_button.html.twig',
- );
+ ];
return $buttonList;
}
@@ -121,44 +114,18 @@ trait ImportableAdminTrait
return $this->importForm;
}
- private function nearest($input, $words, $trans)
- {
- // TODO $input should be the $field, to try both 'name' and 'propertyPath' attributes
- $closest = "";
- $shortest = -1;
-
- foreach ($words as $word) {
- $wordASCII = mb_convert_encoding($word, 'ASCII');
- $lev = levenshtein($input, $wordASCII);
- $levCase = levenshtein(strtolower($input), strtolower($wordASCII));
- $levTrans = levenshtein($trans->trans($input), $wordASCII);
- $lev = min([$lev, $levCase, $levTrans]);
- if ($lev === 0) {
- $closest = $word;
- $shortest = 0;
- break;
- }
- if ($lev <= $shortest || $shortest < 0) {
- $closest = $word;
- $shortest = $lev;
- }
- }
-
- return $closest;
- }
-
public function configureImportSteps(StepAggregator $workflow)
- {
+ {
$dateTimeFields = [];
foreach ($this->importForm as $f) {
-
+
/** @var Form $f */
/** @var FieldDescription $fieldOptions */
- $fieldOptions = $f->getConfig()->getOption('sonata_field_description');
- if ($fieldOptions && ($fieldOptions->getMappingType() === 'datetime'|| $fieldOptions->getMappingType() === 'date')) {
+ $fieldOptions = $f->getConfig()->getOption('sonata_field_description');
+ if ($fieldOptions && ('datetime' === $fieldOptions->getMappingType() || 'date' === $fieldOptions->getMappingType())) {
$dateTimeFields[] = $f->getName();
- }
- }
+ }
+ }
$converter = new DateTimeValueConverter('d/m/Y');
$converterStep = new ValueConverterStep();
foreach ($dateTimeFields as $dateTimeField) {
@@ -166,7 +133,6 @@ trait ImportableAdminTrait
}
$workflow->addStep($converterStep);
-
}
/**
@@ -174,7 +140,7 @@ trait ImportableAdminTrait
* It's called from importAction.
*
* @param Request $request
- * @param Form $form
+ * @param Form $form
*
* @return Response|null
*/
@@ -186,14 +152,58 @@ trait ImportableAdminTrait
* This method can be overloaded in your Admin service.
* It's called from importAction.
*
- * @param Request $request
- * @param UploadedFile $file
- * @param Form $form
- * @param mixed $results
+ * @param Request $request
+ * @param UploadedFile $file
+ * @param Form $form
+ * @param mixed $results
*
* @return Response|null
*/
public function postImport(Request $request, UploadedFile $file, Form $form, $results)
{
}
+
+ protected function configureRoutes(RouteCollection $collection)
+ {
+ /* @var AbstractAdmin $this */
+ $collection
+ ->add('import', 'upload/{fileName}')
+ ->add('upload')
+ ;
+ }
+
+ protected function buildImportForm(array $headers)
+ {
+ if ($this->importForm) {
+ return;
+ }
+
+ $this->importForm = $this->getImportFormBuilder($headers)->getForm();
+ }
+
+ private function nearest($input, $words, $trans)
+ {
+ // TODO $input should be the $field, to try both 'name' and 'propertyPath' attributes
+ $closest = '';
+ $shortest = -1;
+
+ foreach ($words as $word) {
+ $wordASCII = mb_convert_encoding($word, 'ASCII');
+ $lev = levenshtein($input, $wordASCII);
+ $levCase = levenshtein(strtolower($input), strtolower($wordASCII));
+ $levTrans = levenshtein($trans->trans($input), $wordASCII);
+ $lev = min([$lev, $levCase, $levTrans]);
+ if (0 === $lev) {
+ $closest = $word;
+ $shortest = 0;
+ break;
+ }
+ if ($lev <= $shortest || $shortest < 0) {
+ $closest = $word;
+ $shortest = $lev;
+ }
+ }
+
+ return $closest;
+ }
}
diff --git a/Controller/CRUDController.php b/Controller/CRUDController.php
index 407679779c4550e0db7b5e3b325f9f8cd0f8f9f6..980a2fe5f6df82314654f0416069c4726f2ec8bf 100644
--- a/Controller/CRUDController.php
+++ b/Controller/CRUDController.php
@@ -1,5 +1,14 @@
<?php
+/*
+ * This file is part of the Sonata Project package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Sigmapix\Sonata\ImportBundle\Controller;
use Doctrine\DBAL\Exception\ConstraintViolationException;
@@ -11,24 +20,8 @@ use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
-use Doctrine\Common\Inflector\Inflector;
-use Psr\Log\LoggerInterface;
-use Psr\Log\NullLogger;
-use Sonata\AdminBundle\Admin\AdminInterface;
-use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
-use Sonata\AdminBundle\Exception\LockException;
-use Sonata\AdminBundle\Exception\ModelManagerException;
-use Sonata\AdminBundle\Util\AdminObjectAclData;
-use Sonata\AdminBundle\Util\AdminObjectAclManipulator;
-use Symfony\Component\DependencyInjection\ContainerInterface;
-use Symfony\Component\Form\FormView;
-use Symfony\Component\HttpFoundation\JsonResponse;
-use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
-use Symfony\Component\HttpKernel\Exception\HttpException;
-use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
-use Symfony\Component\Security\Csrf\CsrfToken;
class CRUDController extends Controller
{
@@ -37,10 +30,10 @@ class CRUDController extends Controller
*
* @param Request $request
*
- * @return Response
- *
* @throws AccessDeniedException If access is not granted
* @throws \RuntimeException If the export format is invalid
+ *
+ * @return Response
*/
public function exportAction(Request $request)
{
@@ -83,7 +76,8 @@ class CRUDController extends Controller
);
}
- $defaultHeaders = array_map(function(){return "";},$this->admin->getExportFields());
+ $defaultHeaders = array_map(function () {return ''; }, $this->admin->getExportFields());
+
return $exporter->getResponse(
$format,
$filename,
@@ -98,7 +92,7 @@ class CRUDController extends Controller
$admin = $this->admin;
// todo: $admin->checkAccess('import');
- $admin->setFormTabs(array('default'=>array('groups' => array())));
+ $admin->setFormTabs(['default' => ['groups' => []]]);
$formBuilder = $this->createFormBuilder();
$formBuilder
->add('importFile', FileType::class)
@@ -116,17 +110,18 @@ class CRUDController extends Controller
$fileName = md5(uniqid());
$file->move($this->getParameter('import_directory'), $fileName);
- return $this->redirect($admin->generateUrl('import', array('fileName' => $fileName)));
+
+ return $this->redirect($admin->generateUrl('import', ['fileName' => $fileName]));
}
}
// todo: show an error message if the form failed validation
}
- return $this->render('SigmapixSonataImportBundle:CRUD:base_import_form.html.twig', array(
+ return $this->render('SigmapixSonataImportBundle:CRUD:base_import_form.html.twig', [
'action' => 'upload',
'form' => $form->createView(),
- 'object' => null
- ), null);
+ 'object' => null,
+ ], null);
}
public function importAction(Request $request)
@@ -142,7 +137,7 @@ class CRUDController extends Controller
$fileName = $request->get('fileName');
if (!empty($fileName)) {
try {
- $file = new UploadedFile($this->getParameter('import_directory') . $fileName, $fileName);
+ $file = new UploadedFile($this->getParameter('import_directory').$fileName, $fileName);
$headers = $is->getHeaders($file);
@@ -152,28 +147,25 @@ class CRUDController extends Controller
if ($form->isSubmitted()) {
if ($form->isValid()) {
-
$preResponse = $admin->preImport($request, $form);
- if ($preResponse !== null) {
+ if (null !== $preResponse) {
return $preResponse;
}
try {
-
- $results = $is->import($file, $form, $admin);
+ $results = $is->import($file, $form, $admin);
$postResponse = $admin->postImport($request, $file, $form, $results);
- if ($postResponse !== null) {
+ if (null !== $postResponse) {
return $postResponse;
}
- $this->addFlash("success", "message_success"); // todo: show a success message
-
+ $this->addFlash('success', 'message_success'); // todo: show a success message
} catch (ConstraintViolationException $constraintViolationException) {
- $this->addFlash("error", $constraintViolationException->getMessage()); // todo: show an error message
+ $this->addFlash('error', $constraintViolationException->getMessage()); // todo: show an error message
} catch (\Exception $exception) {
- $this->addFlash("error", $exception->getMessage()); // todo: show an error message
+ $this->addFlash('error', $exception->getMessage()); // todo: show an error message
}
return $this->redirect($admin->generateUrl('list'));
@@ -183,14 +175,13 @@ class CRUDController extends Controller
} catch (FileException $e) {
// TODO: show an error message if the file is missing
}
- } else {
- // todo: show an error message if the fileName is missing
}
+ // todo: show an error message if the fileName is missing
- return $this->render('SigmapixSonataImportBundle:CRUD:base_import_form.html.twig', array(
+ return $this->render('SigmapixSonataImportBundle:CRUD:base_import_form.html.twig', [
'action' => 'import',
'form' => $form->createView(),
- 'object' => null
- ), null);
+ 'object' => null,
+ ], null);
}
-}
\ No newline at end of file
+}
diff --git a/DependencyInjection/Compiler/OverrideServiceCompilerPass.php b/DependencyInjection/Compiler/OverrideServiceCompilerPass.php
index 89f0a07f664ab66411cd8f75533eb4c70ecf57ee..fd65f226edf555b4f4d9c40b4e843abb62abe7e0 100644
--- a/DependencyInjection/Compiler/OverrideServiceCompilerPass.php
+++ b/DependencyInjection/Compiler/OverrideServiceCompilerPass.php
@@ -1,5 +1,14 @@
<?php
+/*
+ * This file is part of the Sonata Project package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Sigmapix\Sonata\ImportBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
@@ -10,5 +19,6 @@ class OverrideServiceCompilerPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('sonata.admin.exporter');
- $definition->setClass('Sigmapix\Sonata\ImportBundle\Export\Exporter'); }
-}
\ No newline at end of file
+ $definition->setClass('Sigmapix\Sonata\ImportBundle\Export\Exporter');
+ }
+}
diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php
index 39355fa25a39bbd00139a28fe6532a67884dcb88..a9e1ebbc78687a10703a423e7e2432d1442714ce 100644
--- a/DependencyInjection/Configuration.php
+++ b/DependencyInjection/Configuration.php
@@ -1,5 +1,14 @@
<?php
+/*
+ * This file is part of the Sonata Project package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Sigmapix\Sonata\ImportBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
@@ -8,7 +17,7 @@ use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
- * {@inheritDoc}
+ * {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
@@ -17,4 +26,4 @@ class Configuration implements ConfigurationInterface
return $treeBuilder;
}
-}
\ No newline at end of file
+}
diff --git a/DependencyInjection/SigmapixSonataImportExtension.php b/DependencyInjection/SigmapixSonataImportExtension.php
index 9596d88731eac3f758ff8742cb37d0f39232e449..1526a9201561d0032666a77c02f34965d4c1df90 100644
--- a/DependencyInjection/SigmapixSonataImportExtension.php
+++ b/DependencyInjection/SigmapixSonataImportExtension.php
@@ -1,11 +1,20 @@
<?php
+/*
+ * This file is part of the Sonata Project package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Sigmapix\Sonata\ImportBundle\DependencyInjection;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
-use Symfony\Component\HttpKernel\DependencyInjection\Extension;
+use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
+use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class SigmapixSonataImportExtension extends Extension
{
@@ -21,4 +30,4 @@ class SigmapixSonataImportExtension extends Extension
$loader->load('services.yml');
$loader->load('config.yml');
}
-}
\ No newline at end of file
+}
diff --git a/Export/Exporter.php b/Export/Exporter.php
index 5b8fd944ce7dbc964a9314cf146fe49c537153bb..6b668ee64256ff8231961de8232917993e385f0e 100644
--- a/Export/Exporter.php
+++ b/Export/Exporter.php
@@ -1,5 +1,14 @@
<?php
+/*
+ * This file is part of the Sonata Project package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Sigmapix\Sonata\ImportBundle\Export;
use Exporter\Source\SourceIteratorInterface;
@@ -8,7 +17,6 @@ use Exporter\Writer\JsonWriter;
use Exporter\Writer\XlsWriter;
use Exporter\Writer\XmlWriter;
use Symfony\Component\HttpFoundation\StreamedResponse;
-use Sigmapix\Sonata\ImportBundle\Export\Handler;
@trigger_error(
'The '.__NAMESPACE__.'\Exporter class is deprecated since version 3.1 and will be removed in 4.0.'.
@@ -22,12 +30,12 @@ use Sigmapix\Sonata\ImportBundle\Export\Handler;
class Exporter
{
/**
- * @throws \RuntimeException
- *
* @param string $format
* @param string $filename
* @param SourceIteratorInterface $source
*
+ * @throws \RuntimeException
+ *
* @return StreamedResponse
*/
public function getResponse($format, $filename, SourceIteratorInterface $source)
@@ -52,15 +60,15 @@ class Exporter
default:
throw new \RuntimeException('Invalid format');
}
-
+
$callback = function () use ($source, $writer) {
$handler = Handler::create($source, $writer);
$handler->export();
};
- return new StreamedResponse($callback, 200, array(
+ return new StreamedResponse($callback, 200, [
'Content-Type' => $contentType,
'Content-Disposition' => sprintf('attachment; filename="%s"', $filename),
- ));
+ ]);
}
}
diff --git a/Export/Handler.php b/Export/Handler.php
index f3098a9bf01862c0ff165651a079fbfff46a5e48..48be5a1f042f16a9f020c12c39cf48997aee91c2 100644
--- a/Export/Handler.php
+++ b/Export/Handler.php
@@ -1,8 +1,16 @@
<?php
+/*
+ * This file is part of the Sonata Project package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Sigmapix\Sonata\ImportBundle\Export;
-use Exporter\Source\DoctrineORMQuerySourceIterator;
use Exporter\Source\SourceIteratorInterface;
use Exporter\Writer\WriterInterface;
diff --git a/Service/ImportService.php b/Service/ImportService.php
index 7c66300cca0a68827cee871889c8316cd85fe987..6e9c0aecba5af319c976a217383f12598c51df60 100644
--- a/Service/ImportService.php
+++ b/Service/ImportService.php
@@ -1,32 +1,34 @@
<?php
+/*
+ * This file is part of the Sonata Project package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Sigmapix\Sonata\ImportBundle\Service;
+use Doctrine\ORM\EntityManagerInterface;
use Port\Csv\CsvReader;
use Port\Doctrine\DoctrineWriter;
use Port\Excel\ExcelReader;
-use Port\Steps\Step\ValueConverterStep;
use Port\Steps\StepAggregator;
-use Port\ValueConverter\DateTimeValueConverter;
-use Doctrine\ORM\EntityManagerInterface;
-use Sonata\DoctrineORMAdminBundle\Admin\FieldDescription;
use Sonata\AdminBundle\Admin\AdminInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\SubmitButton;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
-use Port\Steps\Step\ConverterStep;
-use AppBundle\Entity\Residence;
-use AppBundle\Entity\Family;
-use AppBUndle\Entity\Building;
final class ImportService
{
/**
* @var EntityManagerInterface
*/
- protected $em;
+ private $em;
/**
* @var SessionInterface
@@ -45,10 +47,11 @@ final class ImportService
/**
* ImportService constructor.
+ *
* @param EntityManagerInterface $em
* @param $session
* @param ContainerInterface $container
- * @param string $doctrineWriterClass
+ * @param string $doctrineWriterClass
*/
public function __construct(EntityManagerInterface $em, $session, ContainerInterface $container, string $doctrineWriterClass)
{
@@ -60,39 +63,44 @@ final class ImportService
/**
* @param UploadedFile $file
+ *
* @return array
*/
public function getHeaders(UploadedFile $file)
{
$reader = $this->getReader($file);
- $columnHeaders = array_filter($reader->getColumnHeaders(),function($h){return !is_null($h);} );
- $columnHeaders = array_map(function($h){return trim($h);}, $columnHeaders);
+ $columnHeaders = array_filter($reader->getColumnHeaders(), function ($h) {return null !== $h; });
+ $columnHeaders = array_map(function ($h) {return trim($h); }, $columnHeaders);
$headers = array_flip($columnHeaders);
- array_walk($headers, function(&$v, $k) use ($headers) { $v = $k; });
+ array_walk($headers, function (&$v, $k) use ($headers) { $v = $k; });
+
return $headers;
}
/**
- * @param UploadedFile $file
- * @param Form $form
+ * @param UploadedFile $file
+ * @param Form $form
* @param AdminInterface $admin
+ *
* @return mixed
*/
public function import(UploadedFile $file, Form $form, AdminInterface $admin)
{
-
$mapping = [];
foreach ($form as $f) {
- if ($f instanceof SubmitButton) continue;
+ if ($f instanceof SubmitButton) {
+ continue;
+ }
$mapping[$f->getName()] = $f->getNormData();
}
$reader = $this->getReader($file);
// Replace columnsHeader names with entity field name in our $mapping
- $columnHeaders = array_map(function($h) use ($mapping) {
+ $columnHeaders = array_map(function ($h) use ($mapping) {
$k = array_search(trim($h), (array) $mapping, true);
- return ($k === false ? $h : $k);
+
+ return false === $k ? $h : $k;
}, $reader->getColumnHeaders());
$reader->setColumnHeaders($columnHeaders);
@@ -102,24 +110,48 @@ final class ImportService
$writer->setContainer($this->container);
}
$writer->disableTruncate();
-
+
$workflow = new StepAggregator($reader);
- $workflow->addWriter($writer);
- $admin->configureImportSteps($workflow);
-
+ $workflow->addWriter($writer);
+ $admin->configureImportSteps($workflow);
+
$result = $workflow->process();
+
return $result;
}
/**
+ * Get session.
+ *
+ * @return
+ */
+ public function getSession()
+ {
+ return $this->session;
+ }
+
+ /**
+ * Set session.
+ *
+ * @return $this
+ */
+ public function setSession($session)
+ {
+ $this->session = $session;
+
+ return $this;
+ }
+
+ /**
* @param UploadedFile $file
+ *
* @return CsvReader|ExcelReader
*/
private function getReader(UploadedFile $file)
{
$pathFile = $file->getRealPath();
$fileExtension = $file->guessExtension();
- $excelExtensions = array('xls', 'xlsx', 'zip');
+ $excelExtensions = ['xls', 'xlsx', 'zip'];
if (in_array($fileExtension, $excelExtensions)) {
$reader = new ExcelReader(new \SplFileObject($pathFile), 0, 0);
@@ -130,23 +162,4 @@ final class ImportService
return $reader;
}
-
- /**
- * Get session
- * @return
- */
- public function getSession()
- {
- return $this->session;
- }
-
- /**
- * Set session
- * @return $this
- */
- public function setSession($session)
- {
- $this->session = $session;
- return $this;
- }
}
diff --git a/SigmapixSonataImportBundle.php b/SigmapixSonataImportBundle.php
index 68243b75f45c94df9f30ddcbc1fd2c7afe9a96a7..e69683d877d1e6f5e349d253a4b3ec8c9f4eb353 100644
--- a/SigmapixSonataImportBundle.php
+++ b/SigmapixSonataImportBundle.php
@@ -1,5 +1,14 @@
<?php
+/*
+ * This file is part of the Sonata Project package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Sigmapix\Sonata\ImportBundle;
use Sigmapix\Sonata\ImportBundle\DependencyInjection\Compiler\OverrideServiceCompilerPass;
@@ -8,7 +17,6 @@ use Symfony\Component\HttpKernel\Bundle\Bundle;
class SigmapixSonataImportBundle extends Bundle
{
-
public function build(ContainerBuilder $container)
{
parent::build($container);