AddressValidator.php in Drupal Commerce Connector for AvaTax 8
File
src/Controller/AddressValidator.php
View source
<?php
namespace Drupal\commerce_avatax\Controller;
use CommerceGuys\Addressing\Country\CountryRepositoryInterface;
use Drupal\commerce_avatax\AvataxLibInterface;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\Renderer;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class AddressValidator extends ControllerBase {
protected $avataxLib;
protected $renderer;
protected $countryRepository;
public function __construct(AvataxLibInterface $avatax_lib, Renderer $renderer, CountryRepositoryInterface $country_repository) {
$this->avataxLib = $avatax_lib;
$this->renderer = $renderer;
$this->countryRepository = $country_repository;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('commerce_avatax.avatax_lib'), $container
->get('renderer'), $container
->get('address.country_repository'));
}
public function process(Request $request) {
$content = $request
->getContent();
if (empty($content)) {
return new JsonResponse([
'valid' => FALSE,
'output' => NULL,
], 400);
}
$data = $this->avataxLib
->validateAddress(Json::decode($content));
if (!empty($data['suggestion'])) {
$data['output'] = $this
->formatSuggestedAddress($data['original'], $data['suggestion'], $data['fields']);
$data['payload'] = base64_encode(Json::encode($data['suggestion']));
}
elseif (!empty($data['original']) && !$data['valid']) {
$data['output'] = $this
->formatSuggestedAddress($data['original']);
}
return new JsonResponse($data);
}
protected function formatSuggestedAddress(array $original, array $suggestion = [], array $fields = []) {
$countries = $this->countryRepository
->getAll();
if (isset($original['country_code'])) {
$original['country_code'] = $countries[$original['country_code']] ?? $original['country_code'];
}
if (isset($suggestion['country_code'])) {
$suggestion['country_code'] = $countries[$suggestion['country_code']] ?? $suggestion['country_code'];
}
$build = [
'#theme' => 'avatax_address',
'#original' => $original,
'#suggestion' => $suggestion,
'#fields' => $fields,
];
return $this->renderer
->renderPlain($build);
}
}