Skip to content

Commit

Permalink
Add event to allow custom object creation on import
Browse files Browse the repository at this point in the history
  • Loading branch information
MisatoTremor committed Aug 10, 2022
1 parent 3331023 commit 4a08a5d
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
49 changes: 49 additions & 0 deletions Event/CreateObjectEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

/*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Avro\CsvBundle\Event;

use Symfony\Contracts\EventDispatcher\Event;

/**
* @author Steffen Roßkamp <[email protected]>
*/
class CreateObjectEvent extends Event
{
protected $object;
protected string $class;

/**
* @psalm-param class-string $class
*/
public function __construct(string $class)
{
$this->class = $class;
}

public function setObject(?object $object): void
{
$this->object = $object;
}

/**
* Get the doctrine object if set.
*/
public function getObject(): ?object
{
return $this->object;
}

/**
* @return string
* @psalm-return class-string
*/
public function getClass(): string
{
return $this->class;
}
}
8 changes: 7 additions & 1 deletion Import/Importer.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Avro\CaseBundle\Util\CaseConverter;
use Avro\CsvBundle\Event\AssociationFieldEvent;
use Avro\CsvBundle\Event\CreateObjectEvent;
use Avro\CsvBundle\Event\CustomFieldEvent;
use Avro\CsvBundle\Event\RowAddedEvent;
use Avro\CsvBundle\Event\RowErrorEvent;
Expand Down Expand Up @@ -191,7 +192,12 @@ private function convertToFormFieldName($input): string
private function addRow($row, $fields, $andFlush = true): bool
{
// Create new entity
$entity = new $this->class();
$event = new CreateObjectEvent($this->class);
$this->dispatcher->dispatch($event);
$entity = $event->getObject();
if (null === $entity) {
$entity = new $this->class();
}
// Loop through fields and set to row value
foreach ($fields as $k => $v) {
if ($this->metadata->hasField(lcfirst($v))) {
Expand Down

0 comments on commit 4a08a5d

Please sign in to comment.