Skip to content

Commit

Permalink
Move path detection to static function (less closures)
Browse files Browse the repository at this point in the history
  • Loading branch information
veewee committed Jun 12, 2024
1 parent 327434d commit e87d790
Showing 1 changed file with 21 additions and 19 deletions.
40 changes: 21 additions & 19 deletions src/Encoder/ErrorHandlingEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,45 +30,47 @@ public function __construct(
public function iso(Context $context): Iso
{
$innerIso = $this->encoder->iso($context);
$buildPath = static function () use ($context): ?string {
$meta = $context->type->getMeta();
$isElement = $meta->isElement()->unwrapOr(false);
$isAttribute = $meta->isAttribute()->unwrapOr(false);
if (!$isElement && !$isAttribute) {
return null;
}

$path = $context->type->getXmlTargetNodeName();
if ($isAttribute) {
return '@' . $path;
}

return $path;
};

return new Iso(
/**
* @psalm-param TData $value
* @psalm-return TXml
*/
static function (mixed $value) use ($innerIso, $context, $buildPath): mixed {
static function (mixed $value) use ($innerIso, $context): mixed {
try {
return $innerIso->to($value);
} catch (Throwable $exception) {
throw EncodingException::encodingValue($value, $context->type, $exception, $buildPath());
throw EncodingException::encodingValue($value, $context->type, $exception, self::buildPath($context));
}
},
/**
* @psalm-param TXml $value
* @psalm-return TData
*/
static function (mixed $value) use ($innerIso, $context, $buildPath): mixed {
static function (mixed $value) use ($innerIso, $context): mixed {
try {
return $innerIso->from($value);
} catch (Throwable $exception) {
throw EncodingException::decodingValue($value, $context->type, $exception, $buildPath());
throw EncodingException::decodingValue($value, $context->type, $exception, self::buildPath($context));
}
}
);
}

private static function buildPath(Context $context): ?string
{
$meta = $context->type->getMeta();
$isElement = $meta->isElement()->unwrapOr(false);
$isAttribute = $meta->isAttribute()->unwrapOr(false);
if (!$isElement && !$isAttribute) {
return null;
}

$path = $context->type->getXmlTargetNodeName();
if ($isAttribute) {
return '@' . $path;
}

return $path;
}
}

0 comments on commit e87d790

Please sign in to comment.