xero-8.x-2.x-dev/src/Controller/XeroAutocompleteController.php
src/Controller/XeroAutocompleteController.php
<?php
namespace Drupal\xero\Controller;
use Drupal\Component\Utility\Html;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\TypedData\TypedDataManagerInterface;
use Drupal\xero\XeroQuery;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Xero autocomplete controller.
*
* @internal
*/
class XeroAutocompleteController implements ContainerInjectionInterface {
/**
* Xero query.
*
* @var \Drupal\xero\XeroQuery
*/
protected $query;
/**
* Typed data manager.
*
* @var \Drupal\Core\TypedData\TypedDataManagerInterface
*/
protected $typedDataManager;
/**
* Create a new instance of the controller with dependency injection.
*
* @param \Drupal\xero\XeroQuery $query
* The xero query class.
* @param \Drupal\Core\TypedData\TypedDataManagerInterface $typedDataManager
* The typed data manager.
*/
public function __construct(XeroQuery $query, TypedDataManagerInterface $typedDataManager) {
$this->query = $query;
$this->typedDataManager = $typedDataManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('xero.query'),
$container->get('typed_data_manager')
);
}
/**
* Queries Xero for data filtered by the data type name.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The Symfony Request object.
* @param string $type
* The Xero type.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* A JSON response of potential guid and label matches as key/value pairs.
*
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function autocomplete(Request $request, $type) {
$search = $request->query->get('q');
$matches = NULL;
$ignore_case = $request->query->has('ignore-case') ? TRUE : FALSE;
$definition = $this->typedDataManager->createDataDefinition($type);
/** @var \Drupal\xero\TypedData\XeroItemInterface $class */
$class = $definition->getClass();
$this->query
->setType($type)
->setMethod('get');
if ($class::getXeroProperty('label')) {
if ($ignore_case) {
// If search is not case-sensitive, convert both the search string and
// the operator to lower case.
$search = strtolower($search);
$operator = 'ToLower().Contains';
}
else {
$operator = 'Contains';
}
$this->query->addCondition($class::getXeroProperty('label'), $search, $operator);
}
else {
$this->query->setId($search);
}
$items = $this->query->execute();
if (!empty($items)) {
$matches = [];
foreach ($items as $item) {
$key = $item->get($class::getXeroProperty('guid_name'))->getValue();
$label = $class::getXeroProperty('label') ? $item->get($class::getXeroProperty('label'))->getValue() : $key;
$key .= $key !== $label ? ' (' . $label . ')' : '';
$matches[] = ['value' => $key, 'label' => Html::escape($label)];
}
}
return new JsonResponse($matches);
}
}
