webex_client-1.0.5/src/Controller/MakeDefaultController.php
src/Controller/MakeDefaultController.php
<?php
declare(strict_types=1);
namespace Drupal\webex_client\Controller;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Url;
use Drupal\webex_client\Entity\Webex;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Returns responses for webex routes.
*
* This controller handles the setting of a Webex entity as default,
* ensuring that only one Webex entity can be set as default at a time.
*/
final class MakeDefaultController extends ControllerBase {
/**
* Builds the response for setting a Webex entity as default.
*
* This method sets the provided Webex entity as default and unsets all other
* Webex entities as default. It then redirects to the collection of Webex
* entities.
*
* @param \Drupal\webex_client\Entity\Webex $webex
* The Webex entity to be set as default.
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
* A redirect response to the collection of Webex entities.
*/
public function __invoke(Webex $webex): RedirectResponse {
$callback_url = Url::fromRoute('entity.webex.collection')
->setAbsolute()
->toString();
try {
// Set the provided Webex entity as default.
$webex->setDefault()->save();
// Unset all other Webex entities as default.
$wIds = $this->entityTypeManager()
->getStorage('webex')
->getQuery()
->accessCheck()
->condition('id', $webex->id(), '<>')
->execute();
if ($wIds) {
$entities = Webex::loadMultiple($wIds);
foreach ($entities as $entity) {
$entity->setDefault(FALSE)->save();
}
}
$this->messenger()->addMessage(
$this->t('The @webex has been set as default.', ['@webex' => $webex->label()])
);
}
catch (EntityStorageException | InvalidPluginDefinitionException | PluginNotFoundException $e) {
$this->getLogger('webex_client')->error('Failed to set default Webex entity: @error', [
'@error' => $e->getMessage(),
'exception' => $e,
]);
$this->messenger()->addError(
$this->t('Could not set @webex as default. Please try again or contact the administrator.', [
'@webex' => $webex->label(),
])
);
}
catch (\Exception $e) {
$this->getLogger('webex_client')->error('Unexpected error: @error', [
'@error' => $e->getMessage(),
'exception' => $e,
]);
$this->messenger()->addError(
$this->t('An unexpected error occurred. Please contact the administrator.')
);
}
return new RedirectResponse($callback_url);
}
}
