Entity example

<?php declare(strict_types=1);

use Shopware\Core\Framework\DataAbstractionLayer\Entity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;

use function PHPStan\Testing\assertType;

$collection = new EntityCollection(['foo' => new Entity()]);

if ($collection->has('foo')) {
    assertType(Entity::class$collection->get('foo'));
    assertType(Entity::class D '|null', $collection->get('bar'));
} else {
    assertType('null', $collection->get('foo'));
    assertType(Entity::class D '|null', $collection->get('bar'));
}
$this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
      ->disableOriginalConstructor()
      ->getMock();
    $this->display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
      ->disableOriginalConstructor()
      ->getMock();
    $this->stylePlugin = $this->getMockBuilder('Drupal\views\Plugin\views\style\StylePluginBase')
      ->disableOriginalConstructor()
      ->getMock();
    $this->executable->style_plugin = $this->stylePlugin;

    $this->entityHandler = new Entity([], 'entity', ['entity_type' => 'entity_test']$this->entityTypeManager, $this->entityRepository, $this->entityDisplayRepository);

    $this->display->expects($this->any())
      ->method('getPlugin')
      ->with('style')
      ->willReturn($this->stylePlugin);
    $this->executable->expects($this->any())
      ->method('getStyle')
      ->willReturn($this->stylePlugin);

    $token = $this->getMockBuilder('Drupal\Core\Utility\Token')
      ->disableOriginalConstructor()
      
            static::assertContains(\strtolower($column)$existing, 'Column ' . $column . ' not found in table ' . $table . ': ' . \print_r($existing, true));
        }
    }

    private function testCreateFromXml(): void
    {
        $entities = CustomEntityXmlSchema::createFromXmlFile(__DIR__ . '/_fixtures/custom-entity-test/Resources/entities.xml');

        $expected = new CustomEntityXmlSchema(
            __DIR__ . '/_fixtures/custom-entity-test/Resources',
            new Entities([
                new Entity([
                    'name' => 'custom_entity_blog',
                    'fields' => [
                        new IntField(['name' => 'position', 'storeApiAware' => true]),
                        new FloatField(['name' => 'rating', 'storeApiAware' => true]),
                        new StringField(['name' => 'title', 'storeApiAware' => true, 'required' => true, 'translatable' => true]),
                        new TextField(['name' => 'content', 'storeApiAware' => true, 'allowHtml' => true, 'translatable' => true]),
                        new BoolField(['name' => 'display', 'storeApiAware' => true, 'translatable' => true]),
                        new JsonField(['name' => 'payload', 'storeApiAware' => false]),
                        new EmailField(['name' => 'email', 'storeApiAware' => false]),
                        new PriceField(['name' => 'price', 'storeApiAware' => false]),
                        new DateField(['name' => 'my_date', 'storeApiAware' => false]),
                        
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\IdGenerator\UlidGenerator;
use Symfony\Component\Uid\Factory\UlidFactory;
use Symfony\Component\Uid\Ulid;

class UlidGeneratorTest extends TestCase
{
    public function testUlidCanBeGenerated()
    {
        $em = (new \ReflectionClass(EntityManager::class))->newInstanceWithoutConstructor();
        $generator = new UlidGenerator();
        $ulid = $generator->generate($emnew Entity());

        $this->assertInstanceOf(Ulid::class$ulid);
        $this->assertTrue(Ulid::isValid($ulid));
    }

    public function testUlidFactory()
    {
        $ulid = new Ulid('00000000000000000000000000');
        $em = (new \ReflectionClass(EntityManager::class))->newInstanceWithoutConstructor();
        $factory = $this->createMock(UlidFactory::class);
        $factory->expects($this->any())
            
private const CLASSNAME = Entity::class;

    public function testInvalidPropertyName()
    {
        $this->expectException(ValidatorException::class);

        new GetterMetadata(self::CLASSNAME, 'foobar');
    }

    public function testGetPropertyValueFromPublicGetter()
    {
        $entity = new Entity('foobar');
        $metadata = new GetterMetadata(self::CLASSNAME, 'internal');

        $this->assertEquals('foobar from getter', $metadata->getPropertyValue($entity));
    }

    public function testGetPropertyValueFromOverriddenPublicGetter()
    {
        $entity = new Entity();
        $metadata = new GetterMetadata(self::CLASSNAME, 'data');

        $this->assertEquals('Overridden data', $metadata->getPropertyValue($entity));
    }
use Symfony\Component\Uid\Factory\UuidFactory;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Uid\UuidV6;

class UuidGeneratorTest extends TestCase
{
    public function testUuidCanBeGenerated()
    {
        $em = (new \ReflectionClass(EntityManager::class))->newInstanceWithoutConstructor();
        $generator = new UuidGenerator();
        $uuid = $generator->generate($emnew Entity());

        $this->assertInstanceOf(Uuid::class$uuid);
    }

    public function testCustomUuidfactory()
    {
        $uuid = new UuidV4();
        $em = (new \ReflectionClass(EntityManager::class))->newInstanceWithoutConstructor();
        $factory = $this->createMock(UuidFactory::class);
        $factory->expects($this->any())
            ->method('create')
            
private const PARENTCLASS = EntityParent::class;

    public function testInvalidPropertyName()
    {
        $this->expectException(ValidatorException::class);

        new PropertyMetadata(self::CLASSNAME, 'foobar');
    }

    public function testGetPropertyValueFromPrivateProperty()
    {
        $entity = new Entity('foobar');
        $metadata = new PropertyMetadata(self::CLASSNAME, 'internal');

        $this->assertEquals('foobar', $metadata->getPropertyValue($entity));
    }

    public function testGetPropertyValueFromOverriddenPrivateProperty()
    {
        $entity = new Entity('foobar');
        $metadata = new PropertyMetadata(self::PARENTCLASS, 'data');

        $this->assertTrue($metadata->isPublic($entity));
        
$this->createMock(EntityWriteGatewayInterface::class),
            $this->createMock(EventDispatcherInterface::class),
            $serializer,
            $this->createMock(DefinitionInstanceRegistry::class),
            $this->createMock(VersionCommitDefinition::class),
            $this->createMock(VersionCommitDataDefinition::class),
            $this->createMock(VersionDefinition::class),
            $this->createMock(LockFactory::class)
        );

        $entityCollectionMock = new EntityCollection([
            (new Entity())->assign(['_uniqueIdentifier' => Uuid::randomHex()]),
        ]);

        $entityReaderMock->expects(static::once())->method('read')->willReturn($entityCollectionMock);
        $serializer->expects(static::once())->method('serialize')
            ->willReturn('{"extensions":{"foreignKeys":{"extensions":[],"apiAlias":null,"manyToOneId":"' . Uuid::randomHex() . '"}}}');

        $writeContextMock = $this->createMock(WriteContext::class);

        $writeContextMockWithVersionId = $this->createMock(WriteContext::class);
        $writeContextMock->expects(static::once())->method('createWithVersionId')->willReturn($writeContextMockWithVersionId);

        
$this->assertSame('Message %param%', $violations[0]->getMessageTemplate());
        $this->assertSame(['%param%' => 'value']$violations[0]->getParameters());
        $this->assertSame('', $violations[0]->getPropertyPath());
        $this->assertSame('Bernhard', $violations[0]->getRoot());
        $this->assertSame('Bernhard', $violations[0]->getInvalidValue());
        $this->assertNull($violations[0]->getPlural());
        $this->assertNull($violations[0]->getCode());
    }

    public function testClassConstraint()
    {
        $entity = new Entity();

        $callback = function D$value, ExecutionContextInterface $context) use ($entity) {
            $this->assertSame($this::ENTITY_CLASS, $context->getClassName());
            $this->assertNull($context->getPropertyName());
            $this->assertSame('', $context->getPropertyPath());
            $this->assertSame('Group', $context->getGroup());
            $this->assertSame($this->metadata, $context->getMetadata());
            $this->assertSame($entity$context->getRoot());
            $this->assertSame($entity$context->getValue());
            $this->assertSame($entity$value);

            
public function testChangeWithPriceFacade(): void
    {
        $ids = new IdsCollection([
            'default' => Defaults::CURRENCY,
            'usd' => Uuid::randomHex(),
        ]);

        $price = $this->rampUpPriceFacade($ids, 'default', CartPrice::TAX_STATE_GROSS);

        $price->change(
            new PriceFacade(
                new Entity(),
                new CalculatedPrice(5, 5, new CalculatedTaxCollection()new TaxRuleCollection()),
                $this->createMock(ScriptPriceStubs::class),
                $this->createMock(SalesChannelContext::class)
            )
        );

        static::assertEquals(5, $price->getUnit());
    }

    public function testChangeWithNullFacade(): void
    {
        
$this->executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
      ->disableOriginalConstructor()
      ->getMock();
    $this->display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
      ->disableOriginalConstructor()
      ->getMock();

    $definition = [
      'entity_type' => 'entity_test',
    ];

    $this->argumentValidator = new Entity([], 'entity_test', $definition$this->entityTypeManager, $this->entityTypeBundleInfo);
  }

  /** * Tests the validate argument method with no access and bundles. * * @see \Drupal\views\Plugin\views\argument_validator\Entity::validateArgument() */
  public function testValidateArgumentNoAccess() {
    $options = [];
    $options['access'] = FALSE;
    $options['bundles'] = [];
    
$this->buildViolation('myMessage')
            ->setParameter('{{ value }}', '""')
            ->setCode(Expression::EXPRESSION_FAILED_ERROR)
            ->assertRaised();
    }

    public function testSucceedingExpressionAtObjectLevel()
    {
        $constraint = new Expression('this.data == 1');

        $object = new Entity();
        $object->data = '1';

        $this->setObject($object);

        $this->validator->validate($object$constraint);

        $this->assertNoViolation();
    }

    public function testFailingExpressionAtObjectLevel()
    {
        
$price->change(new PriceCollection([
            new Price(Defaults::CURRENCY, 2, 2, false),
        ]));

        static::assertInstanceOf(QuantityPriceDefinition::class$item->getPriceDefinition());
        static::assertEquals(2, $item->getPriceDefinition()->getPrice());
        static::assertNull($item->getPrice());
    }

    public function testChangesAreAppliedDirectlyForEntities(): void
    {
        $item = new Entity();
        $original = new CalculatedPrice(1, 1, new CalculatedTaxCollection()new TaxRuleCollection());
        $stubs = $this->createMock(ScriptPriceStubs::class);
        $stubs->method('calculateQuantity')->willReturn(new CalculatedPrice(2, 2, new CalculatedTaxCollection()new TaxRuleCollection()));

        $price = new PriceFacade($item$original$stubs$this->createMock(SalesChannelContext::class));

        $price->change(new PriceCollection([
            new Price(Defaults::CURRENCY, 2, 2, false),
        ]));

        static::assertEquals(2, $original->getUnitPrice());
    }
Home | Imprint | This part of the site doesn't use cookies.