Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix schema creation for self referencing many to many association #537

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 46 additions & 32 deletions src/EventListener/CreateSchemaListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ class CreateSchemaListener implements EventSubscriber

private MetadataFactory $metadataFactory;

/**
* @var string[]
*/
private array $defferedJoinTablesToCreate = [];

public function __construct(AuditManager $auditManager)
{
$this->config = $auditManager->getConfiguration();
Expand All @@ -47,6 +52,7 @@ public function getSubscribedEvents()
{
return [
ToolEvents::postGenerateSchemaTable,
ToolEvents::postGenerateSchema,
];
}

Expand Down Expand Up @@ -99,27 +105,11 @@ public function postGenerateSchemaTable(GenerateSchemaTableEventArgs $eventArgs)
foreach ($cm->associationMappings as $associationMapping) {
if ($associationMapping['isOwningSide'] && isset($associationMapping['joinTable'])) {
if (isset($associationMapping['joinTable']['name'])) {
$joinTable = $schema->getTable($associationMapping['joinTable']['name']);
$revisionJoinTable = $schema->createTable(
$this->config->getTablePrefix().$joinTable->getName().$this->config->getTableSuffix()
);
foreach ($joinTable->getColumns() as $column) {
/* @var Column $column */
$revisionJoinTable->addColumn(
$column->getName(),
$column->getType()->getName(),
['notnull' => false, 'autoincrement' => false]
);
if ($schema->hasTable($associationMapping['joinTable']['name'])) {
$this->createRevisionJoinTableForJoinTable($schema, $associationMapping['joinTable']['name']);
} else {
$this->defferedJoinTablesToCreate[] = $associationMapping['joinTable']['name'];
}
$revisionJoinTable->addColumn($this->config->getRevisionFieldName(), $this->config->getRevisionIdFieldType());
$revisionJoinTable->addColumn($this->config->getRevisionTypeFieldName(), 'string', ['length' => 4]);

$pk = $joinTable->getPrimaryKey();
$pkColumns = null !== $pk ? $pk->getColumns() : [];
$pkColumns[] = $this->config->getRevisionFieldName();
$revisionJoinTable->setPrimaryKey($pkColumns);
$revIndexName = $this->config->getRevisionFieldName().'_'.md5($revisionJoinTable->getName()).'_idx';
$revisionJoinTable->addIndex([$this->config->getRevisionFieldName()], $revIndexName);
}
}
}
Expand All @@ -140,21 +130,14 @@ public function postGenerateSchemaTable(GenerateSchemaTableEventArgs $eventArgs)
$revisionTable->addForeignKeyConstraint($revisionsTable, [$this->config->getRevisionFieldName()], $foreignColumnNames, [], $revisionForeignKeyName);
}

/**
* NEXT_MAJOR: Remove this method.
*
* @deprecated since sonata-project/entity-audit-bundle 1.4, will be removed in 2.0.
*/
public function postGenerateSchema(GenerateSchemaEventArgs $eventArgs): void
{
$schema = $eventArgs->getSchema();
$revisionsTable = $schema->createTable($this->config->getRevisionTableName());
$revisionsTable->addColumn('id', $this->config->getRevisionIdFieldType(), [
'autoincrement' => true,
]);
$revisionsTable->addColumn('timestamp', Types::DATETIME_MUTABLE);
$revisionsTable->addColumn('username', Types::STRING)->setNotnull(false);
$revisionsTable->setPrimaryKey(['id']);
$this->createRevisionsTable($schema);

foreach ($this->defferedJoinTablesToCreate as $defferedJoinTableToCreate) {
$this->createRevisionJoinTableForJoinTable($schema, $defferedJoinTableToCreate);
}
}

/**
Expand Down Expand Up @@ -199,4 +182,35 @@ private function createRevisionsTable(Schema $schema): Table

return $revisionsTable;
}

private function createRevisionJoinTableForJoinTable(Schema $schema, string $joinTableName): void
{
$joinTable = $schema->getTable($joinTableName);
$revisionJoinTableName = $this->config->getTablePrefix().$joinTable->getName().$this->config->getTableSuffix();

if ($schema->hasTable($revisionJoinTableName)) {
return;
}

$revisionJoinTable = $schema->createTable(
$this->config->getTablePrefix().$joinTable->getName().$this->config->getTableSuffix()
);
foreach ($joinTable->getColumns() as $column) {
/* @var Column $column */
$revisionJoinTable->addColumn(
$column->getName(),
$column->getType()->getName(),
['notnull' => false, 'autoincrement' => false]
);
}
$revisionJoinTable->addColumn($this->config->getRevisionFieldName(), $this->config->getRevisionIdFieldType());
$revisionJoinTable->addColumn($this->config->getRevisionTypeFieldName(), 'string', ['length' => 4]);

$pk = $joinTable->getPrimaryKey();
$pkColumns = null !== $pk ? $pk->getColumns() : [];
$pkColumns[] = $this->config->getRevisionFieldName();
$revisionJoinTable->setPrimaryKey($pkColumns);
$revIndexName = $this->config->getRevisionFieldName().'_'.md5($revisionJoinTable->getName()).'_idx';
$revisionJoinTable->addIndex([$this->config->getRevisionFieldName()], $revIndexName);
}
}
83 changes: 83 additions & 0 deletions tests/Fixtures/Relation/BaseSelfReferencingManyToManyEntity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Sonata\EntityAuditBundle\Tests\Fixtures\Relation;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="type", type="string")
* @ORM\DiscriminatorMap({
* "type 1": "Sonata\EntityAuditBundle\Tests\Fixtures\Relation\SelfReferencingManyToManyEntity"
* })
*/
abstract class BaseSelfReferencingManyToManyEntity
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private ?int $id = null;

/**
* @ORM\Column(type="string", name="title")
*/
private string $title;

/**
* @var Collection<int, BaseSelfReferencingManyToManyEntity>
*
* @ORM\ManyToMany(targetEntity="BaseSelfReferencingManyToManyEntity")
* @ORM\JoinTable(
* name="self_referencing_linked_table",
* joinColumns={@ORM\JoinColumn(name="foo_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="bar_id", referencedColumnName="id")}
* )
*/
private Collection $linkedEntities;

public function __construct(string $title)
{
$this->title = $title;
$this->linkedEntities = new ArrayCollection();
}

public function getId(): ?int
{
return $this->id;
}

public function getTitle(): string
{
return $this->title;
}

public function setTitle(string $title): void
{
$this->title = $title;
}

public function addLinkedEntity(self $selfReferencingManyToManyEntity): self
{
if (!$this->linkedEntities->contains($selfReferencingManyToManyEntity)) {
$this->linkedEntities->add($selfReferencingManyToManyEntity);
}

return $this;
}
}
23 changes: 23 additions & 0 deletions tests/Fixtures/Relation/SelfReferencingManyToManyEntity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Sonata\EntityAuditBundle\Tests\Fixtures\Relation;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
*/
class SelfReferencingManyToManyEntity extends BaseSelfReferencingManyToManyEntity
{
}
75 changes: 75 additions & 0 deletions tests/Issue/IssueSelfReferencingManyToManyEntityTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Sonata\EntityAuditBundle\Tests\Issue;

use Sonata\EntityAuditBundle\Tests\BaseTest;
use Sonata\EntityAuditBundle\Tests\Fixtures\Relation\BaseSelfReferencingManyToManyEntity;
use Sonata\EntityAuditBundle\Tests\Fixtures\Relation\SelfReferencingManyToManyEntity;

final class IssueSelfReferencingManyToManyEntityTest extends BaseTest
{
protected $schemaEntities = [
BaseSelfReferencingManyToManyEntity::class,
SelfReferencingManyToManyEntity::class,
];

protected $auditedEntities = [
SelfReferencingManyToManyEntity::class,
];

public function testSelfReferencingManyToManyAssociationWithClassTableInheritanceWorks(): void
{
$entity = new SelfReferencingManyToManyEntity('foo');
$entityTwo = new SelfReferencingManyToManyEntity('xyz');
$entity->addLinkedEntity($entityTwo);

$this->em->persist($entity);
$this->em->persist($entityTwo);
$this->em->flush();

$entityId = $entity->getId();

\assert(\is_int($entityId));

$this->em->clear();

/** @var SelfReferencingManyToManyEntity $entity */
$entity = $this->em->getRepository(SelfReferencingManyToManyEntity::class)->find($entityId);

$entity->setTitle('bar');
$this->em->flush();

$reader = $this->auditManager->createAuditReader($this->em);

$auditEntity = $reader->find(SelfReferencingManyToManyEntity::class, $entityId, 1);
static::assertInstanceOf(SelfReferencingManyToManyEntity::class, $auditEntity);
static::assertSame('foo', $auditEntity->getTitle());

$auditEntity = $reader->find(SelfReferencingManyToManyEntity::class, $entityId, 2);
static::assertInstanceOf(SelfReferencingManyToManyEntity::class, $auditEntity);
static::assertSame('bar', $auditEntity->getTitle());

$this->em->clear();

/** @var SelfReferencingManyToManyEntity $entity */
$entity = $this->em->getRepository(SelfReferencingManyToManyEntity::class)->find($entityId);

$this->em->remove($entity);
$this->em->flush();

$auditEntity = $reader->find(SelfReferencingManyToManyEntity::class, $entityId, 3);
static::assertInstanceOf(SelfReferencingManyToManyEntity::class, $auditEntity);
static::assertSame('bar', $auditEntity->getTitle());
}
}