o365-2.0.3/modules/o365_teams/src/Controller/TeamsRecipientAutocompleteController.php
modules/o365_teams/src/Controller/TeamsRecipientAutocompleteController.php
<?php
namespace Drupal\o365_teams\Controller;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\o365\GraphService;
use Microsoft\Graph\Model\User;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Custom controller for the autocomplete callback.
*/
final class TeamsRecipientAutocompleteController extends ControllerBase {
/**
* The graph service.
*
* @var \Drupal\o365\GraphService
*/
protected $graphService;
/**
* Constructor for our custom controller.
*
* @param \Drupal\o365\GraphService $graphService
* The Graph service.
*/
public function __construct(GraphService $graphService) {
$this->graphService = $graphService;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('o365.graph'));
}
/**
* Handle our autocomplete request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request where we can get the parameters from.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* The JSON response used in the form.
*
* @throws \Drupal\Core\TempStore\TempStoreException
* @throws \GuzzleHttp\Exception\GuzzleException
* @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
*/
public function handleAutocomplete(Request $request) {
$results = [];
$input = $request->query->get('q');
// Get the typed string from the URL, if it exists.
if (!$input) {
return new JsonResponse($results);
}
// XSS clean the input.
$input = Xss::filter($input);
// Set the endpoint and do the request.
$endpoint = '/me/people/?$search=' . $input . '&$select=displayName,personType,userPrincipalName&$top=20&$filter=personType/class eq \'Person\' and personType/subclass eq \'OrganizationUser\'';
$data = $this->graphService->getGraphData($endpoint, 'GET', FALSE, FALSE, User::class);
if (!empty($data)) {
/** @var \Microsoft\Graph\Model\User $user */
foreach ($data as $user) {
$results[] = [
'value' => $user->getDisplayName() . ' (' . $user->getUserPrincipalName() . ')',
'label' => $user->getDisplayName(),
];
}
}
return new JsonResponse($results);
}
}
