diff --git a/info.log b/info.log new file mode 100644 index 00000000..e69de29b diff --git a/modules/quant_api/src/Client/QuantClient.php b/modules/quant_api/src/Client/QuantClient.php index 8d408809..c9d345f8 100644 --- a/modules/quant_api/src/Client/QuantClient.php +++ b/modules/quant_api/src/Client/QuantClient.php @@ -10,9 +10,10 @@ use Drupal\quant_api\Exception\InvalidPayload; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\MultipartStream; /** - * + * Quant API client. */ class QuantClient implements QuantClientInterface { @@ -82,7 +83,7 @@ public function ping() { ]); } catch (RequestException $e) { - \Drupal::messenger()->addError(t($e->getMessage())); + \Drupal::messenger()->addError($e->getMessage()); return FALSE; } @@ -90,6 +91,16 @@ public function ping() { return TRUE; } + if ($response->getStatusCode() == 402) { + // Emit a subscription invalid warning. + \Drupal::messenger()->addError(t('Your Quant subscription is invalid. Please check the dashboard.')); + } + + if ($response->getStatusCode() == 410) { + // Emit a deleted project warning. + \Drupal::messenger()->addError(t('Project is deleted. Please check the dashboard for restoration options.')); + } + return FALSE; } @@ -150,7 +161,7 @@ public function sendFile(string $file, string $url, int $rid = NULL) : array { 'POST', $this->endpoint, $headers, - new Psr7\MultipartStream([ + new MultipartStream([ [ 'name' => basename($file), 'filename' => basename($file), @@ -180,7 +191,7 @@ public function unpublish(string $url) : array { 'Quant-Customer' => $this->username, 'Quant-Project' => $this->project, 'Quant-Token' => $this->token, - ] + ], ]); return json_decode($response->getBody(), TRUE); diff --git a/modules/quant_api/src/EventSubscriber/QuantApi.php b/modules/quant_api/src/EventSubscriber/QuantApi.php index c3c30af0..a7be3430 100644 --- a/modules/quant_api/src/EventSubscriber/QuantApi.php +++ b/modules/quant_api/src/EventSubscriber/QuantApi.php @@ -46,6 +46,10 @@ class QuantApi implements EventSubscriberInterface { * * @param \Drupal\quant_api\Client\QuantClientInterface $client * The Drupal HTTP Client to make requests. + * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory + * The logger channel factory. + * @param \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $event_dispatcher + * The event dispatcher. */ public function __construct(QuantClientInterface $client, LoggerChannelFactoryInterface $logger_factory, ContainerAwareEventDispatcher $event_dispatcher) { $this->client = $client; @@ -78,7 +82,7 @@ public function onRedirect(QuantRedirectEvent $event) { $data = [ 'url' => $source, 'redirect_url' => $dest, - 'redirect_http_code' => (int)$statusCode, + 'redirect_http_code' => (int) $statusCode, 'published' => TRUE, ]; @@ -92,7 +96,6 @@ public function onRedirect(QuantRedirectEvent $event) { return $res; } - /** * Trigger an API request with the event data. * @@ -114,6 +117,10 @@ public function onOutput(QuantEvent $event) { 'proxy_override' => $meta['proxy_override'], ]; + if (isset($meta['content_type'])) { + $data['headers']['content_type'] = $meta['content_type']; + } + if (!empty($rid = $event->getRevisionId())) { $data['revision'] = $rid; } @@ -151,9 +158,9 @@ public function onOutput(QuantEvent $event) { if (file_exists(DRUPAL_ROOT . $file)) { $this->eventDispatcher->dispatch(QuantFileEvent::OUTPUT, new QuantFileEvent(DRUPAL_ROOT . $file, $file)); } - else if (strpos($url, '/styles/')) { - // Image style derivative does not exist. - // Quant API returns an expected full_path item which allows for image generation. + elseif (strpos($url, '/styles/')) { + // Image style derivative does not exist. Quant API returns an expected + // full_path item which allows for image generation. if (isset($item['full_path'])) { // Build internal request. $config = \Drupal::config('quant.settings'); @@ -187,8 +194,8 @@ public function onOutput(QuantEvent $event) { /** @var \DOMElement $node */ $pager_operations = []; - // @todo: Make this xpath configurable. - // This supports the use case for core views output (mini and standard pager). + // This supports the use case for core views (mini and standard pager). + // @TODO: selector should be configurable. foreach ($xpath->query('//a[contains(@href,"page=") and (./span[contains(text(), "Next")])]') as $node) { $original_href = $node->getAttribute('href'); if ($original_href[0] === '?') { @@ -214,7 +221,6 @@ public function onOutput(QuantEvent $event) { batch_set($batch); } - // @todo: Report on forms that need proxying (attachments.forms). } @@ -234,9 +240,11 @@ public function onMedia(QuantFileEvent $event) { } catch (InvalidPayload $error) { $this->logger->error($error->getMessage()); + return; } catch (Exception $error) { $this->logger->error($error->getMessage()); + return; } return $res; diff --git a/modules/quant_api/src/Form/SettingsForm.php b/modules/quant_api/src/Form/SettingsForm.php index be1bc8fc..699025e7 100644 --- a/modules/quant_api/src/Form/SettingsForm.php +++ b/modules/quant_api/src/Form/SettingsForm.php @@ -56,7 +56,8 @@ public function buildForm(array $form, FormStateInterface $form_state) { if ($config->get('api_token')) { if ($project = $this->client->ping()) { - \Drupal::messenger()->addMessage(t('Successfully connected to ' . $config->get('api_project'))); + $message = t('Successfully connected to @api', ['@api' => $config->get('api_project')]); + \Drupal::messenger()->addMessage($message); } else { \Drupal::messenger()->addError(t('Unable to connect to Quant API, check settings.')); diff --git a/modules/quant_api/tests/src/Unit/QuantClientTest.php b/modules/quant_api/tests/src/Unit/QuantClientTest.php index becea901..c31e2547 100644 --- a/modules/quant_api/tests/src/Unit/QuantClientTest.php +++ b/modules/quant_api/tests/src/Unit/QuantClientTest.php @@ -11,7 +11,6 @@ use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\Response; use GuzzleHttp\RequestOptions; -use Drupal\quant_api\Exception\InvalidPayload; /** * Ensure that the client responds correctly. @@ -21,7 +20,8 @@ class QuantClientTest extends UnitTestCase { /** * Get a stubbed config factory. * - * @return ConfigFactoryInterface + * @return \Drupal\Core\Config\ConfigFactoryInterface + * The config interface. */ protected function getConfigStub($default = []) { $value = [ @@ -45,12 +45,13 @@ protected function getConfigStub($default = []) { * Get a successful project response. * * @return GuzzleHttp\Psr7\Response + * A response object. */ protected function getProjectResponse() { // @TODO - should these be fixtures. $body = [ 'project' => 'test', - 'error' => false, + 'error' => FALSE, 'errorMsg' => '', ]; @@ -65,6 +66,7 @@ protected function getProjectResponse() { * A valid redirect response. * * @return GuzzleHttp\Psr7\Response + * A response object. */ protected function getRedirectResponse() { $body = [ @@ -73,7 +75,7 @@ protected function getRedirectResponse() { 'url' => '/a', 'redirect_http_code' => 302, 'errorMsg' => '', - 'error' => false, + 'error' => FALSE, ]; $res = $this->prophesize(Response::class); @@ -87,10 +89,11 @@ protected function getRedirectResponse() { * Get an invalid response. * * @return GuzzleHttp\Psr7\Response + * A response object. */ protected function getInvalidResponse() { $body = [ - 'error' => true, + 'error' => TRUE, 'errorMsg' => 'Error', ]; @@ -239,7 +242,7 @@ public function testSendRedirectValid() { 'url' => '/a', 'redirect_http_code' => 302, 'errorMsg' => '', - 'error' => false, + 'error' => FALSE, ], $redirect); } @@ -272,7 +275,9 @@ public function testSendRedirectError() { * @expectedException Drupal\quant_api\Exception\InvalidPayload */ public function testSendFileFileNoExist() { + // phpcs:ignore global $exists_return; + // phpcs:ignore global $readable_return; $exists_return = FALSE; @@ -290,7 +295,9 @@ public function testSendFileFileNoExist() { * Ensure files are validated before sending. */ public function testSendFileValid() { + // phpcs:ignore global $exists_return; + // phpcs:ignore global $readable_return; $exists_return = TRUE; @@ -332,6 +339,7 @@ public function testSendFileValid() { * Stub file_exists. */ function file_exists($path) { + // phpcs:ignore global $exists_return; if (isset($exists_return)) { return $exists_return; @@ -343,6 +351,7 @@ function file_exists($path) { * Stub is_readable. */ function is_readable($path) { + // phpcs:ignore global $readable_return; if (isset($readable_return)) { return $readable_return; diff --git a/modules/quant_cron/quant_cron.module b/modules/quant_cron/quant_cron.module index 31c5d33e..e9740adb 100644 --- a/modules/quant_cron/quant_cron.module +++ b/modules/quant_cron/quant_cron.module @@ -1,5 +1,10 @@ loadMultiple(); $content_types = []; - foreach($types as $type) { + foreach ($types as $type) { $content_types[$type->id()] = $type->label(); } diff --git a/modules/quant_sitemap/quant_sitemap.module b/modules/quant_sitemap/quant_sitemap.module index 27cd74c7..f8769eb3 100644 --- a/modules/quant_sitemap/quant_sitemap.module +++ b/modules/quant_sitemap/quant_sitemap.module @@ -1,6 +1,7 @@ entityTypeManager; @@ -111,7 +113,7 @@ public function collectRoutes(CollectRoutesEvent $event) { if ($this->moduleHandler->moduleExists('simple_sitemap')) { $items = $this->getSimpleSitemapItems(); } - else if ($this->moduleHandler->moduleExists('xmlsitemap')) { + elseif ($this->moduleHandler->moduleExists('xmlsitemap')) { $items = $this->getXmlsitemapItems(); } diff --git a/quant.install b/quant.install index f0515a8f..8c37be0a 100644 --- a/quant.install +++ b/quant.install @@ -1,7 +1,5 @@ getEntityTypeId()) { + switch ($entity->getEntityTypeId()) { case 'node': Seed::seedNode($entity); - break; + break; + case 'taxonomy_term': Seed::seedTaxonomyTerm($entity); - break; + break; } } @@ -239,14 +239,14 @@ function _quant_entity_update_op($entity) { /** * Entity delete operation hook. * - * Used to trigger an unpublish from the Quant API. - * - * @TODO: Entity support. - * * @param Drupal\Core\Entity\EntityInterface $entity * The entity. + * + * Used to trigger an unpublish from the Quant API. + * + * @TODO: Entity support. */ -function _quant_entity_delete_op($entity) { +function _quant_entity_delete_op(EntityInterface $entity) { if ($entity->getEntityTypeId() != 'node') { return; } diff --git a/src/Controller/QuantNodeViewController.php b/src/Controller/QuantNodeViewController.php index 2bf62939..49a06d7c 100644 --- a/src/Controller/QuantNodeViewController.php +++ b/src/Controller/QuantNodeViewController.php @@ -47,6 +47,12 @@ class QuantNodeViewController extends NodeViewController { * this will be removed before Drupal 9.0.0. * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository * The entity repository. + * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack + * The request stack. + * @param \Drupal\Core\Routing\CurrentRouteMatch $route_match + * The route matcher. + * @param \Drupal\Core\Session\AccountSwitcherInterface $account_switcher + * The account switcher interface. */ public function __construct(EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer, AccountInterface $current_user = NULL, EntityRepositoryInterface $entity_repository = NULL, RequestStack $request_stack, CurrentRouteMatch $route_match, AccountSwitcherInterface $account_switcher) { parent::__construct($entity_type_manager, $renderer, $current_user, $entity_repository); diff --git a/src/Event/CollectEntitiesEvent.php b/src/Event/CollectEntitiesEvent.php index c747422c..3ce7ab25 100644 --- a/src/Event/CollectEntitiesEvent.php +++ b/src/Event/CollectEntitiesEvent.php @@ -15,10 +15,6 @@ class CollectEntitiesEvent extends ConfigFormEventBase { /** * A list of entity ids that are to be exported. * - * @TODO: See memory usage by storing a class list - * of all entities. We might need to simplify this - * hash to be [id, type]. - * * @var array */ protected $entities; @@ -59,8 +55,9 @@ public function includeRevisions() { * The language code of the entity. * * @return self + * The class instance. */ - public function addEntity($entity, $langcode=NULL) { + public function addEntity($entity, $langcode = NULL) { $this->entities[] = [ 'entity' => $entity, 'langcode' => $langcode, @@ -73,6 +70,7 @@ public function addEntity($entity, $langcode=NULL) { * Get an entity from the evetn. * * @return mixed + * A single entity. */ public function getEntity() { return array_shift($this->entities); diff --git a/src/Event/CollectFilesEvent.php b/src/Event/CollectFilesEvent.php index 6bb7eae7..496be256 100644 --- a/src/Event/CollectFilesEvent.php +++ b/src/Event/CollectFilesEvent.php @@ -34,6 +34,7 @@ public function __construct(array $filePaths = [], FormStateInterface $state = N * The entity object. * * @return self + * The class instance. */ public function addFilePath($path) { $this->filePaths[] = $path; @@ -41,9 +42,10 @@ public function addFilePath($path) { } /** - * Get an entity from the evetn. + * Get an entity from the event. * * @return mixed + * The next file path. */ public function getFilePath() { return array_shift($this->filePaths); diff --git a/src/Event/CollectRedirectsEvent.php b/src/Event/CollectRedirectsEvent.php index 92c1fb24..f5931ca6 100644 --- a/src/Event/CollectRedirectsEvent.php +++ b/src/Event/CollectRedirectsEvent.php @@ -34,6 +34,7 @@ public function __construct(array $entities = [], FormStateInterface $state = NU * The entity object. * * @return self + * The class instance. */ public function addEntity($entity) { $this->entities[] = $entity; @@ -44,6 +45,7 @@ public function addEntity($entity) { * Get an entity from the evetn. * * @return mixed + * A single entity. */ public function getEntity() { return array_shift($this->entities); diff --git a/src/Event/CollectRoutesEvent.php b/src/Event/CollectRoutesEvent.php index 586f77e3..c71eda33 100644 --- a/src/Event/CollectRoutesEvent.php +++ b/src/Event/CollectRoutesEvent.php @@ -43,7 +43,8 @@ public function getSetting($key) { * @var string $route * The entity object. * - * @return self + * @return Drupal\quant\Event\CollectRoutesEvent + * The route collection event. */ public function addRoute($route) { $this->routes[] = $route; @@ -51,9 +52,10 @@ public function addRoute($route) { } /** - * Get an entity from the evetn. + * Get an route from the event. * * @return string + * A route. */ public function getRoute() { return array_shift($this->routes); diff --git a/src/Event/NodeInsertEvent.php b/src/Event/NodeInsertEvent.php index 39100563..ef6b289f 100644 --- a/src/Event/NodeInsertEvent.php +++ b/src/Event/NodeInsertEvent.php @@ -22,16 +22,19 @@ class NodeInsertEvent extends Event { /** * Language code for export. * - * @var string $langcode + * @var string */ + protected $langcode; /** * Constructs a node insertion demo event object. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity object. + * @param string $langcode + * A two character langcode. */ - public function __construct(EntityInterface $entity, $langcode=NULL) { + public function __construct(EntityInterface $entity, $langcode = NULL) { $this->entity = $entity; $this->langcode = $langcode; } @@ -50,6 +53,7 @@ public function getEntity() { * Get the language code associated with the event. * * @return string + * The language code for the event. */ public function getLangcode() { return $this->langcode; diff --git a/src/EventSubscriber/CollectionSubscriber.php b/src/EventSubscriber/CollectionSubscriber.php index 1e1c9300..97217cb6 100644 --- a/src/EventSubscriber/CollectionSubscriber.php +++ b/src/EventSubscriber/CollectionSubscriber.php @@ -22,6 +22,8 @@ class CollectionSubscriber implements EventSubscriberInterface { /** * The entity type manager. + * + * @var \Drupal\Core\Entity\EntityTypeManager */ protected $entityTypeManager; diff --git a/src/EventSubscriber/NodeInsertSubscriber.php b/src/EventSubscriber/NodeInsertSubscriber.php index 6e439a39..640fbd82 100644 --- a/src/EventSubscriber/NodeInsertSubscriber.php +++ b/src/EventSubscriber/NodeInsertSubscriber.php @@ -4,7 +4,6 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Drupal\quant\Event\NodeInsertEvent; -use Drupal\quant\EntityRendererInterface; use Drupal\quant\Plugin\QuantMetadataManager; use Drupal\quant\Seed; @@ -27,6 +26,7 @@ public function __construct(QuantMetadataManager $metadata_manager) { * Log the creation of a new node. * * @param \Drupal\quant\Event\NodeInsertEvent $event + * The event interface. */ public function onNodeInsert(NodeInsertEvent $event) { $entity = $event->getEntity(); diff --git a/src/Form/MetadataConfigForm.php b/src/Form/MetadataConfigForm.php index 775c0f07..d918ac7f 100644 --- a/src/Form/MetadataConfigForm.php +++ b/src/Form/MetadataConfigForm.php @@ -5,6 +5,9 @@ use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\FormStateInterface; +/** + * The metadata configuration form. + */ class MetadataConfigForm extends ConfigFormBase { const SETTINGS = 'quant.metadata.settings'; @@ -25,6 +28,9 @@ protected function getEditableConfigNames() { ]; } + /** + * {@inheritdoc} + */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config(static::SETTINGS); @@ -77,4 +83,5 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $config->save(); parent::submitForm($form, $form_state); } + } diff --git a/src/Form/SeedForm.php b/src/Form/SeedForm.php index 7b660db5..a080c471 100644 --- a/src/Form/SeedForm.php +++ b/src/Form/SeedForm.php @@ -2,7 +2,6 @@ namespace Drupal\quant\Form; -use Drupal\node\Entity\Node; use Drupal\quant\Seed; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; @@ -14,6 +13,7 @@ use Drupal\quant\QuantStaticTrait; use Drupal\quant_api\Client\QuantClientInterface; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Contains a form for initializing a static build. @@ -32,14 +32,16 @@ class SeedForm extends FormBase { protected $client; /** + * The event dispatcher. * + * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface */ protected $dispatcher; /** * Build the form. */ - public function __construct(QuantClientInterface $client, $event_dispatcher) { + public function __construct(QuantClientInterface $client, EventDispatcherInterface $event_dispatcher) { $this->client = $client; $this->dispatcher = $event_dispatcher; } @@ -55,14 +57,14 @@ public static function create(ContainerInterface $container) { } /** - * {@inheritdoc}. + * {@inheritdoc} */ public function getFormId() { return 'quant_seed_form'; } /** - * {@inheritdoc}. + * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { @@ -126,7 +128,7 @@ public function buildForm(array $form, FormStateInterface $form_state) { ->loadMultiple(); $content_types = []; - foreach($types as $type) { + foreach ($types as $type) { $content_types[$type->id()] = $type->label(); } @@ -255,8 +257,17 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $routes = array_merge($routes, Seed::findLunrRoutes()); } - $config->set('routes_export', $form_state->getValue('routes_textarea'))->save(); $config->set('routes', $form_state->getValue('routes'))->save(); + $config->set('routes_export', $form_state->getValue('routes_textarea'))->save(); + + if ($form_state->getValue('routes_textarea')) { + foreach (explode(PHP_EOL, $form_state->getValue('routes')) as $route) { + if (strpos((trim($route)), '/') !== 0) { + continue; + } + $routes[] = trim($route); + } + } $batch = [ 'title' => t('Exporting to Quant...'), @@ -287,6 +298,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $event = new CollectRoutesEvent($routes, $form_state); $this->dispatcher->dispatch(QuantCollectionEvents::ROUTES, $event); + while ($route = $event->getRoute()) { $batch['operations'][] = ['\Drupal\quant\Seed::exportRoute', [$route]]; } diff --git a/src/Plugin/Quant/Metadata/ProxyOverride.php b/src/Plugin/Quant/Metadata/ProxyOverride.php index 3af23125..48c1fad3 100644 --- a/src/Plugin/Quant/Metadata/ProxyOverride.php +++ b/src/Plugin/Quant/Metadata/ProxyOverride.php @@ -20,7 +20,9 @@ class ProxyOverride extends MetadataBase implements ContainerFactoryPluginInterface { /** - * @var EntityStorage + * The entity type manager. + * + * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityManager; @@ -48,10 +50,10 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public function build(EntityInterface $entity) : array { - // Proxies are created manually and usually not something you want to replace. - // This is a globally configurable to allow override, just in case. + // Proxies are created manually and usually not something you want to + // replace. This is a globally configurable to allow override just in case. $config = \Drupal::config('quant.settings'); - $proxy_override = boolval($config->get('proxy_override', true)); + $proxy_override = boolval($config->get('proxy_override', TRUE)); return ['proxy_override' => $proxy_override]; } diff --git a/src/Plugin/Quant/Metadata/Published.php b/src/Plugin/Quant/Metadata/Published.php index 73a48a1e..03f977e0 100644 --- a/src/Plugin/Quant/Metadata/Published.php +++ b/src/Plugin/Quant/Metadata/Published.php @@ -20,7 +20,9 @@ class Published extends MetadataBase implements ContainerFactoryPluginInterface { /** - * @var EntityStorage + * The entity type manager. + * + * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityManager; @@ -48,9 +50,9 @@ public static function create(ContainerInterface $container, array $configuratio * {@inheritdoc} */ public function build(EntityInterface $entity) : array { - // Note: This approach returns the default published state of the parent node. - // This should be used to make content non-viewable if it is unpublished. - // $default = $this->entityManager->getStorage($entity->getEntityTypeId())->load($entity->id()); + // Note: This approach returns the default published state of the parent + // node. This should be used to make content non-viewable if it is + // unpublished. // Return the published status of the revision. return ['published' => $entity->isPublished()]; } diff --git a/src/Plugin/Quant/Metadata/PublishedRevision.php b/src/Plugin/Quant/Metadata/PublishedRevision.php index 004447b0..440e8c85 100644 --- a/src/Plugin/Quant/Metadata/PublishedRevision.php +++ b/src/Plugin/Quant/Metadata/PublishedRevision.php @@ -20,7 +20,9 @@ class PublishedRevision extends MetadataBase implements ContainerFactoryPluginInterface { /** - * @var EntityStorage + * The entity type manager. + * + * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityManager; diff --git a/src/Plugin/QuantMetadataManager.php b/src/Plugin/QuantMetadataManager.php index c92011c7..a00038d4 100644 --- a/src/Plugin/QuantMetadataManager.php +++ b/src/Plugin/QuantMetadataManager.php @@ -30,7 +30,7 @@ public function __construct(\Traversable $namespaces, CacheBackendInterface $cac /** * {@inheritdoc} */ - public function createInstance($plugin_id, array $configuration = array()) { + public function createInstance($plugin_id, array $configuration = []) { $plugin = parent::createInstance($plugin_id, $configuration); $config = \Drupal::config(MetadataConfigForm::SETTINGS)->get($plugin_id) ?: []; diff --git a/src/Seed.php b/src/Seed.php index c2ceb007..73b7d989 100644 --- a/src/Seed.php +++ b/src/Seed.php @@ -9,7 +9,6 @@ use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Url; - /** * Seed Manager. * @@ -59,15 +58,16 @@ public static function exportRedirect($redirect, &$context) { */ public static function exportRoute($route, &$context) { $message = "Processing route: {$route}"; + $response = self::markupFromRoute($route); - $markup = self::markupFromRoute($route); - - if (empty($markup)) { + if (empty($response)) { return; } + list($markup, $content_type) = $response; + $config = \Drupal::config('quant.settings'); - $proxy_override = boolval($config->get('proxy_override', false)); + $proxy_override = boolval($config->get('proxy_override', FALSE)); $meta = [ 'info' => [ @@ -78,6 +78,7 @@ public static function exportRoute($route, &$context) { 'transitions' => [], 'proxy_override' => $proxy_override, 'content_timestamp' => time(), + 'content_type' => $content_type, ]; \Drupal::service('event_dispatcher')->dispatch(QuantEvent::OUTPUT, new QuantEvent($markup, $route, $meta)); @@ -103,7 +104,7 @@ public static function exportFile($file, &$context) { } /** - * + * Batch finish callback for the seed. */ public static function finishedSeedCallback($success, $results, $operations) { // The 'success' parameter means no fatal PHP errors were detected. All @@ -122,6 +123,7 @@ public static function finishedSeedCallback($success, $results, $operations) { /** * Find lunr assets. + * * This includes static output from the lunr module. */ public static function findLunrAssets() { @@ -150,6 +152,7 @@ public static function findLunrAssets() { /** * Find lunr routes. + * * Determine URLs lunr indexes are exposed on. */ public static function findLunrRoutes() { @@ -170,6 +173,12 @@ public static function seedRedirect($redirect) { $source = $redirect->getSourcePathWithQuery(); $destination = $redirect->getRedirectUrl()->toString(); $statusCode = $redirect->getStatusCode(); + + if (!(bool) $statusCode && !$redirect->isNew()) { + \Drupal::service('event_dispatcher')->dispatch(QuantEvent::UNPUBLISH, new QuantEvent('', $source, [], NULL)); + return; + } + \Drupal::service('event_dispatcher')->dispatch(QuantRedirectEvent::UPDATE, new QuantRedirectEvent($source, $destination, $statusCode)); } @@ -178,14 +187,13 @@ public static function seedRedirect($redirect) { */ public static function deleteRedirect($redirect) { $source = $redirect->getSourcePathWithQuery(); - $destination = $redirect->getRedirectUrl()->toString(); \Drupal::service('event_dispatcher')->dispatch(QuantEvent::UNPUBLISH, new QuantEvent('', $source, [], NULL)); } /** * Seeds taxonomy term. */ - public static function seedTaxonomyTerm($entity, $langcode=NULL) { + public static function seedTaxonomyTerm($entity, $langcode = NULL) { $tid = $entity->get('tid')->value; $options = ['absolute' => FALSE]; @@ -195,12 +203,16 @@ public static function seedTaxonomyTerm($entity, $langcode=NULL) { } $url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $tid], $options)->toString(); - $markup = self::markupFromRoute($url); + $response = self::markupFromRoute($url); + if (empty($response)) { + return; + } $meta = []; + list($markup, $content_type) = $response; - if (empty($markup)) { - return; + if (!empty($content_type)) { + $meta['content_type'] = $content_type; } $metaManager = \Drupal::service('plugin.manager.quant.metadata'); @@ -216,9 +228,15 @@ public static function seedTaxonomyTerm($entity, $langcode=NULL) { /** * Trigger an internal http request to retrieve node markup. + * * Seeds an individual node update to Quant. + * + * @param \Drupal\Core\Entity\EntityInterface $entity + * A node interface. + * @param string $langcode + * The node language. */ - public static function seedNode($entity, $langcode=NULL) { + public static function seedNode(EntityInterface $entity, $langcode = NULL) { $nid = $entity->get('nid')->value; $rid = $entity->get('vid')->value; @@ -238,7 +256,7 @@ public static function seedNode($entity, $langcode=NULL) { if ((strpos($front, '/node/') === 0) && $nid == substr($front, 6)) { if ($entity->isPublished() && $entity->isDefaultRevision()) { // Trigger redirect event from alias to home. - \Drupal::service('event_dispatcher')->dispatch(QuantRedirectEvent::UPDATE, new QuantRedirectEvent($url, "/", 301)); + \Drupal::service('event_dispatcher')->dispatch(QuantRedirectEvent::UPDATE, new QuantRedirectEvent($url, "/", 301)); } $url = "/"; } @@ -246,16 +264,20 @@ public static function seedNode($entity, $langcode=NULL) { // Generate a request token. $token = \Drupal::service('quant.token_manager')->create($nid); - $markup = self::markupFromRoute($url, [ + $response = self::markupFromRoute($url, [ 'quant-revision' => $rid, 'quant-token' => $token, ]); $meta = []; - - if (empty($markup)) { + if (empty($response)) { return; } + list($markup, $content_type) = $response; + + if (!empty($content_type)) { + $meta['content_type'] = $content_type; + } $metaManager = \Drupal::service('plugin.manager.quant.metadata'); foreach ($metaManager->getDefinitions() as $pid => $def) { @@ -311,8 +333,8 @@ public static function unpublishRoute(EntityInterface $entity) { * * @param string $route * The route to collect markup from. - * @param array $query - * Query parameters to add to the route. + * @param array $headers + * Headers to add to the request. * * @return string|bool * The markup from the $route. @@ -343,27 +365,28 @@ protected static function markupFromRoute($route, array $headers = []) { 'allow_redirects' => FALSE, ]); - $markup = ''; + $markup = $content_type = ''; + + $response->getHeader('content-type'); if ($response->getStatusCode() == 301 || $response->getStatusCode() == 302) { $destination = reset($response->getHeader('Location')); - // Ensure relative for internal redirect. $destination = self::rewriteRelative($destination); - \Drupal::service('event_dispatcher')->dispatch(QuantRedirectEvent::UPDATE, new QuantRedirectEvent($route, $destination, $response->getStatusCode())); return FALSE; } if ($response->getStatusCode() == 200) { $markup = $response->getBody(); + $content_type = $response->getHeader('content-type'); } else { $messenger = \Drupal::messenger(); $messenger->addMessage("Non-200 response for {$route}: " . $response->getStatusCode(), $messenger::TYPE_WARNING); } - return $markup; + return [$markup, $content_type]; } diff --git a/src/TokenManager.php b/src/TokenManager.php index ad82d45f..d2670bdf 100644 --- a/src/TokenManager.php +++ b/src/TokenManager.php @@ -34,8 +34,10 @@ class TokenManager { /** * Construct a TokenManager instance. * - * @param Drupal\Core\Database\Connection $connection + * @param \Drupal\Core\Database\Connection $connection * The database connection. + * @param \Symfony\Component\HttpFoundation\RequestStack $request + * The current request stack. */ public function __construct(Connection $connection, RequestStack $request) { $this->connection = $connection;