refs #451. Testing hardwareType

pull/7/head
Manuel Aranda Rosales 2024-06-18 16:38:14 +02:00
parent f746f435e4
commit 579d5284b6
10 changed files with 446 additions and 6 deletions

View File

@ -0,0 +1,31 @@
resources:
App\Entity\HardwareType:
processor: App\State\Processor\HardwareTypeProcessor
input: App\Dto\Input\HardwareTypeInput
output: App\Dto\Output\HardwareTypeOutput
normalization_context:
groups: ['default', 'hardware-type:read']
denormalization_context:
groups: ['hardware-type:write']
operations:
ApiPlatform\Metadata\GetCollection:
provider: App\State\Provider\HardwareTypeProvider
filters:
- 'api_platform.filter.hardware_type.order'
- 'api_platform.filter.hardware_type.search'
ApiPlatform\Metadata\Get:
provider: App\State\Provider\HardwareTypeProvider
ApiPlatform\Metadata\Put:
provider: App\State\Provider\HardwareTypeProvider
ApiPlatform\Metadata\Patch:
provider: App\State\Provider\HardwareTypeProvider
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
properties:
App\Entity\HardwareType:
id:
identifier: false
uuid:
identifier: true

View File

@ -66,6 +66,11 @@ services:
$itemProvider: '@api_platform.doctrine.orm.state.item_provider'
App\State\Provider\OperativeSystemProvider:
bind:
$collectionProvider: '@api_platform.doctrine.orm.state.collection_provider'
$itemProvider: '@api_platform.doctrine.orm.state.item_provider'
App\State\Provider\HardwareTypeProvider:
bind:
$collectionProvider: '@api_platform.doctrine.orm.state.collection_provider'
$itemProvider: '@api_platform.doctrine.orm.state.item_provider'

View File

@ -3,6 +3,7 @@
namespace App\Dto\Input;
use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\HardwareTypeOutput;
use App\Entity\Hardware;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
@ -20,8 +21,7 @@ final class HardwareInput
#[Groups(['hardware:write'])]
#[ApiProperty(description: 'The type of the hardware', example: "Server")]
public ?string $type = null;
public ?HardwareTypeOutput $type = null;
public function __construct(?Hardware $hardware = null)
{
@ -31,7 +31,7 @@ final class HardwareInput
$this->name = $hardware->getName();
$this->description = $hardware->getDescription();
$this->type = $hardware->getType();
$this->type = new HardwareTypeOutput($hardware->getType());
}
public function createOrUpdateEntity(?Hardware $hardware = null): Hardware
@ -42,7 +42,7 @@ final class HardwareInput
$hardware->setName($this->name);
$hardware->setDescription($this->description);
$hardware->setType($this->type);
$hardware->setType($this->type->getEntity());
return $hardware;
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Dto\Input;
use App\Entity\HardwareType;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
class HardwareTypeInput
{
#[Assert\NotBlank]
#[Groups(['hardware-type:read'])]
public ?string $name = null;
public function __construct(?HardwareType $hardwareType = null)
{
if (!$hardwareType) {
return;
}
$this->name = $hardwareType->getName();
}
public function createOrUpdateEntity(?HardwareType $hardwareType = null): HardwareType
{
if (!$hardwareType) {
$hardwareType = new HardwareType();
}
$hardwareType->setName($this->name);
return $hardwareType;
}
}

View File

@ -16,7 +16,7 @@ final class HardwareOutput extends AbstractOutput
public ?string $description = '';
#[Groups(['hardware:read'])]
public ?string $type = '';
public ?HardwareTypeOutput $type = null;
#[Groups(['hardware:read'])]
public \DateTime $createAt;
@ -30,7 +30,7 @@ final class HardwareOutput extends AbstractOutput
$this->name = $hardware->getName();
$this->description = $hardware->getDescription();
$this->type = $hardware->getType();
$this->type = new HardwareTypeOutput($hardware->getType());
$this->createAt = $hardware->getCreatedAt();
$this->createBy = $hardware->getCreatedBy();
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Dto\Output;
use ApiPlatform\Metadata\Get;
use App\Entity\HardwareType;
use Symfony\Component\Serializer\Annotation\Groups;
#[Get(shortName: 'HardwareType')]
final class HardwareTypeOutput extends AbstractOutput
{
#[Groups(['hardware-type:read'])]
public string $name;
public function __construct(HardwareType $hardwareType)
{
parent::__construct($hardwareType);
$this->name = $hardwareType->getName();
}
}

View File

@ -0,0 +1,76 @@
<?php
namespace App\Factory;
use App\Entity\HardwareType;
use App\Repository\HardwareTypeRepository;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Persistence\PersistentProxyObjectFactory;
use Zenstruck\Foundry\Persistence\Proxy;
use Zenstruck\Foundry\Persistence\ProxyRepositoryDecorator;
/**
* @extends PersistentProxyObjectFactory<HardwareType>
*
* @method HardwareType|Proxy create(array|callable $attributes = [])
* @method static HardwareType|Proxy createOne(array $attributes = [])
* @method static HardwareType|Proxy find(object|array|mixed $criteria)
* @method static HardwareType|Proxy findOrCreate(array $attributes)
* @method static HardwareType|Proxy first(string $sortedField = 'id')
* @method static HardwareType|Proxy last(string $sortedField = 'id')
* @method static HardwareType|Proxy random(array $attributes = [])
* @method static HardwareType|Proxy randomOrCreate(array $attributes = [])
* @method static HardwareTypeRepository|ProxyRepositoryDecorator repository()
* @method static HardwareType[]|Proxy[] all()
* @method static HardwareType[]|Proxy[] createMany(int $number, array|callable $attributes = [])
* @method static HardwareType[]|Proxy[] createSequence(iterable|callable $sequence)
* @method static HardwareType[]|Proxy[] findBy(array $attributes)
* @method static HardwareType[]|Proxy[] randomRange(int $min, int $max, array $attributes = [])
* @method static HardwareType[]|Proxy[] randomSet(int $number, array $attributes = [])
*/
final class HardwareTypeFactory extends ModelFactory
{
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#factories-as-services
*
* @todo inject services if required
*/
public function __construct()
{
parent::__construct();
}
public static function class(): string
{
return HardwareType::class;
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#model-factories
*
* @todo add your default values here
*/
protected function getDefaults(): array
{
return [
'createdAt' => self::faker()->dateTime(),
'name' => self::faker()->text(255),
'updatedAt' => self::faker()->dateTime(),
];
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#initialization
*/
protected function initialize(): self
{
return $this
// ->afterInstantiate(function(HardwareType $hardwareType): void {})
;
}
protected static function getClass(): string
{
return HardwareType::class;
}
}

View File

@ -0,0 +1,77 @@
<?php
namespace App\State\Processor;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\Validator\ValidatorInterface;
use App\Dto\Input\HardwareTypeInput;
use App\Dto\Input\MenuInput;
use App\Dto\Input\OperativeSystemInput;
use App\Dto\Input\UserGroupInput;
use App\Dto\Output\HardwareTypeOutput;
use App\Dto\Output\MenuOutput;
use App\Dto\Output\OperativeSystemOutput;
use App\Dto\Output\UserGroupOutput;
use App\Repository\HardwareTypeRepository;
use App\Repository\MenuRepository;
use App\Repository\OperativeSystemRepository;
use App\Repository\UserGroupRepository;
readonly class HardwareTypeProcessor implements ProcessorInterface
{
public function __construct(
private HardwareTypeRepository $hardwareTypeRepository,
private ValidatorInterface $validator
)
{
}
/**
* @throws \Exception
*/
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): HardwareTypeOutput|null
{
switch ($operation){
case $operation instanceof Post:
case $operation instanceof Put:
case $operation instanceof Patch:
return $this->processCreateOrUpdate($data, $operation, $uriVariables, $context);
case $operation instanceof Delete:
return $this->processDelete($data, $operation, $uriVariables, $context);
}
}
/**
* @throws \Exception
*/
private function processCreateOrUpdate($data, Operation $operation, array $uriVariables = [], array $context = []): HardwareTypeOutput
{
if (!($data instanceof HardwareTypeInput)) {
throw new \Exception(sprintf('data is not instance of %s', MenuInput::class));
}
$entity = null;
if (isset($uriVariables['uuid'])) {
$entity = $this->hardwareTypeRepository->findOneByUuid($uriVariables['uuid']);
}
$hardwareType = $data->createOrUpdateEntity($entity);
$this->validator->validate($hardwareType);
$this->hardwareTypeRepository->save($hardwareType);
return new HardwareTypeOutput($hardwareType);
}
private function processDelete($data, Operation $operation, array $uriVariables = [], array $context = []): null
{
$user = $this->hardwareTypeRepository->findOneByUuid($uriVariables['uuid']);
$this->hardwareTypeRepository->delete($user);
return null;
}
}

View File

@ -0,0 +1,78 @@
<?php
namespace App\State\Provider;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Put;
use ApiPlatform\State\Pagination\TraversablePaginator;
use ApiPlatform\State\ProviderInterface;
use App\Dto\Input\ClientInput;
use App\Dto\Input\HardwareInput;
use App\Dto\Input\HardwareTypeInput;
use App\Dto\Input\OperativeSystemInput;
use App\Dto\Output\ClientOutput;
use App\Dto\Output\HardwareOutput;
use App\Dto\Output\HardwareTypeOutput;
use App\Dto\Output\NetworkSettingsOutput;
use App\Dto\Output\OperativeSystemOutput;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class HardwareTypeProvider implements ProviderInterface
{
public function __construct(
private readonly ProviderInterface $collectionProvider,
private readonly ProviderInterface $itemProvider
)
{
}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
switch ($operation){
case $operation instanceof GetCollection:
return $this->provideCollection($operation, $uriVariables, $context);
case $operation instanceof Patch:
case $operation instanceof Put:
return $this->provideInput($operation, $uriVariables, $context);
case $operation instanceof Get:
return $this->provideItem($operation, $uriVariables, $context);
}
}
private function provideCollection(Operation $operation, array $uriVariables = [], array $context = []): object
{
$paginator = $this->collectionProvider->provide($operation, $uriVariables, $context);
$items = new \ArrayObject();
foreach ($paginator->getIterator() as $item){
$items[] = new HardwareTypeOutput($item);
}
return new TraversablePaginator($items, $paginator->getCurrentPage(), $paginator->getItemsPerPage(), $paginator->getTotalItems());
}
public function provideItem(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
$item = $this->itemProvider->provide($operation, $uriVariables, $context);
if (!$item) {
throw new NotFoundHttpException('Operative system not found');
}
return new HardwareTypeOutput($item);
}
public function provideInput(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
if (isset($uriVariables['uuid'])) {
$item = $this->itemProvider->provide($operation, $uriVariables, $context);
return $item !== null ? new HardwareTypeInput($item) : null;
}
return new HardwareTypeInput();
}
}

View File

@ -0,0 +1,117 @@
<?php
namespace Functional;
use App\Entity\HardwareType;
use App\Factory\HardwareTypeFactory;
use App\Factory\OrganizationalUnitFactory;
use App\Factory\UserFactory;
use App\Model\UserGroupPermissions;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
class HardwareTypeTest extends AbstractTest
{
CONST string USER_ADMIN = 'ogadmin';
CONST string HW_TYPE_CREATE = 'test-hw-type-create';
CONST string HW_TYPE_UPDATE = 'test-hw-type-update';
CONST string HW_TYPE_DELETE = 'test-hw-type-delete';
/**
* @throws RedirectionExceptionInterface
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
*/
public function testGetCollectionHardwareType(): void
{
UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]);
HardwareTypeFactory::createMany(10);
$this->createClientWithCredentials()->request('GET', '/hardware-types');
$this->assertResponseStatusCodeSame(Response::HTTP_OK);
$this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
$this->assertJsonContains([
'@context' => '/contexts/HardwareType',
'@id' => '/hardware-types',
'@type' => 'hydra:Collection',
'hydra:totalItems' => 10,
]);
}
/**
* @throws RedirectionExceptionInterface
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
*/
public function testCreateHardwareType(): void
{
UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]);
$this->createClientWithCredentials()->request('POST', '/hardware-types',['json' => [
'name' => self::HW_TYPE_CREATE,
]]);
$this->assertResponseStatusCodeSame(201);
$this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
$this->assertJsonContains([
'@context' => '/contexts/HardwareTypeOutput',
'@type' => 'HardwareType',
'name' => self::HW_TYPE_CREATE
]);
}
/**
* @throws RedirectionExceptionInterface
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
*/
public function testUpdateHardwareType(): void
{
UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]);
HardwareTypeFactory::createOne(['name' => self::HW_TYPE_CREATE]);
$iri = $this->findIriBy(HardwareType::class, ['name' => self::HW_TYPE_CREATE]);
$this->createClientWithCredentials()->request('PUT', $iri, ['json' => [
'name' => self::HW_TYPE_UPDATE,
]]);
$this->assertResponseIsSuccessful();
$this->assertJsonContains([
'@id' => $iri,
'name' => self::HW_TYPE_UPDATE,
]);
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
*/
public function testDeleteHardwareType(): void
{
UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]);
HardwareTypeFactory::createOne(['name' => self::HW_TYPE_DELETE]);
$iri = $this->findIriBy(HardwareType::class, ['name' => self::HW_TYPE_DELETE]);
$this->createClientWithCredentials()->request('DELETE', $iri);
$this->assertResponseStatusCodeSame(204);
$this->assertNull(
static::getContainer()->get('doctrine')->getRepository(HardwareType::class)->findOneBy(['name' => self::HW_TYPE_DELETE])
);
}
}