devel_wizard-2.x-dev/templates/spell/entity_type/config/comparer.php.twig
templates/spell/entity_type/config/comparer.php.twig
{%
include '@devel_wizard/php/devel_wizard.php.file.header.php.twig'
with {
'namespace': config.namespace,
}
%}
class Comparer {
protected int $result = 0;
protected array $fieldNames = [
'weight',
'label',
];
public function getFieldNames(): array {
return $this->fieldNames;
}
public function setFieldNames(array $fieldNames): static {
$this->fieldNames = $fieldNames;
return $this;
}
protected bool $ascending = TRUE;
public function isAscending(): bool {
return $this->ascending;
}
public function setAscending(bool $ascending): static {
$this->ascending = $ascending;
return $this;
}
public function __invoke($a, $b): int {
return $this->compare($a, $b);
}
public function compare($a, $b): int {
return $this
->initResult()
->setResult($a, $b)
->getResult();
}
protected function getResult(): int {
if ($this->result === 0 || $this->isAscending()) {
return $this->result;
}
return $this->result > 0 ? -1 : 1;
}
/**
* @param \{{ config.interface_fqn }} $a
* @param \{{ config.interface_fqn }} $b
*/
protected function setResult($a, $b): static {
foreach ($this->fieldNames as $fieldName) {
$this->result = $a->get($fieldName) <=> $b->get($fieldName);
if ($this->result !== 0) {
return $this;
}
}
return $this;
}
protected function initResult(): static {
$this->result = 0;
return $this;
}
}
