Files
esun3d/app/code/Esun/Customer/ViewModel/AddressBook.php
T
2026-09-15 10:35:56 +08:00

63 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\Customer\ViewModel;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Directory\Api\CountryInformationAcquirerInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Element\Block\ArgumentInterface;
class AddressBook implements ArgumentInterface
{
public function __construct(
private readonly CountryInformationAcquirerInterface $countryInformationAcquirer
) {
}
public function getName(AddressInterface $address): string
{
return implode(' ', array_filter([
$address->getPrefix(),
$address->getFirstname(),
$address->getMiddlename(),
$address->getLastname(),
$address->getSuffix(),
], static fn ($part): bool => trim((string) $part) !== ''));
}
public function getStreetLines(AddressInterface $address): array
{
return array_values(array_filter(
$address->getStreet() ?? [],
static fn ($line): bool => trim((string) $line) !== ''
));
}
public function getLocalityLine(AddressInterface $address): string
{
$region = $address->getRegion();
return implode(', ', array_filter([
$address->getCity(),
$region ? $region->getRegion() : null,
$address->getPostcode(),
], static fn ($part): bool => trim((string) $part) !== ''));
}
public function getCountryName(AddressInterface $address): string
{
$countryId = (string) $address->getCountryId();
if ($countryId === '') {
return '';
}
try {
$country = $this->countryInformationAcquirer->getCountryInfo($countryId);
return (string) ($country->getFullNameLocale() ?: $country->getFullNameEnglish() ?: $countryId);
} catch (NoSuchEntityException) {
return $countryId;
}
}
}