ApiDocReimportSpecForm.php in Apigee API Catalog 8.2
File
src/Entity/Form/ApiDocReimportSpecForm.php
View source
<?php
namespace Drupal\apigee_api_catalog\Entity\Form;
use Drupal\apigee_api_catalog\SpecFetcherInterface;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\ContentEntityConfirmFormBase;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ApiDocReimportSpecForm extends ContentEntityConfirmFormBase {
protected $messenger;
protected $specFetcher;
protected $operation = 'reimport_spec';
public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info, TimeInterface $time, MessengerInterface $messenger, SpecFetcherInterface $spec_fetcher) {
parent::__construct($entity_repository, $entity_type_bundle_info, $time);
$this->messenger = $messenger;
$this->specFetcher = $spec_fetcher;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity.repository'), $container
->get('entity_type.bundle.info'), $container
->get('datetime.time'), $container
->get('messenger'), $container
->get('apigee_api_catalog.spec_fetcher'));
}
public function checkAccess(RouteMatchInterface $route_match, AccountInterface $account) {
$entity = $route_match
->getParameter('node');
return AccessResult::allowedIf($entity
->bundle() == 'apidoc' && $entity
->access('update', $account));
}
public function getQuestion() {
return $this
->t('Are you sure you want to update the OpenAPI specification file from URL on API Doc %name?', [
'%name' => $this->entity
->label(),
]);
}
public function getCancelUrl() {
return new Url('view.api_catalog_admin.page_1');
}
public function getDescription() {
return $this
->t('This will replace the current OpenAPI specification file.
This action cannot be undone.');
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$entity = $this
->getEntity();
if ($entity
->get('field_apidoc_spec_file_source')->value != SpecFetcherInterface::SPEC_AS_URL) {
$this
->messenger()
->addStatus($this
->t('API Doc %label is using a local file as the the source, there nothing to import.', [
'%label' => $this->entity
->label(),
]));
return;
}
$fetch_status = $this->specFetcher
->fetchSpec($entity);
if ($fetch_status != SpecFetcherInterface::STATUS_ERROR) {
if ($entity
->getEntityType()
->isRevisionable()) {
$entity
->setNewRevision();
}
$entity
->save();
$this
->messenger()
->addStatus($this
->t('API Doc %label: imported the OpenAPI specification file from URL.', [
'%label' => $this->entity
->label(),
]));
}
}
}