Compare commits

..

No commits in common. "233c5e85500118d0bb2c60a5fcd95e65ddaea86a" and "43d72faf482a6f52c8df86de84f5bfe835f958ce" have entirely different histories.

195 changed files with 662 additions and 747 deletions

View file

@ -20,14 +20,12 @@
declare(strict_types=1);
use Symfony\Config\DoctrineConfig;
/**
* This class extends the default doctrine ORM configuration to enable native lazy objects on PHP 8.4+.
* We have to do this in a PHP file, because the yaml file does not support conditionals on PHP version.
*/
return static function(DoctrineConfig $doctrine) {
return static function(\Symfony\Config\DoctrineConfig $doctrine) {
//On PHP 8.4+ we can use native lazy objects, which are much more efficient than proxies.
if (PHP_VERSION_ID >= 80400) {
$doctrine->orm()->enableNativeLazyObjects(true);

View file

@ -18,7 +18,7 @@ use Rector\Symfony\Set\SymfonySetList;
use Rector\TypeDeclaration\Rector\StmtsAwareInterface\DeclareStrictTypesRector;
return RectorConfig::configure()
->withComposerBased(phpunit: true, symfony: true)
->withComposerBased(phpunit: true)
->withSymfonyContainerPhp(__DIR__ . '/tests/symfony-container.php')
->withSymfonyContainerXml(__DIR__ . '/var/cache/dev/App_KernelDevDebugContainer.xml')
@ -36,6 +36,8 @@ return RectorConfig::configure()
PHPUnitSetList::PHPUNIT_90,
PHPUnitSetList::PHPUNIT_110,
PHPUnitSetList::PHPUNIT_CODE_QUALITY,
])
->withRules([
@ -57,9 +59,6 @@ return RectorConfig::configure()
PreferPHPUnitThisCallRector::class,
//Do not replace 'GET' with class constant,
LiteralGetToRequestClassConstantRector::class,
//Do not move help text of commands to the command class, as we want to keep the help text in the command definition for better readability
\Rector\Symfony\Symfony73\Rector\Class_\CommandHelpToAttributeRector::class
])
//Do not apply rules to Symfony own files
@ -68,7 +67,6 @@ return RectorConfig::configure()
__DIR__ . '/src/Kernel.php',
__DIR__ . '/config/preload.php',
__DIR__ . '/config/bundles.php',
__DIR__ . '/config/reference.php'
])
;

View file

@ -22,7 +22,6 @@ declare(strict_types=1);
namespace App\Controller;
use App\Entity\InfoProviderSystem\BulkInfoProviderImportJob;
use App\DataTables\LogDataTable;
use App\Entity\Attachments\AttachmentUpload;
use App\Entity\Parts\Category;
@ -152,7 +151,7 @@ final class PartController extends AbstractController
$jobId = $request->query->get('jobId');
$bulkJob = null;
if ($jobId) {
$bulkJob = $this->em->getRepository(BulkInfoProviderImportJob::class)->find($jobId);
$bulkJob = $this->em->getRepository(\App\Entity\InfoProviderSystem\BulkInfoProviderImportJob::class)->find($jobId);
// Verify user owns this job
if ($bulkJob && $bulkJob->getCreatedBy() !== $this->getUser()) {
$bulkJob = null;
@ -173,7 +172,7 @@ final class PartController extends AbstractController
throw $this->createAccessDeniedException('Invalid CSRF token');
}
$bulkJob = $this->em->getRepository(BulkInfoProviderImportJob::class)->find($jobId);
$bulkJob = $this->em->getRepository(\App\Entity\InfoProviderSystem\BulkInfoProviderImportJob::class)->find($jobId);
if (!$bulkJob || $bulkJob->getCreatedBy() !== $this->getUser()) {
throw $this->createNotFoundException('Bulk import job not found');
}
@ -339,7 +338,7 @@ final class PartController extends AbstractController
$jobId = $request->query->get('jobId');
$bulkJob = null;
if ($jobId) {
$bulkJob = $this->em->getRepository(BulkInfoProviderImportJob::class)->find($jobId);
$bulkJob = $this->em->getRepository(\App\Entity\InfoProviderSystem\BulkInfoProviderImportJob::class)->find($jobId);
// Verify user owns this job
if ($bulkJob && $bulkJob->getCreatedBy() !== $this->getUser()) {
$bulkJob = null;

View file

@ -147,7 +147,10 @@ class SecurityController extends AbstractController
'label' => 'user.settings.pw_confirm.label',
],
'invalid_message' => 'password_must_match',
'constraints' => [new Length(min: 6, max: 128)],
'constraints' => [new Length([
'min' => 6,
'max' => 128,
])],
]);
$builder->add('submit', SubmitType::class, [

View file

@ -295,7 +295,10 @@ class UserSettingsController extends AbstractController
'autocomplete' => 'new-password',
],
],
'constraints' => [new Length(min: 6, max: 128)],
'constraints' => [new Length([
'min' => 6,
'max' => 128,
])],
])
->add('submit', SubmitType::class, [
'label' => 'save',

View file

@ -160,7 +160,7 @@ class PartSearchFilter implements FilterInterface
if ($search_dbId) {
$expressions[] = $queryBuilder->expr()->eq('part.id', ':id_exact');
$queryBuilder->setParameter('id_exact', (int) $this->keyword,
ParameterType::INTEGER);
\Doctrine\DBAL\ParameterType::INTEGER);
}
//Guard condition

View file

@ -1,7 +1,5 @@
<?php
declare(strict_types=1);
namespace App\EventSubscriber\UserSystem;
use App\Entity\Parts\Part;

View file

@ -122,7 +122,9 @@ class AttachmentFormType extends AbstractType
],
'constraints' => [
//new AllowedFileExtension(),
new File(maxSize: $options['max_file_size']),
new File([
'maxSize' => $options['max_file_size'],
]),
],
]);

View file

@ -22,7 +22,6 @@ declare(strict_types=1);
namespace App\Form\InfoProviderSystem;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
@ -62,7 +61,7 @@ class FieldToProviderMappingType extends AbstractType
'style' => 'width: 80px;'
],
'constraints' => [
new Range(min: 1, max: 10),
new \Symfony\Component\Validator\Constraints\Range(['min' => 1, 'max' => 10]),
],
]);
}

View file

@ -177,7 +177,10 @@ class UserAdminForm extends AbstractType
'required' => false,
'mapped' => false,
'disabled' => !$this->security->isGranted('set_password', $entity) || $entity->isSamlUser(),
'constraints' => [new Length(min: 6, max: 128)],
'constraints' => [new Length([
'min' => 6,
'max' => 128,
])],
])
->add('need_pw_change', CheckboxType::class, [

View file

@ -92,7 +92,9 @@ class UserSettingsType extends AbstractType
'accept' => 'image/*',
],
'constraints' => [
new File(maxSize: '5M'),
new File([
'maxSize' => '5M',
]),
],
])
->add('aboutMe', RichTextEditorType::class, [

View file

@ -22,8 +22,6 @@ declare(strict_types=1);
*/
namespace App\Services\ImportExportSystem;
use App\Entity\Parts\Supplier;
use App\Entity\PriceInformations\Orderdetail;
use App\Entity\Parts\Part;
use App\Entity\ProjectSystem\Project;
use App\Entity\ProjectSystem\ProjectBOMEntry;
@ -277,7 +275,7 @@ class BOMImporter
$mapped_entries = []; // Collect all mapped entries for validation
// Fetch suppliers once for efficiency
$suppliers = $this->entityManager->getRepository(Supplier::class)->findAll();
$suppliers = $this->entityManager->getRepository(\App\Entity\Parts\Supplier::class)->findAll();
$supplierSPNKeys = [];
$suppliersByName = []; // Map supplier names to supplier objects
foreach ($suppliers as $supplier) {
@ -373,7 +371,7 @@ class BOMImporter
if ($supplier_spn !== null) {
// Query for orderdetails with matching supplier and SPN
$orderdetail = $this->entityManager->getRepository(Orderdetail::class)
$orderdetail = $this->entityManager->getRepository(\App\Entity\PriceInformations\Orderdetail::class)
->findOneBy([
'supplier' => $supplier,
'supplierpartnr' => $supplier_spn,
@ -537,7 +535,7 @@ class BOMImporter
];
// Add dynamic supplier fields based on available suppliers in the database
$suppliers = $this->entityManager->getRepository(Supplier::class)->findAll();
$suppliers = $this->entityManager->getRepository(\App\Entity\Parts\Supplier::class)->findAll();
foreach ($suppliers as $supplier) {
$supplierName = $supplier->getName();
$targets[$supplierName . ' SPN'] = [
@ -572,7 +570,7 @@ class BOMImporter
];
// Add supplier-specific patterns
$suppliers = $this->entityManager->getRepository(Supplier::class)->findAll();
$suppliers = $this->entityManager->getRepository(\App\Entity\Parts\Supplier::class)->findAll();
foreach ($suppliers as $supplier) {
$supplierName = $supplier->getName();
$supplierLower = strtolower($supplierName);

View file

@ -22,7 +22,6 @@ declare(strict_types=1);
namespace App\Services\ImportExportSystem;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use App\Entity\Base\AbstractNamedDBElement;
use App\Entity\Base\AbstractStructuralDBElement;
use App\Helpers\FilenameSanatizer;
@ -178,7 +177,7 @@ class EntityExporter
$colIndex = 1;
foreach ($columns as $column) {
$cellCoordinate = Coordinate::stringFromColumnIndex($colIndex) . $rowIndex;
$cellCoordinate = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex) . $rowIndex;
$worksheet->setCellValue($cellCoordinate, $column);
$colIndex++;
}

View file

@ -22,7 +22,6 @@ declare(strict_types=1);
namespace App\Services\ImportExportSystem;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use App\Entity\Base\AbstractNamedDBElement;
use App\Entity\Base\AbstractStructuralDBElement;
use App\Entity\Parts\Category;
@ -420,14 +419,14 @@ class EntityImporter
'worksheet_title' => $worksheet->getTitle()
]);
$highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; $row++) {
$rowData = [];
// Read all columns using numeric index
for ($colIndex = 1; $colIndex <= $highestColumnIndex; $colIndex++) {
$col = Coordinate::stringFromColumnIndex($colIndex);
$col = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex);
try {
$cellValue = $worksheet->getCell("{$col}{$row}")->getCalculatedValue();
$rowData[] = $cellValue ?? '';

View file

@ -22,7 +22,6 @@ declare(strict_types=1);
namespace App\Services\InfoProviderSystem\DTOs;
use Doctrine\ORM\Exception\ORMException;
use App\Entity\Parts\Part;
use Doctrine\ORM\EntityManagerInterface;
use Traversable;
@ -177,7 +176,7 @@ readonly class BulkSearchResponseDTO implements \ArrayAccess, \IteratorAggregate
* @param array $data
* @param EntityManagerInterface $entityManager
* @return BulkSearchResponseDTO
* @throws ORMException
* @throws \Doctrine\ORM\Exception\ORMException
*/
public static function fromSerializableRepresentation(array $data, EntityManagerInterface $entityManager): BulkSearchResponseDTO
{

View file

@ -365,7 +365,7 @@ class BuerklinProvider implements BatchInfoProviderInterface, URLHandlerInfoProv
* - prefers 'zoom' format, then 'product' format, then all others
*
* @param array|null $images
* @return FileDTO[]
* @return \App\Services\InfoProviderSystem\DTOs\FileDTO[]
*/
private function getProductImages(?array $images): array
{

View file

@ -70,14 +70,12 @@ use App\Twig\Sandbox\SandboxedLabelExtension;
use App\Twig\TwigCoreExtension;
use InvalidArgumentException;
use Twig\Environment;
use Twig\Extension\AttributeExtension;
use Twig\Extension\SandboxExtension;
use Twig\Extra\Html\HtmlExtension;
use Twig\Extra\Intl\IntlExtension;
use Twig\Extra\Markdown\MarkdownExtension;
use Twig\Extra\String\StringExtension;
use Twig\Loader\ArrayLoader;
use Twig\RuntimeLoader\FactoryRuntimeLoader;
use Twig\Sandbox\SecurityPolicyInterface;
/**
@ -188,18 +186,13 @@ final class SandboxedTwigFactory
$twig->addExtension(new StringExtension());
$twig->addExtension(new HtmlExtension());
//Add Part-DB specific extension
$twig->addExtension($this->formatExtension);
$twig->addExtension($this->barcodeExtension);
$twig->addExtension($this->entityExtension);
$twig->addExtension($this->twigCoreExtension);
$twig->addExtension($this->sandboxedLabelExtension);
//Our other extensions are using attributes, we need a bit more work to load them
$dynamicExtensions = [$this->formatExtension, $this->barcodeExtension, $this->entityExtension, $this->twigCoreExtension];
$dynamicExtensionsMap = [];
foreach ($dynamicExtensions as $extension) {
$twig->addExtension(new AttributeExtension($extension::class));
$dynamicExtensionsMap[$extension::class] = static fn () => $extension;
}
$twig->addRuntimeLoader(new FactoryRuntimeLoader($dynamicExtensionsMap));
return $twig;
}

View file

@ -32,7 +32,7 @@ class LogDiffFormatter
* @param $old_data
* @param $new_data
*/
public function formatDiff(mixed $old_data, mixed $new_data): string
public function formatDiff($old_data, $new_data): string
{
if (is_string($old_data) && is_string($new_data)) {
return $this->diffString($old_data, $new_data);

View file

@ -22,8 +22,6 @@ declare(strict_types=1);
namespace App\Services\System;
use Doctrine\DBAL\Platforms\AbstractMySQLPlatform;
use Doctrine\DBAL\Platforms\PostgreSQLPlatform;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Shivas\VersioningBundle\Service\VersionManagerInterface;
@ -336,7 +334,7 @@ readonly class BackupManager
$params = $connection->getParams();
$platform = $connection->getDatabasePlatform();
if ($platform instanceof AbstractMySQLPlatform) {
if ($platform instanceof \Doctrine\DBAL\Platforms\AbstractMySQLPlatform) {
// Use mysql command to import - need to use shell to handle input redirection
$mysqlCmd = 'mysql';
if (isset($params['host'])) {
@ -363,7 +361,7 @@ readonly class BackupManager
if (!$process->isSuccessful()) {
throw new \RuntimeException('MySQL import failed: ' . $process->getErrorOutput());
}
} elseif ($platform instanceof PostgreSQLPlatform) {
} elseif ($platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform) {
// Use psql command to import
$psqlCmd = 'psql';
if (isset($params['host'])) {

View file

@ -25,34 +25,22 @@ namespace App\Twig;
use App\Entity\Attachments\Attachment;
use App\Services\Attachments\AttachmentURLGenerator;
use App\Services\Misc\FAIconGenerator;
use Twig\Attribute\AsTwigFunction;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
final readonly class AttachmentExtension
final class AttachmentExtension extends AbstractExtension
{
public function __construct(private AttachmentURLGenerator $attachmentURLGenerator, private FAIconGenerator $FAIconGenerator)
public function __construct(protected AttachmentURLGenerator $attachmentURLGenerator, protected FAIconGenerator $FAIconGenerator)
{
}
/**
* Returns the URL of the thumbnail of the given attachment. Returns null if no thumbnail is available.
*/
#[AsTwigFunction("attachment_thumbnail")]
public function attachmentThumbnail(Attachment $attachment, string $filter_name = 'thumbnail_sm'): ?string
public function getFunctions(): array
{
return $this->attachmentURLGenerator->getThumbnailURL($attachment, $filter_name);
}
/**
* Return the font-awesome icon type for the given file extension. Returns "file" if no specific icon is available.
* Null is allowed for files withot extension
* @param string|null $extension
* @return string
*/
#[AsTwigFunction("ext_to_fa_icon")]
public function extToFAIcon(?string $extension): string
{
return $this->FAIconGenerator->fileExtensionToFAType($extension ?? '');
return [
/* Returns the URL to a thumbnail of the given attachment */
new TwigFunction('attachment_thumbnail', fn(Attachment $attachment, string $filter_name = 'thumbnail_sm'): ?string => $this->attachmentURLGenerator->getThumbnailURL($attachment, $filter_name)),
/* Returns the font awesome icon class which is representing the given file extension (We allow null here for attachments without extension) */
new TwigFunction('ext_to_fa_icon', fn(?string $extension): string => $this->FAIconGenerator->fileExtensionToFAType($extension ?? '')),
];
}
}

View file

@ -23,14 +23,19 @@ declare(strict_types=1);
namespace App\Twig;
use Com\Tecnick\Barcode\Barcode;
use Twig\Attribute\AsTwigFunction;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
final class BarcodeExtension
final class BarcodeExtension extends AbstractExtension
{
/**
* Generates a barcode in SVG format for the given content and type.
*/
#[AsTwigFunction('barcode_svg')]
public function getFunctions(): array
{
return [
/* Generates a barcode with the given Type and Data and returns it as an SVG represenation */
new TwigFunction('barcode_svg', fn(string $content, string $type = 'QRCODE'): string => $this->barcodeSVG($content, $type)),
];
}
public function barcodeSVG(string $content, string $type = 'QRCODE'): string
{
$barcodeFactory = new Barcode();

View file

@ -41,9 +41,6 @@ use App\Exceptions\EntityNotSupportedException;
use App\Services\ElementTypeNameGenerator;
use App\Services\EntityURLGenerator;
use App\Services\Trees\TreeViewGenerator;
use Twig\Attribute\AsTwigFunction;
use Twig\Attribute\AsTwigTest;
use Twig\DeprecatedCallableInfo;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Twig\TwigTest;
@ -51,27 +48,61 @@ use Twig\TwigTest;
/**
* @see \App\Tests\Twig\EntityExtensionTest
*/
final readonly class EntityExtension
final class EntityExtension extends AbstractExtension
{
public function __construct(private EntityURLGenerator $entityURLGenerator, private TreeViewGenerator $treeBuilder, private ElementTypeNameGenerator $nameGenerator)
public function __construct(protected EntityURLGenerator $entityURLGenerator, protected TreeViewGenerator $treeBuilder, private readonly ElementTypeNameGenerator $nameGenerator)
{
}
/**
* Checks if the given variable is an entity (instance of AbstractDBElement).
*/
#[AsTwigTest("entity")]
public function entityTest(mixed $var): bool
public function getTests(): array
{
return $var instanceof AbstractDBElement;
return [
/* Checks if the given variable is an entitity (instance of AbstractDBElement) */
new TwigTest('entity', static fn($var) => $var instanceof AbstractDBElement),
];
}
public function getFunctions(): array
{
return [
/* Returns a string representation of the given entity */
new TwigFunction('entity_type', fn(object $entity): ?string => $this->getEntityType($entity)),
/* Returns the URL to the given entity */
new TwigFunction('entity_url', fn(AbstractDBElement $entity, string $method = 'info'): string => $this->generateEntityURL($entity, $method)),
/* Returns the URL to the given entity in timetravel mode */
new TwigFunction('timetravel_url', fn(AbstractDBElement $element, \DateTimeInterface $dateTime): ?string => $this->timeTravelURL($element, $dateTime)),
/* Generates a JSON array of the given tree */
new TwigFunction('tree_data', fn(AbstractDBElement $element, string $type = 'newEdit'): string => $this->treeData($element, $type)),
/**
* Returns a string representation of the given entity
*/
#[AsTwigFunction("entity_type")]
public function entityType(object $entity): ?string
/* Gets a human readable label for the type of the given entity */
new TwigFunction('entity_type_label', fn(object|string $entity): string => $this->nameGenerator->getLocalizedTypeLabel($entity)),
new TwigFunction('type_label', fn(object|string $entity): string => $this->nameGenerator->typeLabel($entity)),
new TwigFunction('type_label_p', fn(object|string $entity): string => $this->nameGenerator->typeLabelPlural($entity)),
];
}
public function timeTravelURL(AbstractDBElement $element, \DateTimeInterface $dateTime): ?string
{
try {
return $this->entityURLGenerator->timeTravelURL($element, $dateTime);
} catch (EntityNotSupportedException) {
return null;
}
}
public function treeData(AbstractDBElement $element, string $type = 'newEdit'): string
{
$tree = $this->treeBuilder->getTreeView($element::class, null, $type, $element);
return json_encode($tree, JSON_THROW_ON_ERROR);
}
public function generateEntityURL(AbstractDBElement $entity, string $method = 'info'): string
{
return $this->entityURLGenerator->getURL($entity, $method);
}
public function getEntityType(object $entity): ?string
{
$map = [
Part::class => 'part',
@ -98,69 +129,4 @@ final readonly class EntityExtension
return null;
}
/**
* Returns the URL for the given entity and method. E.g. for a Part and method "edit", it will return the URL to edit this part.
*/
#[AsTwigFunction("entity_url")]
public function entityURL(AbstractDBElement $entity, string $method = 'info'): string
{
return $this->entityURLGenerator->getURL($entity, $method);
}
/**
* Returns the URL for the given entity in timetravel mode.
*/
#[AsTwigFunction("timetravel_url")]
public function timeTravelURL(AbstractDBElement $element, \DateTimeInterface $dateTime): ?string
{
try {
return $this->entityURLGenerator->timeTravelURL($element, $dateTime);
} catch (EntityNotSupportedException) {
return null;
}
}
/**
* Generates a tree data structure for the given element, which can be used to display a tree view of the element and its related entities.
* The type parameter can be used to specify the type of tree view (e.g. "newEdit" for the tree view in the new/edit pages). The returned data is a JSON string.
*/
#[AsTwigFunction("tree_data")]
public function treeData(AbstractDBElement $element, string $type = 'newEdit'): string
{
$tree = $this->treeBuilder->getTreeView($element::class, null, $type, $element);
return json_encode($tree, JSON_THROW_ON_ERROR);
}
/**
* Gets the localized type label for the given entity. E.g. for a Part, it will return "Part" in English and "Bauteil" in German.
* @deprecated Use the "type_label" function instead, which does the same but is more concise.
*/
#[AsTwigFunction("entity_type_label", deprecationInfo: new DeprecatedCallableInfo("Part-DB", "2", "Use the 'type_label' function instead."))]
public function entityTypeLabel(object|string $entity): string
{
return $this->nameGenerator->getLocalizedTypeLabel($entity);
}
/**
* Gets the localized type label for the given entity. E.g. for a Part, it will return "Part" in English and "Bauteil" in German.
*/
#[AsTwigFunction("type_label")]
public function typeLabel(object|string $entity): string
{
return $this->nameGenerator->typeLabel($entity);
}
/**
* Gets the localized plural type label for the given entity. E.g. for a Part, it will return "Parts" in English and "Bauteile" in German.
* @param object|string $entity
* @return string
*/
#[AsTwigFunction("type_label_p")]
public function typeLabelPlural(object|string $entity): string
{
return $this->nameGenerator->typeLabelPlural($entity);
}
}

View file

@ -29,28 +29,35 @@ use App\Services\Formatters\MarkdownParser;
use App\Services\Formatters\MoneyFormatter;
use App\Services\Formatters\SIFormatter;
use Brick\Math\BigDecimal;
use Twig\Attribute\AsTwigFilter;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
final readonly class FormatExtension
final class FormatExtension extends AbstractExtension
{
public function __construct(private MarkdownParser $markdownParser, private MoneyFormatter $moneyFormatter, private SIFormatter $siformatter, private AmountFormatter $amountFormatter)
public function __construct(protected MarkdownParser $markdownParser, protected MoneyFormatter $moneyFormatter, protected SIFormatter $siformatter, protected AmountFormatter $amountFormatter)
{
}
/**
* Mark the given text as markdown, which will be rendered in the browser
*/
#[AsTwigFilter("format_markdown", isSafe: ['html'], preEscape: 'html')]
public function formatMarkdown(string $markdown, bool $inline_mode = false): string
public function getFilters(): array
{
return $this->markdownParser->markForRendering($markdown, $inline_mode);
return [
/* Mark the given text as markdown, which will be rendered in the browser */
new TwigFilter('format_markdown', fn(string $markdown, bool $inline_mode = false): string => $this->markdownParser->markForRendering($markdown, $inline_mode), [
'pre_escape' => 'html',
'is_safe' => ['html'],
]),
/* Format the given amount as money, using a given currency */
new TwigFilter('format_money', fn($amount, ?Currency $currency = null, int $decimals = 5): string => $this->formatCurrency($amount, $currency, $decimals)),
/* Format the given number using SI prefixes and the given unit (string) */
new TwigFilter('format_si', fn($value, $unit, $decimals = 2, bool $show_all_digits = false): string => $this->siFormat($value, $unit, $decimals, $show_all_digits)),
/** Format the given amount using the given MeasurementUnit */
new TwigFilter('format_amount', fn($value, ?MeasurementUnit $unit, array $options = []): string => $this->amountFormat($value, $unit, $options)),
/** Format the given number of bytes as human-readable number */
new TwigFilter('format_bytes', fn(int $bytes, int $precision = 2): string => $this->formatBytes($bytes, $precision)),
];
}
/**
* Format the given amount as money, using a given currency
*/
#[AsTwigFilter("format_money")]
public function formatMoney(BigDecimal|float|string $amount, ?Currency $currency = null, int $decimals = 5): string
public function formatCurrency($amount, ?Currency $currency = null, int $decimals = 5): string
{
if ($amount instanceof BigDecimal) {
$amount = (string) $amount;
@ -59,22 +66,19 @@ final readonly class FormatExtension
return $this->moneyFormatter->format($amount, $currency, $decimals);
}
/**
* Format the given number using SI prefixes and the given unit (string)
*/
#[AsTwigFilter("format_si")]
public function siFormat(float $value, string $unit, int $decimals = 2, bool $show_all_digits = false): string
public function siFormat($value, $unit, $decimals = 2, bool $show_all_digits = false): string
{
return $this->siformatter->format($value, $unit, $decimals);
}
#[AsTwigFilter("format_amount")]
public function amountFormat(float|int|string $value, ?MeasurementUnit $unit, array $options = []): string
public function amountFormat($value, ?MeasurementUnit $unit, array $options = []): string
{
return $this->amountFormatter->format($value, $unit, $options);
}
#[AsTwigFilter("format_bytes")]
/**
* @param $bytes
*/
public function formatBytes(int $bytes, int $precision = 2): string
{
$size = ['B','kB','MB','GB','TB','PB','EB','ZB','YB'];

View file

@ -23,25 +23,31 @@ declare(strict_types=1);
namespace App\Twig;
use Twig\Attribute\AsTwigFunction;
use App\Services\InfoProviderSystem\ProviderRegistry;
use App\Services\InfoProviderSystem\Providers\InfoProviderInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
final readonly class InfoProviderExtension
class InfoProviderExtension extends AbstractExtension
{
public function __construct(
private ProviderRegistry $providerRegistry
private readonly ProviderRegistry $providerRegistry
) {}
public function getFunctions(): array
{
return [
new TwigFunction('info_provider', $this->getInfoProvider(...)),
new TwigFunction('info_provider_label', $this->getInfoProviderName(...))
];
}
/**
* Gets the info provider with the given key. Returns null, if the provider does not exist.
* @param string $key
* @return InfoProviderInterface|null
*/
#[AsTwigFunction(name: 'info_provider')]
public function getInfoProvider(string $key): ?InfoProviderInterface
private function getInfoProvider(string $key): ?InfoProviderInterface
{
try {
return $this->providerRegistry->getProviderByKey($key);
@ -55,8 +61,7 @@ final readonly class InfoProviderExtension
* @param string $key
* @return string|null
*/
#[AsTwigFunction(name: 'info_provider_label')]
public function getInfoProviderName(string $key): ?string
private function getInfoProviderName(string $key): ?string
{
try {
return $this->providerRegistry->getProviderByKey($key)->getProviderInfo()['name'];
@ -64,4 +69,4 @@ final readonly class InfoProviderExtension
return null;
}
}
}
}

View file

@ -25,26 +25,21 @@ namespace App\Twig;
use App\Entity\LogSystem\AbstractLogEntry;
use App\Services\LogSystem\LogDataFormatter;
use App\Services\LogSystem\LogDiffFormatter;
use Twig\Attribute\AsTwigFunction;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
final readonly class LogExtension
final class LogExtension extends AbstractExtension
{
public function __construct(private LogDataFormatter $logDataFormatter, private LogDiffFormatter $logDiffFormatter)
public function __construct(private readonly LogDataFormatter $logDataFormatter, private readonly LogDiffFormatter $logDiffFormatter)
{
}
#[AsTwigFunction(name: 'format_log_data', isSafe: ['html'])]
public function formatLogData(mixed $data, AbstractLogEntry $logEntry, string $fieldName): string
public function getFunctions(): array
{
return $this->logDataFormatter->formatData($data, $logEntry, $fieldName);
}
#[AsTwigFunction(name: 'format_log_diff', isSafe: ['html'])]
public function formatLogDiff(mixed $old_data, mixed $new_data): string
{
return $this->logDiffFormatter->formatDiff($old_data, $new_data);
return [
new TwigFunction('format_log_data', fn($data, AbstractLogEntry $logEntry, string $fieldName): string => $this->logDataFormatter->formatData($data, $logEntry, $fieldName), ['is_safe' => ['html']]),
new TwigFunction('format_log_diff', fn($old_data, $new_data): string => $this->logDiffFormatter->formatDiff($old_data, $new_data), ['is_safe' => ['html']]),
];
}
}

View file

@ -22,7 +22,6 @@ declare(strict_types=1);
*/
namespace App\Twig;
use Twig\Attribute\AsTwigFunction;
use App\Settings\SettingsIcon;
use Symfony\Component\HttpFoundation\Request;
use App\Services\LogSystem\EventCommentType;
@ -32,14 +31,23 @@ use Twig\TwigFunction;
use App\Services\LogSystem\EventCommentNeededHelper;
use Twig\Extension\AbstractExtension;
final readonly class MiscExtension
final class MiscExtension extends AbstractExtension
{
public function __construct(private EventCommentNeededHelper $eventCommentNeededHelper)
public function __construct(private readonly EventCommentNeededHelper $eventCommentNeededHelper)
{
}
#[AsTwigFunction(name: 'event_comment_needed')]
public function evenCommentNeeded(string|EventCommentType $operation_type): bool
public function getFunctions(): array
{
return [
new TwigFunction('event_comment_needed', $this->evenCommentNeeded(...)),
new TwigFunction('settings_icon', $this->settingsIcon(...)),
new TwigFunction('uri_without_host', $this->uri_without_host(...))
];
}
private function evenCommentNeeded(string|EventCommentType $operation_type): bool
{
if (is_string($operation_type)) {
$operation_type = EventCommentType::from($operation_type);
@ -55,8 +63,7 @@ final readonly class MiscExtension
* @return string|null
* @throws \ReflectionException
*/
#[AsTwigFunction(name: 'settings_icon')]
public function settingsIcon(string|object $objectOrClass): ?string
private function settingsIcon(string|object $objectOrClass): ?string
{
//If the given object is a proxy, then get the real object
if (is_a($objectOrClass, SettingsProxyInterface::class)) {
@ -75,7 +82,6 @@ final readonly class MiscExtension
* @param Request $request
* @return string
*/
#[AsTwigFunction(name: 'uri_without_host')]
public function uri_without_host(Request $request): string
{
if (null !== $qs = $request->getQueryString()) {

View file

@ -22,11 +22,7 @@ declare(strict_types=1);
*/
namespace App\Twig;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Twig\Attribute\AsTwigFilter;
use Twig\Attribute\AsTwigFunction;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Twig\Attribute\AsTwigTest;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
@ -36,54 +32,58 @@ use Twig\TwigTest;
* The functionalities here extend the Twig with some core functions, which are independently of Part-DB.
* @see \App\Tests\Twig\TwigCoreExtensionTest
*/
final readonly class TwigCoreExtension
final class TwigCoreExtension extends AbstractExtension
{
private NormalizerInterface $objectNormalizer;
private readonly ObjectNormalizer $objectNormalizer;
public function __construct()
{
$this->objectNormalizer = new ObjectNormalizer();
}
/**
* Checks if the given variable is an instance of the given class/interface/enum. E.g. `x is instanceof('App\Entity\Parts\Part')`
* @param mixed $var
* @param string $instance
* @return bool
*/
#[AsTwigTest("instanceof")]
public function testInstanceOf(mixed $var, string $instance): bool
public function getFunctions(): array
{
if (!class_exists($instance) && !interface_exists($instance) && !enum_exists($instance)) {
throw new \InvalidArgumentException(sprintf('The given class/interface/enum "%s" does not exist!', $instance));
return [
/* Returns the enum cases as values */
new TwigFunction('enum_cases', $this->getEnumCases(...)),
];
}
public function getTests(): array
{
return [
/*
* Checks if a given variable is an instance of a given class. E.g. ` x is instanceof('App\Entity\Parts\Part')`
*/
new TwigTest('instanceof', static fn($var, $instance) => $var instanceof $instance),
/* Checks if a given variable is an object. E.g. `x is object` */
new TwigTest('object', static fn($var): bool => is_object($var)),
new TwigTest('enum', fn($var) => $var instanceof \UnitEnum),
];
}
/**
* @param string $enum_class
* @phpstan-param class-string $enum_class
*/
public function getEnumCases(string $enum_class): array
{
if (!enum_exists($enum_class)) {
throw new \InvalidArgumentException(sprintf('The given class "%s" is not an enum!', $enum_class));
}
return $var instanceof $instance;
/** @noinspection PhpUndefinedMethodInspection */
return ($enum_class)::cases();
}
/**
* Checks if the given variable is an object. This can be used to check if a variable is an object, without knowing the exact class of the object. E.g. `x is object`
* @param mixed $var
* @return bool
*/
#[AsTwigTest("object")]
public function testObject(mixed $var): bool
public function getFilters(): array
{
return is_object($var);
return [
/* Converts the given object to an array representation of the public/accessible properties */
new TwigFilter('to_array', fn($object) => $this->toArray($object)),
];
}
/**
* Checks if the given variable is an enum (instance of UnitEnum). This can be used to check if a variable is an enum, without knowing the exact class of the enum. E.g. `x is enum`
* @param mixed $var
* @return bool
*/
#[AsTwigTest("enum")]
public function testEnum(mixed $var): bool
{
return $var instanceof \UnitEnum;
}
#[AsTwigFilter('to_array')]
public function toArray(object|array $object): array
{
//If it is already an array, we can just return it

View file

@ -23,7 +23,6 @@ declare(strict_types=1);
namespace App\Twig;
use Twig\Attribute\AsTwigFunction;
use App\Services\System\UpdateAvailableFacade;
use Symfony\Bundle\SecurityBundle\Security;
use Twig\Extension\AbstractExtension;
@ -32,18 +31,26 @@ use Twig\TwigFunction;
/**
* Twig extension for update-related functions.
*/
final readonly class UpdateExtension
final class UpdateExtension extends AbstractExtension
{
public function __construct(private UpdateAvailableFacade $updateAvailableManager,
private Security $security)
public function __construct(private readonly UpdateAvailableFacade $updateAvailableManager,
private readonly Security $security)
{
}
public function getFunctions(): array
{
return [
new TwigFunction('is_update_available', $this->isUpdateAvailable(...)),
new TwigFunction('get_latest_version', $this->getLatestVersion(...)),
new TwigFunction('get_latest_version_url', $this->getLatestVersionUrl(...)),
];
}
/**
* Check if an update is available and the user has permission to see it.
*/
#[AsTwigFunction(name: 'is_update_available')]
public function isUpdateAvailable(): bool
{
// Only show to users with the show_updates permission
@ -57,7 +64,6 @@ final readonly class UpdateExtension
/**
* Get the latest available version string.
*/
#[AsTwigFunction(name: 'get_latest_version')]
public function getLatestVersion(): string
{
return $this->updateAvailableManager->getLatestVersionString();
@ -66,7 +72,6 @@ final readonly class UpdateExtension
/**
* Get the URL to the latest version release page.
*/
#[AsTwigFunction(name: 'get_latest_version_url')]
public function getLatestVersionUrl(): string
{
return $this->updateAvailableManager->getLatestVersionUrl();

View file

@ -41,24 +41,51 @@ declare(strict_types=1);
namespace App\Twig;
use Twig\Attribute\AsTwigFilter;
use Twig\Attribute\AsTwigFunction;
use App\Entity\Base\AbstractDBElement;
use App\Entity\UserSystem\User;
use App\Entity\LogSystem\AbstractLogEntry;
use App\Repository\LogEntryRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
/**
* @see \App\Tests\Twig\UserExtensionTest
*/
final readonly class UserExtension
final class UserExtension extends AbstractExtension
{
private readonly LogEntryRepository $repo;
public function __construct(
private Security $security,
private UrlGeneratorInterface $urlGenerator)
public function __construct(EntityManagerInterface $em,
private readonly Security $security,
private readonly UrlGeneratorInterface $urlGenerator)
{
$this->repo = $em->getRepository(AbstractLogEntry::class);
}
public function getFilters(): array
{
return [
new TwigFilter('remove_locale_from_path', fn(string $path): string => $this->removeLocaleFromPath($path)),
];
}
public function getFunctions(): array
{
return [
/* Returns the user which has edited the given entity the last time. */
new TwigFunction('last_editing_user', fn(AbstractDBElement $element): ?User => $this->repo->getLastEditingUser($element)),
/* Returns the user which has created the given entity. */
new TwigFunction('creating_user', fn(AbstractDBElement $element): ?User => $this->repo->getCreatingUser($element)),
new TwigFunction('impersonator_user', $this->getImpersonatorUser(...)),
new TwigFunction('impersonation_active', $this->isImpersonationActive(...)),
new TwigFunction('impersonation_path', $this->getImpersonationPath(...)),
];
}
/**
@ -66,7 +93,6 @@ final readonly class UserExtension
* If the current user is not impersonated, null is returned.
* @return User|null
*/
#[AsTwigFunction(name: 'impersonator_user')]
public function getImpersonatorUser(): ?User
{
$token = $this->security->getToken();
@ -81,13 +107,11 @@ final readonly class UserExtension
return null;
}
#[AsTwigFunction(name: 'impersonation_active')]
public function isImpersonationActive(): bool
{
return $this->security->isGranted('IS_IMPERSONATOR');
}
#[AsTwigFunction(name: 'impersonation_path')]
public function getImpersonationPath(User $user, string $route_name = 'homepage'): string
{
if (! $this->security->isGranted('CAN_SWITCH_USER', $user)) {
@ -100,7 +124,6 @@ final readonly class UserExtension
/**
* This function/filter generates a path.
*/
#[AsTwigFilter(name: 'remove_locale_from_path')]
public function removeLocaleFromPath(string $path): string
{
//Ensure the path has the correct format

View file

@ -1,57 +0,0 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2026 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Twig;
use App\Entity\Base\AbstractDBElement;
use App\Entity\LogSystem\AbstractLogEntry;
use App\Entity\UserSystem\User;
use App\Repository\LogEntryRepository;
use Doctrine\ORM\EntityManagerInterface;
use Twig\Attribute\AsTwigFunction;
final readonly class UserRepoExtension
{
public function __construct(private EntityManagerInterface $entityManager)
{
}
/**
* Returns the user which has edited the given entity the last time.
*/
#[AsTwigFunction('creating_user')]
public function creatingUser(AbstractDBElement $element): ?User
{
return $this->entityManager->getRepository(AbstractLogEntry::class)->getCreatingUser($element);
}
/**
* Returns the user which has edited the given entity the last time.
*/
#[AsTwigFunction('last_editing_user')]
public function lastEditingUser(AbstractDBElement $element): ?User
{
return $this->entityManager->getRepository(AbstractLogEntry::class)->getLastEditingUser($element);
}
}

View file

@ -1,7 +1,5 @@
<?php
declare(strict_types=1);
namespace App\Validator\Constraints;
use Attribute;

View file

@ -1,7 +1,5 @@
<?php
declare(strict_types=1);
namespace App\Validator\Constraints;
use App\Entity\Parts\Part;

View file

@ -84,7 +84,7 @@
</span>
</div>
{% if entity is instanceof("App\\Entity\\Parts\\StorageLocation") %}
{% if entity is instanceof("App\\Entity\\Parts\\Storelocation") %}
{{ dropdown.profile_dropdown('storelocation', entity.id, true, 'btn-secondary w-100 mt-2') }}
{% endif %}
@ -136,4 +136,4 @@
{% if filterForm is defined %}
{% include "parts/lists/_filter.html.twig" %}
{% endif %}
</div>
</div>

View file

@ -28,7 +28,7 @@ use App\Entity\UserSystem\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
final class APIDocsAvailabilityTest extends WebTestCase
class APIDocsAvailabilityTest extends WebTestCase
{
#[DataProvider('urlProvider')]
public function testDocAvailabilityForLoggedInUser(string $url): void

View file

@ -27,7 +27,7 @@ use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use App\DataFixtures\APITokenFixtures;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use ApiPlatform\Symfony\Bundle\Test\Client;
final class APITokenAuthenticationTest extends ApiTestCase
class APITokenAuthenticationTest extends ApiTestCase
{
public function testUnauthenticated(): void
{

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\AuthenticatedApiTestCase;
final class ApiTokenEnpointTest extends AuthenticatedApiTestCase
class ApiTokenEnpointTest extends AuthenticatedApiTestCase
{
public function testGetCurrentToken(): void
{

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class AttachmentTypeEndpointTest extends CrudEndpointTestCase
class AttachmentTypeEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\AuthenticatedApiTestCase;
final class AttachmentsEndpointTest extends AuthenticatedApiTestCase
class AttachmentsEndpointTest extends AuthenticatedApiTestCase
{
public function testGetCollection(): void
{

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class CategoryEndpointTest extends CrudEndpointTestCase
class CategoryEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -24,7 +24,7 @@ declare(strict_types=1);
namespace App\Tests\API\Endpoints;
final class CurrencyEndpointTest extends CrudEndpointTestCase
class CurrencyEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class FootprintsEndpointTest extends CrudEndpointTestCase
class FootprintsEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace API\Endpoints;
use App\Tests\API\AuthenticatedApiTestCase;
final class InfoEndpointTest extends AuthenticatedApiTestCase
class InfoEndpointTest extends AuthenticatedApiTestCase
{
public function testGetInfo(): void
{

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class ManufacturersEndpointTest extends CrudEndpointTestCase
class ManufacturersEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -23,7 +23,7 @@ declare(strict_types=1);
namespace App\Tests\API\Endpoints;
final class MeasurementUnitsEndpointTest extends CrudEndpointTestCase
class MeasurementUnitsEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class OrderdetailsEndpointTest extends CrudEndpointTestCase
class OrderdetailsEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -23,7 +23,7 @@ declare(strict_types=1);
namespace App\Tests\API\Endpoints;
final class ParametersEndpointTest extends CrudEndpointTestCase
class ParametersEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class PartAssociationsEndpointTest extends CrudEndpointTestCase
class PartAssociationsEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -23,7 +23,7 @@ declare(strict_types=1);
namespace App\Tests\API\Endpoints;
final class PartCustomStateEndpointTest extends CrudEndpointTestCase
class PartCustomStateEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -23,7 +23,7 @@ declare(strict_types=1);
namespace App\Tests\API\Endpoints;
final class PartEndpointTest extends CrudEndpointTestCase
class PartEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class PartLotsEndpointTest extends CrudEndpointTestCase
class PartLotsEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class PricedetailsEndpointTest extends CrudEndpointTestCase
class PricedetailsEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -23,7 +23,7 @@ declare(strict_types=1);
namespace App\Tests\API\Endpoints;
final class ProjectBOMEntriesEndpointTest extends CrudEndpointTestCase
class ProjectBOMEntriesEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class ProjectsEndpointTest extends CrudEndpointTestCase
class ProjectsEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class StorageLocationsEndpointTest extends CrudEndpointTestCase
class StorageLocationsEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -25,7 +25,7 @@ namespace App\Tests\API\Endpoints;
use App\Tests\API\Endpoints\CrudEndpointTestCase;
final class SuppliersEndpointTest extends CrudEndpointTestCase
class SuppliersEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -23,7 +23,7 @@ declare(strict_types=1);
namespace App\Tests\API\Endpoints;
final class UsersEndpointTest extends CrudEndpointTestCase
class UsersEndpointTest extends CrudEndpointTestCase
{
protected function getBasePath(): string

View file

@ -32,7 +32,7 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
*/
#[Group('DB')]
#[Group('slow')]
final class ApplicationAvailabilityFunctionalTest extends WebTestCase
class ApplicationAvailabilityFunctionalTest extends WebTestCase
{
#[DataProvider('urlProvider')]
public function testPageIsSuccessful(string $url): void

View file

@ -27,7 +27,7 @@ use App\Entity\Attachments\AttachmentType;
#[Group('slow')]
#[Group('DB')]
final class AttachmentTypeController extends AbstractAdminController
class AttachmentTypeController extends AbstractAdminController
{
protected static string $base_path = '/en/attachment_type';
protected static string $entity_class = AttachmentType::class;

View file

@ -27,7 +27,7 @@ use App\Entity\Parts\Category;
#[Group('slow')]
#[Group('DB')]
final class CategoryController extends AbstractAdminController
class CategoryController extends AbstractAdminController
{
protected static string $base_path = '/en/category';
protected static string $entity_class = Category::class;

View file

@ -28,7 +28,7 @@ use App\Entity\Parts\Manufacturer;
#[Group('slow')]
#[Group('DB')]
final class CurrencyController extends AbstractAdminController
class CurrencyController extends AbstractAdminController
{
protected static string $base_path = '/en/currency';
protected static string $entity_class = Currency::class;

View file

@ -27,7 +27,7 @@ use App\Entity\Parts\Footprint;
#[Group('slow')]
#[Group('DB')]
final class FootprintController extends AbstractAdminController
class FootprintController extends AbstractAdminController
{
protected static string $base_path = '/en/footprint';
protected static string $entity_class = Footprint::class;

View file

@ -46,7 +46,7 @@ use PHPUnit\Framework\Attributes\Group;
use App\Entity\LabelSystem\LabelProfile;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class LabelProfileController extends AbstractAdminController
class LabelProfileController extends AbstractAdminController
{
protected static string $base_path = '/en/label_profile';
protected static string $entity_class = LabelProfile::class;

View file

@ -27,7 +27,7 @@ use App\Entity\Parts\Manufacturer;
#[Group('slow')]
#[Group('DB')]
final class ManufacturerController extends AbstractAdminController
class ManufacturerController extends AbstractAdminController
{
protected static string $base_path = '/en/manufacturer';
protected static string $entity_class = Manufacturer::class;

View file

@ -27,7 +27,7 @@ use App\Entity\Parts\MeasurementUnit;
#[Group('slow')]
#[Group('DB')]
final class MeasurementUnitController extends AbstractAdminController
class MeasurementUnitController extends AbstractAdminController
{
protected static string $base_path = '/en/measurement_unit';
protected static string $entity_class = MeasurementUnit::class;

View file

@ -27,7 +27,7 @@ use PHPUnit\Framework\Attributes\Group;
#[Group('slow')]
#[Group('DB')]
final class PartCustomStateControllerTest extends AbstractAdminController
class PartCustomStateControllerTest extends AbstractAdminController
{
protected static string $base_path = '/en/part_custom_state';
protected static string $entity_class = PartCustomState::class;

View file

@ -28,7 +28,7 @@ use App\Entity\ProjectSystem\Project;
#[Group('slow')]
#[Group('DB')]
final class ProjectController extends AbstractAdminController
class ProjectController extends AbstractAdminController
{
protected static string $base_path = '/en/project';
protected static string $entity_class = Project::class;

View file

@ -27,7 +27,7 @@ use App\Entity\Parts\StorageLocation;
#[Group('slow')]
#[Group('DB')]
final class StorelocationController extends AbstractAdminController
class StorelocationController extends AbstractAdminController
{
protected static string $base_path = '/en/store_location';
protected static string $entity_class = StorageLocation::class;

View file

@ -27,7 +27,7 @@ use App\Entity\Parts\Supplier;
#[Group('slow')]
#[Group('DB')]
final class SupplierController extends AbstractAdminController
class SupplierController extends AbstractAdminController
{
protected static string $base_path = '/en/supplier';
protected static string $entity_class = Supplier::class;

View file

@ -22,8 +22,6 @@ declare(strict_types=1);
namespace App\Tests\Controller;
use App\Services\InfoProviderSystem\BulkInfoProviderService;
use App\Services\InfoProviderSystem\DTOs\BulkSearchFieldMappingDTO;
use App\Entity\InfoProviderSystem\BulkImportJobStatus;
use App\Entity\InfoProviderSystem\BulkInfoProviderImportJob;
use App\Entity\Parts\Part;
@ -38,7 +36,7 @@ use Symfony\Component\HttpFoundation\Response;
#[Group("slow")]
#[Group("DB")]
final class BulkInfoProviderImportControllerTest extends WebTestCase
class BulkInfoProviderImportControllerTest extends WebTestCase
{
public function testStep1WithoutIds(): void
{
@ -176,8 +174,8 @@ final class BulkInfoProviderImportControllerTest extends WebTestCase
// Verify the template rendered the source_field and source_keyword correctly
$content = $client->getResponse()->getContent();
$this->assertStringContainsString('test_field', (string) $content);
$this->assertStringContainsString('test_keyword', (string) $content);
$this->assertStringContainsString('test_field', $content);
$this->assertStringContainsString('test_keyword', $content);
// Clean up - find by ID to avoid detached entity issues
$jobId = $job->getId();
@ -609,7 +607,7 @@ final class BulkInfoProviderImportControllerTest extends WebTestCase
}
$this->assertResponseStatusCodeSame(Response::HTTP_OK);
$this->assertStringContainsString('Bulk Info Provider Import', (string) $client->getResponse()->getContent());
$this->assertStringContainsString('Bulk Info Provider Import', $client->getResponse()->getContent());
}
public function testStep1FormSubmissionWithErrors(): void
@ -632,7 +630,7 @@ final class BulkInfoProviderImportControllerTest extends WebTestCase
}
$this->assertResponseStatusCodeSame(Response::HTTP_OK);
$this->assertStringContainsString('Bulk Info Provider Import', (string) $client->getResponse()->getContent());
$this->assertStringContainsString('Bulk Info Provider Import', $client->getResponse()->getContent());
}
public function testBulkInfoProviderServiceKeywordExtraction(): void
@ -649,18 +647,18 @@ final class BulkInfoProviderImportControllerTest extends WebTestCase
}
// Test that the service can extract keywords from parts
$bulkService = $client->getContainer()->get(BulkInfoProviderService::class);
$bulkService = $client->getContainer()->get(\App\Services\InfoProviderSystem\BulkInfoProviderService::class);
// Create field mappings to verify the service works
$fieldMappings = [
new BulkSearchFieldMappingDTO('name', ['test'], 1),
new BulkSearchFieldMappingDTO('mpn', ['test'], 2)
new \App\Services\InfoProviderSystem\DTOs\BulkSearchFieldMappingDTO('name', ['test'], 1),
new \App\Services\InfoProviderSystem\DTOs\BulkSearchFieldMappingDTO('mpn', ['test'], 2)
];
// The service may return an empty result or throw when no results are found
try {
$result = $bulkService->performBulkSearch([$part], $fieldMappings, false);
$this->assertInstanceOf(BulkSearchResponseDTO::class, $result);
$this->assertInstanceOf(\App\Services\InfoProviderSystem\DTOs\BulkSearchResponseDTO::class, $result);
} catch (\RuntimeException $e) {
$this->assertStringContainsString('No search results found', $e->getMessage());
}
@ -727,12 +725,12 @@ final class BulkInfoProviderImportControllerTest extends WebTestCase
}
// Test that the service can handle supplier part number fields
$bulkService = $client->getContainer()->get(BulkInfoProviderService::class);
$bulkService = $client->getContainer()->get(\App\Services\InfoProviderSystem\BulkInfoProviderService::class);
// Create field mappings with supplier SPN field mapping
$fieldMappings = [
new BulkSearchFieldMappingDTO('invalid_field', ['test'], 1),
new BulkSearchFieldMappingDTO('test_supplier_spn', ['test'], 2)
new \App\Services\InfoProviderSystem\DTOs\BulkSearchFieldMappingDTO('invalid_field', ['test'], 1),
new \App\Services\InfoProviderSystem\DTOs\BulkSearchFieldMappingDTO('test_supplier_spn', ['test'], 2)
];
// The service should be able to process the request and throw an exception when no results are found
@ -758,11 +756,11 @@ final class BulkInfoProviderImportControllerTest extends WebTestCase
}
// Test that the service can handle batch processing
$bulkService = $client->getContainer()->get(BulkInfoProviderService::class);
$bulkService = $client->getContainer()->get(\App\Services\InfoProviderSystem\BulkInfoProviderService::class);
// Create field mappings with multiple keywords
$fieldMappings = [
new BulkSearchFieldMappingDTO('empty', ['test'], 1)
new \App\Services\InfoProviderSystem\DTOs\BulkSearchFieldMappingDTO('empty', ['test'], 1)
];
// The service should be able to process the request and throw an exception when no results are found
@ -788,7 +786,7 @@ final class BulkInfoProviderImportControllerTest extends WebTestCase
}
// Test that the service can handle prefetch details
$bulkService = $client->getContainer()->get(BulkInfoProviderService::class);
$bulkService = $client->getContainer()->get(\App\Services\InfoProviderSystem\BulkInfoProviderService::class);
// Create empty search results to test prefetch method
$searchResults = new BulkSearchResponseDTO([

View file

@ -27,7 +27,7 @@ use App\DataFixtures\APITokenFixtures;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
final class KiCadApiControllerTest extends WebTestCase
class KiCadApiControllerTest extends WebTestCase
{
private const BASE_URL = '/en/kicad-api/v1';

View file

@ -38,7 +38,7 @@ use Symfony\Component\HttpFoundation\Response;
#[Group("slow")]
#[Group("DB")]
final class PartControllerTest extends WebTestCase
class PartControllerTest extends WebTestCase
{
public function testShowPart(): void
{

View file

@ -33,7 +33,7 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
#[Group('slow')]
#[Group('DB')]
final class RedirectControllerTest extends WebTestCase
class RedirectControllerTest extends WebTestCase
{
protected EntityManagerInterface $em;
protected UserRepository $userRepo;

View file

@ -25,7 +25,7 @@ namespace App\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
final class ScanControllerTest extends WebTestCase
class ScanControllerTest extends WebTestCase
{
private ?KernelBrowser $client = null;

View file

@ -27,7 +27,7 @@ use App\DataTables\Filters\FilterInterface;
use Doctrine\ORM\QueryBuilder;
use PHPUnit\Framework\TestCase;
final class CompoundFilterTraitTest extends TestCase
class CompoundFilterTraitTest extends TestCase
{
public function testFindAllChildFiltersEmpty(): void
@ -49,9 +49,9 @@ final class CompoundFilterTraitTest extends TestCase
public function testFindAllChildFilters(): void
{
$f1 = $this->createStub(FilterInterface::class);
$f2 = $this->createStub(FilterInterface::class);
$f3 = $this->createStub(FilterInterface::class);
$f1 = $this->createMock(FilterInterface::class);
$f2 = $this->createMock(FilterInterface::class);
$f3 = $this->createMock(FilterInterface::class);
$filter = new class($f1, $f2, $f3, null) {
use CompoundFilterTrait;
@ -108,7 +108,7 @@ final class CompoundFilterTraitTest extends TestCase
}
};
$qb = $this->createStub(QueryBuilder::class);
$qb = $this->createMock(QueryBuilder::class);
$filter->_applyAllChildFilters($qb);
}

View file

@ -26,7 +26,7 @@ use PHPUnit\Framework\Attributes\DataProvider;
use App\DataTables\Filters\Constraints\FilterTrait;
use PHPUnit\Framework\TestCase;
final class FilterTraitTest extends TestCase
class FilterTraitTest extends TestCase
{
use FilterTrait;

View file

@ -28,7 +28,7 @@ use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use PHPUnit\Framework\TestCase;
final class BulkImportJobStatusConstraintTest extends TestCase
class BulkImportJobStatusConstraintTest extends TestCase
{
private BulkImportJobStatusConstraint $constraint;
private QueryBuilder $queryBuilder;
@ -46,7 +46,7 @@ final class BulkImportJobStatusConstraintTest extends TestCase
public function testConstructor(): void
{
$this->assertSame([], $this->constraint->getValue());
$this->assertEquals([], $this->constraint->getValue());
$this->assertEmpty($this->constraint->getOperator());
$this->assertFalse($this->constraint->isEnabled());
}
@ -56,7 +56,7 @@ final class BulkImportJobStatusConstraintTest extends TestCase
$values = ['pending', 'in_progress'];
$this->constraint->setValue($values);
$this->assertSame($values, $this->constraint->getValue());
$this->assertEquals($values, $this->constraint->getValue());
}
public function testGetAndSetOperator(): void
@ -64,7 +64,7 @@ final class BulkImportJobStatusConstraintTest extends TestCase
$operator = 'ANY';
$this->constraint->setOperator($operator);
$this->assertSame($operator, $this->constraint->getOperator());
$this->assertEquals($operator, $this->constraint->getOperator());
}
public function testIsEnabledWithEmptyValues(): void

View file

@ -28,7 +28,7 @@ use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use PHPUnit\Framework\TestCase;
final class BulkImportPartStatusConstraintTest extends TestCase
class BulkImportPartStatusConstraintTest extends TestCase
{
private BulkImportPartStatusConstraint $constraint;
private QueryBuilder $queryBuilder;
@ -46,7 +46,7 @@ final class BulkImportPartStatusConstraintTest extends TestCase
public function testConstructor(): void
{
$this->assertSame([], $this->constraint->getValue());
$this->assertEquals([], $this->constraint->getValue());
$this->assertEmpty($this->constraint->getOperator());
$this->assertFalse($this->constraint->isEnabled());
}
@ -56,7 +56,7 @@ final class BulkImportPartStatusConstraintTest extends TestCase
$values = ['pending', 'completed', 'skipped'];
$this->constraint->setValue($values);
$this->assertSame($values, $this->constraint->getValue());
$this->assertEquals($values, $this->constraint->getValue());
}
public function testGetAndSetOperator(): void
@ -64,7 +64,7 @@ final class BulkImportPartStatusConstraintTest extends TestCase
$operator = 'ANY';
$this->constraint->setOperator($operator);
$this->assertSame($operator, $this->constraint->getOperator());
$this->assertEquals($operator, $this->constraint->getOperator());
}
public function testIsEnabledWithEmptyValues(): void
@ -294,6 +294,6 @@ final class BulkImportPartStatusConstraintTest extends TestCase
$this->constraint->apply($this->queryBuilder);
$this->assertSame($statusValues, $this->constraint->getValue());
$this->assertEquals($statusValues, $this->constraint->getValue());
}
}

View file

@ -44,7 +44,7 @@ namespace App\Tests;
use PHPUnit\Framework\Attributes\DataProvider;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
final class DatatablesAvailabilityTest extends WebTestCase
class DatatablesAvailabilityTest extends WebTestCase
{
#[DataProvider('urlProvider')]
public function testDataTable(string $url, ?array $ordering = null): void

View file

@ -26,7 +26,7 @@ use PHPUnit\Framework\Attributes\DataProvider;
use App\Doctrine\Middleware\SQLiteRegexExtensionMiddlewareDriver;
use PHPUnit\Framework\TestCase;
final class SQLiteRegexMiddlewareTest extends TestCase
class SQLiteRegexMiddlewareTest extends TestCase
{
public static function regexpDataProvider(): \Generator

View file

@ -55,7 +55,7 @@ use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
final class AttachmentTest extends TestCase
class AttachmentTest extends TestCase
{
public function testEmptyState(): void
{

View file

@ -28,7 +28,7 @@ use App\Entity\Attachments\UserAttachment;
use Doctrine\Common\Collections\Collection;
use PHPUnit\Framework\TestCase;
final class AttachmentTypeTest extends TestCase
class AttachmentTypeTest extends TestCase
{
public function testEmptyState(): void
{

View file

@ -31,7 +31,7 @@ use PHPUnit\Framework\TestCase;
* Test StructuralDBElement entities.
* Note: Because StructuralDBElement is abstract we use AttachmentType here as a placeholder.
*/
final class AbstractStructuralDBElementTest extends TestCase
class AbstractStructuralDBElementTest extends TestCase
{
protected AttachmentType $root;
protected AttachmentType $child1;

View file

@ -25,7 +25,7 @@ namespace App\Tests\Entity;
use App\Entity\InfoProviderSystem\BulkImportJobStatus;
use PHPUnit\Framework\TestCase;
final class BulkImportJobStatusTest extends TestCase
class BulkImportJobStatusTest extends TestCase
{
public function testEnumValues(): void
{

View file

@ -28,25 +28,32 @@ use App\Entity\InfoProviderSystem\BulkInfoProviderImportJobPart;
use App\Entity\Parts\Part;
use PHPUnit\Framework\TestCase;
final class BulkInfoProviderImportJobPartTest extends TestCase
class BulkInfoProviderImportJobPartTest extends TestCase
{
private BulkInfoProviderImportJob $job;
private Part $part;
private BulkInfoProviderImportJobPart $jobPart;
protected function setUp(): void
{
$this->jobPart = new BulkInfoProviderImportJobPart($this->createStub(BulkInfoProviderImportJob::class), $this->createStub(Part::class));
$this->job = $this->createMock(BulkInfoProviderImportJob::class);
$this->part = $this->createMock(Part::class);
$this->jobPart = new BulkInfoProviderImportJobPart($this->job, $this->part);
}
public function testConstructor(): void
{
$this->assertSame(BulkImportPartStatus::PENDING, $this->jobPart->getStatus());
$this->assertSame($this->job, $this->jobPart->getJob());
$this->assertSame($this->part, $this->jobPart->getPart());
$this->assertEquals(BulkImportPartStatus::PENDING, $this->jobPart->getStatus());
$this->assertNull($this->jobPart->getReason());
$this->assertNull($this->jobPart->getCompletedAt());
}
public function testGetAndSetJob(): void
{
$newJob = $this->createStub(BulkInfoProviderImportJob::class);
$newJob = $this->createMock(BulkInfoProviderImportJob::class);
$result = $this->jobPart->setJob($newJob);
@ -56,7 +63,7 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
public function testGetAndSetPart(): void
{
$newPart = $this->createStub(Part::class);
$newPart = $this->createMock(Part::class);
$result = $this->jobPart->setPart($newPart);
@ -69,7 +76,7 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
$result = $this->jobPart->setStatus(BulkImportPartStatus::COMPLETED);
$this->assertSame($this->jobPart, $result);
$this->assertSame(BulkImportPartStatus::COMPLETED, $this->jobPart->getStatus());
$this->assertEquals(BulkImportPartStatus::COMPLETED, $this->jobPart->getStatus());
}
public function testGetAndSetReason(): void
@ -79,7 +86,7 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
$result = $this->jobPart->setReason($reason);
$this->assertSame($this->jobPart, $result);
$this->assertSame($reason, $this->jobPart->getReason());
$this->assertEquals($reason, $this->jobPart->getReason());
}
public function testGetAndSetCompletedAt(): void
@ -101,7 +108,7 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
$afterTime = new \DateTimeImmutable();
$this->assertSame($this->jobPart, $result);
$this->assertSame(BulkImportPartStatus::COMPLETED, $this->jobPart->getStatus());
$this->assertEquals(BulkImportPartStatus::COMPLETED, $this->jobPart->getStatus());
$this->assertInstanceOf(\DateTimeImmutable::class, $this->jobPart->getCompletedAt());
$this->assertGreaterThanOrEqual($beforeTime, $this->jobPart->getCompletedAt());
$this->assertLessThanOrEqual($afterTime, $this->jobPart->getCompletedAt());
@ -117,8 +124,8 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
$afterTime = new \DateTimeImmutable();
$this->assertSame($this->jobPart, $result);
$this->assertSame(BulkImportPartStatus::SKIPPED, $this->jobPart->getStatus());
$this->assertSame($reason, $this->jobPart->getReason());
$this->assertEquals(BulkImportPartStatus::SKIPPED, $this->jobPart->getStatus());
$this->assertEquals($reason, $this->jobPart->getReason());
$this->assertInstanceOf(\DateTimeImmutable::class, $this->jobPart->getCompletedAt());
$this->assertGreaterThanOrEqual($beforeTime, $this->jobPart->getCompletedAt());
$this->assertLessThanOrEqual($afterTime, $this->jobPart->getCompletedAt());
@ -129,8 +136,8 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
$result = $this->jobPart->markAsSkipped();
$this->assertSame($this->jobPart, $result);
$this->assertSame(BulkImportPartStatus::SKIPPED, $this->jobPart->getStatus());
$this->assertSame('', $this->jobPart->getReason());
$this->assertEquals(BulkImportPartStatus::SKIPPED, $this->jobPart->getStatus());
$this->assertEquals('', $this->jobPart->getReason());
$this->assertInstanceOf(\DateTimeImmutable::class, $this->jobPart->getCompletedAt());
}
@ -144,8 +151,8 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
$afterTime = new \DateTimeImmutable();
$this->assertSame($this->jobPart, $result);
$this->assertSame(BulkImportPartStatus::FAILED, $this->jobPart->getStatus());
$this->assertSame($reason, $this->jobPart->getReason());
$this->assertEquals(BulkImportPartStatus::FAILED, $this->jobPart->getStatus());
$this->assertEquals($reason, $this->jobPart->getReason());
$this->assertInstanceOf(\DateTimeImmutable::class, $this->jobPart->getCompletedAt());
$this->assertGreaterThanOrEqual($beforeTime, $this->jobPart->getCompletedAt());
$this->assertLessThanOrEqual($afterTime, $this->jobPart->getCompletedAt());
@ -156,8 +163,8 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
$result = $this->jobPart->markAsFailed();
$this->assertSame($this->jobPart, $result);
$this->assertSame(BulkImportPartStatus::FAILED, $this->jobPart->getStatus());
$this->assertSame('', $this->jobPart->getReason());
$this->assertEquals(BulkImportPartStatus::FAILED, $this->jobPart->getStatus());
$this->assertEquals('', $this->jobPart->getReason());
$this->assertInstanceOf(\DateTimeImmutable::class, $this->jobPart->getCompletedAt());
}
@ -169,7 +176,7 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
$result = $this->jobPart->markAsPending();
$this->assertSame($this->jobPart, $result);
$this->assertSame(BulkImportPartStatus::PENDING, $this->jobPart->getStatus());
$this->assertEquals(BulkImportPartStatus::PENDING, $this->jobPart->getStatus());
$this->assertNull($this->jobPart->getReason());
$this->assertNull($this->jobPart->getCompletedAt());
}
@ -274,7 +281,7 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
// After marking as skipped, should have reason and completion time
$this->jobPart->markAsSkipped('Skipped reason');
$this->assertSame('Skipped reason', $this->jobPart->getReason());
$this->assertEquals('Skipped reason', $this->jobPart->getReason());
$this->assertInstanceOf(\DateTimeImmutable::class, $this->jobPart->getCompletedAt());
// After marking as pending, reason and completion time should be cleared
@ -284,7 +291,7 @@ final class BulkInfoProviderImportJobPartTest extends TestCase
// After marking as failed, should have reason and completion time
$this->jobPart->markAsFailed('Failed reason');
$this->assertSame('Failed reason', $this->jobPart->getReason());
$this->assertEquals('Failed reason', $this->jobPart->getReason());
$this->assertInstanceOf(\DateTimeImmutable::class, $this->jobPart->getCompletedAt());
// After marking as completed, should have completion time (reason may remain from previous state)

View file

@ -22,8 +22,6 @@ declare(strict_types=1);
namespace App\Tests\Entity;
use App\Entity\Parts\Part;
use App\Services\InfoProviderSystem\DTOs\BulkSearchPartResultsDTO;
use App\Entity\InfoProviderSystem\BulkImportJobStatus;
use App\Entity\InfoProviderSystem\BulkInfoProviderImportJob;
use App\Entity\UserSystem\User;
@ -33,7 +31,7 @@ use App\Services\InfoProviderSystem\DTOs\BulkSearchResponseDTO;
use App\Services\InfoProviderSystem\DTOs\SearchResultDTO;
use PHPUnit\Framework\TestCase;
final class BulkInfoProviderImportJobTest extends TestCase
class BulkInfoProviderImportJobTest extends TestCase
{
private BulkInfoProviderImportJob $job;
private User $user;
@ -47,9 +45,9 @@ final class BulkInfoProviderImportJobTest extends TestCase
$this->job->setCreatedBy($this->user);
}
private function createMockPart(int $id): Part
private function createMockPart(int $id): \App\Entity\Parts\Part
{
$part = $this->createMock(Part::class);
$part = $this->createMock(\App\Entity\Parts\Part::class);
$part->method('getId')->willReturn($id);
$part->method('getName')->willReturn("Test Part {$id}");
return $part;
@ -60,7 +58,7 @@ final class BulkInfoProviderImportJobTest extends TestCase
$job = new BulkInfoProviderImportJob();
$this->assertInstanceOf(\DateTimeImmutable::class, $job->getCreatedAt());
$this->assertSame(BulkImportJobStatus::PENDING, $job->getStatus());
$this->assertEquals(BulkImportJobStatus::PENDING, $job->getStatus());
$this->assertEmpty($job->getPartIds());
$this->assertEmpty($job->getFieldMappings());
$this->assertEmpty($job->getSearchResultsRaw());
@ -72,14 +70,14 @@ final class BulkInfoProviderImportJobTest extends TestCase
public function testBasicGettersSetters(): void
{
$this->job->setName('Test Job');
$this->assertSame('Test Job', $this->job->getName());
$this->assertEquals('Test Job', $this->job->getName());
// Test with actual parts - this is what actually works
$parts = [$this->createMockPart(1), $this->createMockPart(2), $this->createMockPart(3)];
foreach ($parts as $part) {
$this->job->addPart($part);
}
$this->assertSame([1, 2, 3], $this->job->getPartIds());
$this->assertEquals([1, 2, 3], $this->job->getPartIds());
$fieldMappings = [new BulkSearchFieldMappingDTO(field: 'field1', providers: ['provider1', 'provider2'])];
$this->job->setFieldMappings($fieldMappings);
@ -100,24 +98,24 @@ final class BulkInfoProviderImportJobTest extends TestCase
$this->assertFalse($this->job->isStopped());
$this->job->markAsInProgress();
$this->assertSame(BulkImportJobStatus::IN_PROGRESS, $this->job->getStatus());
$this->assertEquals(BulkImportJobStatus::IN_PROGRESS, $this->job->getStatus());
$this->assertTrue($this->job->isInProgress());
$this->assertFalse($this->job->isPending());
$this->job->markAsCompleted();
$this->assertSame(BulkImportJobStatus::COMPLETED, $this->job->getStatus());
$this->assertEquals(BulkImportJobStatus::COMPLETED, $this->job->getStatus());
$this->assertTrue($this->job->isCompleted());
$this->assertNotNull($this->job->getCompletedAt());
$job2 = new BulkInfoProviderImportJob();
$job2->markAsFailed();
$this->assertSame(BulkImportJobStatus::FAILED, $job2->getStatus());
$this->assertEquals(BulkImportJobStatus::FAILED, $job2->getStatus());
$this->assertTrue($job2->isFailed());
$this->assertNotNull($job2->getCompletedAt());
$job3 = new BulkInfoProviderImportJob();
$job3->markAsStopped();
$this->assertSame(BulkImportJobStatus::STOPPED, $job3->getStatus());
$this->assertEquals(BulkImportJobStatus::STOPPED, $job3->getStatus());
$this->assertTrue($job3->isStopped());
$this->assertNotNull($job3->getCompletedAt());
}
@ -141,7 +139,7 @@ final class BulkInfoProviderImportJobTest extends TestCase
public function testPartCount(): void
{
$this->assertSame(0, $this->job->getPartCount());
$this->assertEquals(0, $this->job->getPartCount());
// Test with actual parts - setPartIds doesn't actually add parts
$parts = [
@ -154,31 +152,31 @@ final class BulkInfoProviderImportJobTest extends TestCase
foreach ($parts as $part) {
$this->job->addPart($part);
}
$this->assertSame(5, $this->job->getPartCount());
$this->assertEquals(5, $this->job->getPartCount());
}
public function testResultCount(): void
{
$this->assertSame(0, $this->job->getResultCount());
$this->assertEquals(0, $this->job->getResultCount());
$searchResults = new BulkSearchResponseDTO([
new BulkSearchPartResultsDTO(
new \App\Services\InfoProviderSystem\DTOs\BulkSearchPartResultsDTO(
part: $this->createMockPart(1),
searchResults: [new BulkSearchPartResultDTO(searchResult: new SearchResultDTO(provider_key: 'dummy', provider_id: '1234', name: 'Part 1', description: 'A part'))]
),
new BulkSearchPartResultsDTO(
new \App\Services\InfoProviderSystem\DTOs\BulkSearchPartResultsDTO(
part: $this->createMockPart(2),
searchResults: [new BulkSearchPartResultDTO(searchResult: new SearchResultDTO(provider_key: 'dummy', provider_id: '1234', name: 'Part 2', description: 'A part')),
new BulkSearchPartResultDTO(searchResult: new SearchResultDTO(provider_key: 'dummy', provider_id: '5678', name: 'Part 2 Alt', description: 'Another part'))]
),
new BulkSearchPartResultsDTO(
new \App\Services\InfoProviderSystem\DTOs\BulkSearchPartResultsDTO(
part: $this->createMockPart(3),
searchResults: []
)
]);
$this->job->setSearchResults($searchResults);
$this->assertSame(3, $this->job->getResultCount());
$this->assertEquals(3, $this->job->getResultCount());
}
public function testPartProgressTracking(): void
@ -224,21 +222,21 @@ final class BulkInfoProviderImportJobTest extends TestCase
$this->job->addPart($part);
}
$this->assertSame(0, $this->job->getCompletedPartsCount());
$this->assertSame(0, $this->job->getSkippedPartsCount());
$this->assertEquals(0, $this->job->getCompletedPartsCount());
$this->assertEquals(0, $this->job->getSkippedPartsCount());
$this->job->markPartAsCompleted(1);
$this->job->markPartAsCompleted(2);
$this->job->markPartAsSkipped(3, 'Error');
$this->assertSame(2, $this->job->getCompletedPartsCount());
$this->assertSame(1, $this->job->getSkippedPartsCount());
$this->assertEquals(2, $this->job->getCompletedPartsCount());
$this->assertEquals(1, $this->job->getSkippedPartsCount());
}
public function testProgressPercentage(): void
{
$emptyJob = new BulkInfoProviderImportJob();
$this->assertEqualsWithDelta(100.0, $emptyJob->getProgressPercentage(), PHP_FLOAT_EPSILON);
$this->assertEquals(100.0, $emptyJob->getProgressPercentage());
// Test with actual parts - setPartIds doesn't actually add parts
$parts = [
@ -252,18 +250,18 @@ final class BulkInfoProviderImportJobTest extends TestCase
$this->job->addPart($part);
}
$this->assertEqualsWithDelta(0.0, $this->job->getProgressPercentage(), PHP_FLOAT_EPSILON);
$this->assertEquals(0.0, $this->job->getProgressPercentage());
$this->job->markPartAsCompleted(1);
$this->job->markPartAsCompleted(2);
$this->assertEqualsWithDelta(40.0, $this->job->getProgressPercentage(), PHP_FLOAT_EPSILON);
$this->assertEquals(40.0, $this->job->getProgressPercentage());
$this->job->markPartAsSkipped(3, 'Error');
$this->assertEqualsWithDelta(60.0, $this->job->getProgressPercentage(), PHP_FLOAT_EPSILON);
$this->assertEquals(60.0, $this->job->getProgressPercentage());
$this->job->markPartAsCompleted(4);
$this->job->markPartAsCompleted(5);
$this->assertEqualsWithDelta(100.0, $this->job->getProgressPercentage(), PHP_FLOAT_EPSILON);
$this->assertEquals(100.0, $this->job->getProgressPercentage());
}
public function testIsAllPartsCompleted(): void
@ -303,8 +301,8 @@ final class BulkInfoProviderImportJobTest extends TestCase
$this->job->addPart($part);
}
$this->assertSame('info_providers.bulk_import.job_name_template', $this->job->getDisplayNameKey());
$this->assertSame(['%count%' => 3], $this->job->getDisplayNameParams());
$this->assertEquals('info_providers.bulk_import.job_name_template', $this->job->getDisplayNameKey());
$this->assertEquals(['%count%' => 3], $this->job->getDisplayNameParams());
}
public function testFormattedTimestamp(): void

View file

@ -58,7 +58,7 @@ use App\Entity\UserSystem\Group;
use App\Entity\UserSystem\User;
use PHPUnit\Framework\TestCase;
final class AbstractLogEntryTest extends TestCase
class AbstractLogEntryTest extends TestCase
{
public function testSetGetTarget(): void
{

View file

@ -25,7 +25,7 @@ namespace App\Tests\Entity\LogSystem;
use App\Entity\LogSystem\LogLevel;
use PHPUnit\Framework\TestCase;
final class LogLevelTest extends TestCase
class LogLevelTest extends TestCase
{
public function testToPSR3LevelString(): void

View file

@ -30,7 +30,7 @@ use App\Entity\Parts\Category;
use App\Entity\UserSystem\User;
use PHPUnit\Framework\TestCase;
final class LogTargetTypeTest extends TestCase
class LogTargetTypeTest extends TestCase
{
public function testToClass(): void

View file

@ -45,7 +45,7 @@ use PHPUnit\Framework\Attributes\DataProvider;
use App\Entity\Parameters\PartParameter;
use PHPUnit\Framework\TestCase;
final class PartParameterTest extends TestCase
class PartParameterTest extends TestCase
{
public static function valueWithUnitDataProvider(): \Iterator
{

View file

@ -26,7 +26,7 @@ use App\Entity\Parts\InfoProviderReference;
use App\Services\InfoProviderSystem\DTOs\PartDetailDTO;
use PHPUnit\Framework\TestCase;
final class InfoProviderReferenceTest extends TestCase
class InfoProviderReferenceTest extends TestCase
{
public function testNoProvider(): void
{

View file

@ -26,7 +26,7 @@ use App\Entity\Parts\AssociationType;
use App\Entity\Parts\PartAssociation;
use PHPUnit\Framework\TestCase;
final class PartAssociationTest extends TestCase
class PartAssociationTest extends TestCase
{
public function testGetTypeTranslationKey(): void

View file

@ -26,7 +26,7 @@ use App\Entity\Parts\PartLot;
use DateTime;
use PHPUnit\Framework\TestCase;
final class PartLotTest extends TestCase
class PartLotTest extends TestCase
{
public function testIsExpired(): void
{

View file

@ -29,7 +29,7 @@ use DateTime;
use Doctrine\Common\Collections\Collection;
use PHPUnit\Framework\TestCase;
final class PartTest extends TestCase
class PartTest extends TestCase
{
public function testAddRemovePartLot(): void
{

View file

@ -26,7 +26,7 @@ use App\Entity\PriceInformations\Currency;
use Brick\Math\BigDecimal;
use PHPUnit\Framework\TestCase;
final class CurrencyTest extends TestCase
class CurrencyTest extends TestCase
{
public function testGetInverseExchangeRate(): void
{

View file

@ -27,7 +27,7 @@ use App\Entity\PriceInformations\Pricedetail;
use Doctrine\Common\Collections\Collection;
use PHPUnit\Framework\TestCase;
final class OrderdetailTest extends TestCase
class OrderdetailTest extends TestCase
{
public function testAddRemovePricdetails(): void
{

View file

@ -28,7 +28,7 @@ use App\Entity\PriceInformations\Pricedetail;
use Brick\Math\BigDecimal;
use PHPUnit\Framework\TestCase;
final class PricedetailTest extends TestCase
class PricedetailTest extends TestCase
{
public function testGetPricePerUnit(): void
{

View file

@ -25,7 +25,7 @@ namespace App\Tests\Entity\UserSystem;
use App\Entity\UserSystem\ApiTokenType;
use PHPUnit\Framework\TestCase;
final class ApiTokenTypeTest extends TestCase
class ApiTokenTypeTest extends TestCase
{
public function testGetTokenPrefix(): void

View file

@ -25,7 +25,7 @@ namespace App\Tests\Entity\UserSystem;
use App\Entity\UserSystem\PermissionData;
use PHPUnit\Framework\TestCase;
final class PermissionDataTest extends TestCase
class PermissionDataTest extends TestCase
{
public function testGetSetIs(): void

View file

@ -31,7 +31,7 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\Uid\Uuid;
use Webauthn\TrustPath\EmptyTrustPath;
final class UserTest extends TestCase
class UserTest extends TestCase
{
public function testGetFullName(): void
{

View file

@ -1,7 +1,4 @@
<?php
declare(strict_types=1);
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -20,12 +17,13 @@ declare(strict_types=1);
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace App\Tests\EnvVarProcessors;
use App\EnvVarProcessors\AddSlashEnvVarProcessor;
use PHPUnit\Framework\TestCase;
final class AddSlashEnvVarProcessorTest extends TestCase
class AddSlashEnvVarProcessorTest extends TestCase
{
protected AddSlashEnvVarProcessor $processor;

Some files were not shown because too many files have changed in this diff Show more