La regex \w+ ne capturait pas les caracteres accentues (ex. {Diametre}
avec 'è'), le placeholder restait litteral dans la reference auto.
Remplace par [^}]+ avec le flag u/gu cote PHP et JS pour matcher
n'importe quel caractere entre les accolades.
58 lines
1.6 KiB
PHP
58 lines
1.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Service;
|
|
|
|
use App\Entity\Composant;
|
|
use App\Entity\CustomFieldValue;
|
|
use App\Entity\Piece;
|
|
|
|
class ReferenceAutoGenerator
|
|
{
|
|
public function generate(Composant|Piece $entity): ?string
|
|
{
|
|
$modelType = $entity instanceof Piece
|
|
? $entity->getTypePiece()
|
|
: $entity->getTypeComposant();
|
|
|
|
if (!$modelType || !$modelType->getReferenceFormula()) {
|
|
return null;
|
|
}
|
|
|
|
$valueMap = $this->buildValueMap($entity);
|
|
|
|
$requiredFields = $modelType->getRequiredFieldsForReference();
|
|
|
|
if ($requiredFields) {
|
|
foreach ($requiredFields as $fieldName) {
|
|
if (!isset($valueMap[$fieldName]) || '' === $valueMap[$fieldName]) {
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
|
|
return preg_replace_callback('/\{([^}]+)\}/u', static function (array $matches) use ($valueMap): string {
|
|
return $valueMap[$matches[1]] ?? '';
|
|
}, $modelType->getReferenceFormula());
|
|
}
|
|
|
|
/**
|
|
* Build a map of fieldName → normalized value from the entity's CustomFieldValues.
|
|
*
|
|
* @return array<string, string>
|
|
*/
|
|
private function buildValueMap(Composant|Piece $entity): array
|
|
{
|
|
$map = [];
|
|
|
|
/** @var CustomFieldValue $cfv */
|
|
foreach ($entity->getCustomFieldValues() as $cfv) {
|
|
$normalized = mb_strtoupper(trim($cfv->getValue()));
|
|
$map[$cfv->getCustomField()->getName()] = $normalized;
|
|
}
|
|
|
|
return $map;
|
|
}
|
|
}
|