Skip to content

Commit bfc8313

Browse files
committed
Refactor AssociativeArray::toString()
1 parent 82be42e commit bfc8313

1 file changed

Lines changed: 24 additions & 6 deletions

File tree

‎src/Constraint/AssociativeArray.php‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -76,15 +76,33 @@ public function __construct(array $constraints, bool $allowMissing = false, bool
7676
*/
7777
public function toString(): string
7878
{
79-
$constraintDescriptions = [];
79+
if (!$this->constraints) {
80+
return $this->allowAdditional ? 'is an associative array' : 'is an empty array';
81+
}
82+
83+
$templateArguments = [];
8084
foreach ($this->constraints as $key => $constraint) {
81-
$constraintDescriptions[] = 'has the key ' . $this->exporter()->export($key) . ' '
82-
. 'whose value ' . $constraint->toString();
85+
$templateArguments[] = $this->exporter()->export($key);
86+
$templateArguments[] = $constraint->toString();
8387
}
8488

85-
return 'is an associative array that '
86-
. implode(!$this->allowMissing ? ' and ' : ' and/or ', $constraintDescriptions)
87-
. ($this->allowAdditional ? ' or any other item' : '');
89+
$itemConjunction = !$this->allowMissing ? 'and' : 'and/or';
90+
$itemCount = count($this->constraints);
91+
92+
if ($this->allowAdditional) {
93+
$itemTemplate = sprintf(', %s has the key %%s whose value %%s', $itemConjunction);
94+
$template = 'is an associative array that has the key %s whose value %s'
95+
. str_repeat($itemTemplate, $itemCount - 1)
96+
. sprintf(', %s any other item', $itemConjunction);
97+
98+
return vsprintf($template, $templateArguments);
99+
} else {
100+
$itemTemplate = sprintf(', %s the key %%s whose value %%s', $itemConjunction);
101+
$template = 'is an associative array that has just the key %s whose value %s'
102+
. str_repeat($itemTemplate, $itemCount - 1);
103+
104+
return vsprintf($template, $templateArguments);
105+
}
88106
}
89107

90108
/**

0 commit comments

Comments
 (0)