breezy_utility-1.0.x-dev/src/Controller/BreezyUtilityPropertyController.php
src/Controller/BreezyUtilityPropertyController.php
<?php
namespace Drupal\breezy_utility\Controller;
use Drupal\breezy_utility\BreezyUtilityClassServiceInterface;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Provides autocomplete for property names.
*/
final class BreezyUtilityPropertyController extends ControllerBase {
/**
* Utility class service definition.
*
* @var \Drupal\breezy_utility\BreezyUtilityClassServiceInterface
*/
protected $classService;
/**
* Constructs a new BreezyUtilityPropertyController object.
*
* @param \Drupal\breezy_utility\BreezyUtilityClassServiceInterface $class_service
* The class service.
*/
public function __construct(BreezyUtilityClassServiceInterface $class_service) {
$this->classService = $class_service;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('breezy_utility.utility_classes')
);
}
/**
* Autocomplete callback.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* The response object.
*/
public function handleAutocomplete(Request $request) {
$matches = [];
$matched_array = [];
$search = $request->query->get('q');
$options = $this->classService->getPropertyOptions();
if (!empty($options)) {
$matched_array = array_filter($options, function ($key, $value) use ($search) {
return str_contains(strtolower($key), strtolower($search))
|| str_contains(strtolower($value), strtolower($search));
}, ARRAY_FILTER_USE_BOTH);
}
if (!empty($matched_array)) {
foreach ($matched_array as $key => $label) {
$matches[] = [
'value' => $key,
'label' => $label,
];
}
}
return new JsonResponse($matches);
}
}
