Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Rector\BetterPhpDocParser\PhpDocNode\Symfony\Validator\Constraints;

use Nette\Utils\Strings;
use Rector\BetterPhpDocParser\Contract\PhpDocNode\ShortNameAwareTagInterface;
use Rector\BetterPhpDocParser\Contract\PhpDocNode\TypeAwareTagValueNodeInterface;
use Rector\Symfony\PhpDocParser\Ast\PhpDoc\AbstractConstraintTagValueNode;
Expand All @@ -25,6 +26,16 @@ final class AssertChoiceTagValueNode extends AbstractConstraintTagValueNode impl
*/
private $choices;

/**
* @var string|null
*/
private $originalChoiceContent;

/**
* @var bool
*/
private $hasChoiceKeywordExplicit = false;

/**
* @param mixed[]|string|null $callback
*/
Expand All @@ -34,6 +45,12 @@ public function __construct($callback, ?bool $strict, string $annotationContent,
$this->strict = $strict;
$this->resolveOriginalContentSpacingAndOrder($annotationContent);
$this->choices = $choices;

// is default key
$this->hasChoiceKeywordExplicit = (bool) Strings::match($annotationContent, '#choices=#');

// hotfix for https://github.com/rectorphp/rector/issues/3044, the constant reference is actually parsed to values
$this->originalChoiceContent = $this->resolveOriginalChoiceContent($annotationContent);
}

public function __toString(): string
Expand All @@ -47,7 +64,7 @@ public function __toString(): string
$contentItems['callback'] = sprintf('callback="%s"', $this->callback);
}
} elseif ($this->choices) {
$contentItems[] = $this->printArrayItem($this->choices);
$contentItems[] = $this->createChoices();
}

if ($this->strict !== null) {
Expand All @@ -71,4 +88,41 @@ public function getShortName(): string
{
return '@Assert\Choice';
}

private function isClassConstantReference(?string $originalChoiceContent): bool
{
if ($originalChoiceContent === null) {
return false;
}

return Strings::contains($originalChoiceContent, '::');
}

private function createOriginalChoiceContent()
{
$content = '';
if ($this->hasChoiceKeywordExplicit) {
$content = 'choices=';
}

return $content . $this->originalChoiceContent;
}

private function resolveOriginalChoiceContent(string $annotationContent): ?string
{
$matches = Strings::match($annotationContent, '#(\(choices=|\()(?<choice_content>.*?)(\)|,)#ms');
Comment thread
TomasVotruba marked this conversation as resolved.

return $matches['choice_content'] ?? null;
}

private function createChoices(): string
{
if ($this->isClassConstantReference($this->originalChoiceContent)) {
return $this->createOriginalChoiceContent();
}

assert(is_array($this->choices));

return $this->printArrayItem($this->choices);
}
}