Skip to content
Snippets Groups Projects
Commit 4de08fc9 authored by Anna Demianik's avatar Anna Demianik
Browse files

Issue #3491975 by anna d: Code Styling & Coding standart issue

parent 27e41337
No related branches found
No related tags found
1 merge request!4#3491975: Code standards and code styling
Pipeline #361138 passed with warnings
# https://git.drupalcode.org/project/gitlab_templates/
include:
- project: $_GITLAB_TEMPLATES_REPO
ref: $_GITLAB_TEMPLATES_REF
file:
- '/includes/include.drupalci.main.yml'
- '/includes/include.drupalci.variables.yml'
- '/includes/include.drupalci.workflows.yml'
phpcs:
allow_failure: false
phpstan:
allow_failure: false
......@@ -2,56 +2,54 @@
/**
* @file
* Custom functionality for bing indexing api.
* Contains hook implementations for bing_indexing_api module.
*/
use Drupal\Core\Entity\EntityInterface;
declare(strict_types=1);
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\node\NodeInterface;
/**
* Implements hook_help().
*/
function bing_indexing_api_help($route_name, RouteMatchInterface $route_match) {
function bing_indexing_api_help(string $route_name, RouteMatchInterface $route_match): string {
switch ($route_name) {
case 'help.page.bing_indexing_api':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The module provides Microsoft Bing Indexing API and service for URL Submission Tool') . '</p>';
return $output;
default:
return '';
}
}
/**
* Implements hook_node_predelete().
*/
function bing_indexing_api_node_predelete(NodeInterface $node) {
// Update url only if deleting published node.
if ($node->get("moderation_state")->getString() == 'published') {
\Drupal::service('bing_index_api.client')->updateUrl($node->toUrl()
function bing_indexing_api_node_predelete(NodeInterface $node): void {
// Update the URL only if deleting a published node.
if ($node->isPublished()) {
\Drupal::service('bing_indexing_api.client')->reindexUrl($node->toUrl()
->toString());
}
}
/**
* Implements hook_entity_presave().
* Implements hook_entity_ENTITY_TYPE_presave().
*/
function bing_indexing_api_entity_presave(EntityInterface $entity) {
if ($entity instanceof NodeInterface) {
if ($entity->isDefaultRevision() && $entity->original) {
$statusAfter = $entity->get('status')->first()->getValue()['value'];
$statusBefore = $entity->original->get('status')
->first()
->getValue()['value'];
// Update url only if unpublish node.
if ($statusBefore == 1 && $statusAfter == 0) {
\Drupal::service('bing_index_api.client')->updateUrl($entity->toUrl()
->toString());
}
function bing_indexing_api_node_presave(NodeInterface $node): void {
$original = !empty($node->original) ? $node->original : NULL;
if ($original && $node->isDefaultRevision()) {
// Trigger URL reindexing only if the node status changes from
// published to unpublished.
if ($original->isPublished() && !$node->isPublished()) {
\Drupal::service('bing_indexing_api.client')->reindexUrl($node->toUrl()
->toString());
}
}
}
services:
bing_index_api.client:
class: Drupal\bing_indexing_api\Service\BingIndexApi
arguments: ['@state', '@logger.factory', '@http_client']
bing_indexing_api.client:
class: Drupal\bing_indexing_api\Service\BingIndexingApi
arguments: ['@state', '@logger.channel.bing_indexing_api', '@http_client']
logger.channel.bing_indexing_api:
parent: logger.channel_base
arguments: [ 'bing_indexing_api' ]
parameters:
level: 8
ignoreErrors:
- identifier: missingType.iterableValue
\ No newline at end of file
......@@ -14,34 +14,38 @@ class BingIndexApiBatch {
*
* @param string $url
* The url string we are checking.
* @param object &$context
* @param array &$context
* The batch context object.
*/
public static function batchProcess($url, &$context) {
// Show message.
$message = t('Now checking %url', ['%url' => $url]);
$context['message'] = '<h2>' . $message . '</h2>';
\Drupal::service('bing_index_api.client')->updateUrl($url);
// Set the result.
public static function batchProcess(string $url, array &$context): void {
$context['message'] = t('Preprocessing %url', ['%url' => $url]);
\Drupal::service('bing_indexing_api.client')->reindexUrl($url);
$context['results']['final'][] = $url;
}
/**
* Batch finished callback.
* Finish callback for our batch processing.
*
* @param bool $success
* Whether the batch completed successfully.
* @param array $results
* The results array.
* @param array $operations
* The operations array.
*/
public static function batchFinished($success, $results, $operations) {
public static function batchFinished(bool $success, array $results, array $operations): void {
if ($success) {
$message = \Drupal::translation()->formatPlural(count($results), 'One URL updated.', '@count urls updated.');
$message = \Drupal::translation()
->formatPlural(count($results), 'One URL updated.', '@count urls updated.');
\Drupal::messenger()->addStatus($message);
}
else {
$error_operation = reset($operations);
\Drupal::messenger()->addError(t('An error occurred while processing @operation with arguments : @args', [
'@operation' => $error_operation[0],
'@args' => print_r($error_operation[0], TRUE),
]));
\Drupal::messenger()
->addError(t('An error occurred while processing @operation with arguments : @args', [
'@operation' => $error_operation[0],
'@args' => print_r($error_operation[0], TRUE),
]));
}
}
......
......@@ -5,42 +5,24 @@ namespace Drupal\bing_indexing_api\Form;
use Drupal\Core\Extension\ModuleExtensionList;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class BulkUpdateForm.
* Provides BingBulkUpdateForm for URLs submission.
*/
class BingBulkUpdateForm extends FormBase {
/**
* The Messenger service.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* The list of available modules.
*
* @var \Drupal\Core\Extension\ModuleExtensionList
* Constructor.
*/
protected $extensionListModule;
/**
* Class constructor.
*/
public function __construct(MessengerInterface $messenger, ModuleExtensionList $extension_list_module) {
$this->messenger = $messenger;
$this->extensionListModule = $extension_list_module;
public function __construct(protected ModuleExtensionList $extensionListModule) {
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('messenger'),
public static function create(ContainerInterface $container): self {
return new self(
$container->get('extension.list.module')
);
}
......@@ -48,26 +30,20 @@ class BingBulkUpdateForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
public function getFormId(): string {
return 'bing_index_api_bulk_update_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['get'] = [
'#type' => 'markup',
'#markup' => '<h2>' . $this->t('Import your list below') . '</h2>',
];
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['urls'] = [
'#type' => 'textarea',
'#title' => $this->t('Urls to upload'),
'#states' => [
'visible' => [':input[name="upload"]' => ['checked' => FALSE]],
],
'#required' => TRUE,
'#title' => $this->t('URLs for submission through Bing Webmaster Tools'),
'#description' => $this->t('Provide the absolute URLs you wish to reindex in Bing, each on a new line.'),
];
$form['submit'] = [
......@@ -81,21 +57,7 @@ class BingBulkUpdateForm extends FormBase {
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
// Validate the form here instead of using required.
$urls = $form_state->getValue('urls');
if (empty($urls)) {
$form_state->setErrorByName('urls', 'You can\'t leave this blank');
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
public function submitForm(array &$form, FormStateInterface $form_state): void {
// Process the URLS.
$urls = $this->processUrls($form_state);
foreach ($urls as $url) {
......@@ -120,36 +82,38 @@ class BingBulkUpdateForm extends FormBase {
batch_set($batch);
}
else {
$this->messenger->addMessage($this->t('No Valid URLs to Process!'));
$this->messenger()->addMessage($this->t('No valid URLs to process.'));
}
}
/**
* Make all the urls happy via text or file.
* Parses the URLs into an array.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Obvious form objects.
* Form State object.
*
* @return mixed
* The parsed happiness of urls to win.
* @return array
* The parsed urls.
*/
protected function processUrls(FormStateInterface $form_state) {
// Grab the urls.
protected function processUrls(FormStateInterface $form_state): array {
$urls = $form_state->getValue('urls');
// If the text box.
$urls = preg_split("/\r\n|\n|\r/", $urls);
// Put the URLs into an array and try to get them in the best
// format possible for domination.
$parsed_urls = [];
if (!$urls || !is_string($urls)) {
return [];
}
$urls = preg_split('/\r\n|\n|\r/', $urls);
if (!$urls) {
return [];
}
// Validate urls and make an array.
foreach ($urls as $url) {
$url = trim(preg_replace("/\s+/", " ", $url));
$url = preg_replace('/\s+/', ' ', $url) ?: '';
$url = trim($url);
if (filter_var($url, FILTER_VALIDATE_URL)) {
$parsed_urls[] = parse_url($url, PHP_URL_PATH);
}
}
return $parsed_urls;
return $parsed_urls ?? [];
}
}
......@@ -4,47 +4,33 @@ namespace Drupal\bing_indexing_api\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Link;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Url;
use Drupal\file\FileUsage\FileUsageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class SettingsForm.
* Provides Bing Settings Form.
*/
class BingSettingsForm extends FormBase {
/**
* Drupal\Core\State\StateInterface definition.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* Drupal\file\FileUsage\FileUsageInterface definition.
*
* @var \Drupal\file\FileUsage\FileUsageInterface
*/
protected $fileUsage;
/**
* Constructs a new SettingsForm object.
* Constructs a new BingSettingsForm object.
*
* @param \Drupal\Core\State\StateInterface $state
* The State Service.
* @param \Drupal\file\FileUsage\FileUsageInterface $file_usage
* @param \Drupal\file\FileUsage\FileUsageInterface $fileUsage
* The file usage service.
*/
public function __construct(StateInterface $state, FileUsageInterface $file_usage) {
$this->state = $state;
$this->fileUsage = $file_usage;
public function __construct(protected StateInterface $state, protected FileUsageInterface $fileUsage) {
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
public static function create(ContainerInterface $container): self {
return new self(
$container->get('state'),
$container->get('file.usage')
);
......@@ -53,19 +39,14 @@ class BingSettingsForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
public function getFormId(): string {
return 'bing_index_api_settings_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['info'] = [
'#type' => 'item',
'#title' => $this->t('Access Bing Webmaster Tools to obtain your API key'),
];
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['top'] = [
'#type' => 'fieldset',
'#title' => $this->t('Settings'),
......@@ -76,15 +57,19 @@ class BingSettingsForm extends FormBase {
$form['top']['bing_index_api_base_domain'] = [
'#type' => 'textfield',
'#title' => $this->t('The Base Domain of the site'),
'#description' => $this->t('Please, inform the site domain'),
'#description' => $this->t('Provide the site domain.'),
'#default_value' => $this->state->get('bing_index_api_base_domain'),
'#required' => TRUE,
];
$form['top']['bing_index_api_key'] = [
'#type' => 'textfield',
'#title' => $this->t('Api key'),
'#title' => $this->t('API key'),
'#default_value' => $this->state->get('bing_index_api_key'),
'#description' => $this->t('Follow @instruction_link to configure Bing and get API key.', [
'@instruction_link' => Link::fromTextAndUrl($this->t('instruction'), Url::fromUri('https://learn.microsoft.com/en-us/bingwebmaster/getting-access#using-api-key'))
->toString(),
]),
'#required' => TRUE,
];
......@@ -99,14 +84,9 @@ class BingSettingsForm extends FormBase {
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Grab the values.
$apiKey = $form_state->getValue('bing_index_api_key');
$domain = $form_state->getValue('bing_index_api_base_domain');
// Save to use else where.
$this->state->set('bing_index_api_key', $apiKey);
$this->state->set('bing_index_api_base_domain', $domain);
public function submitForm(array &$form, FormStateInterface $form_state): void {
$this->state->set('bing_index_api_key', $form_state->getValue('bing_index_api_key'));
$this->state->set('bing_index_api_base_domain', $form_state->getValue('bing_index_api_base_domain'));
}
}
<?php
namespace Drupal\bing_indexing_api\Service;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use GuzzleHttp\ClientInterface;
/**
* Service class for calling the Bing Indexing API.
*
* @ingroup bing_index_api
*/
class BingIndexApi {
/**
* The Google Index API End Point.
*/
const END_POINT = 'https://www.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=';
/**
* Drupal\Core\State\StateInterface definition.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* The logger factory.
*
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $loggerFactory;
/**
* The GuzzleHttp Client.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $client;
/**
* Callback Controller constructor.
*
* @param \Drupal\Core\State\StateInterface $state
* The State Service.
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $loggerFactory
* The Logging Service.
* @param \GuzzleHttp\ClientInterface $client
* Http Client.
*/
public function __construct(StateInterface $state, LoggerChannelFactoryInterface $loggerFactory, ClientInterface $client) {
$this->state = $state;
$this->loggerFactory = $loggerFactory->get('Bing Index API');
$this->client = $client;
}
/**
* Update url in the Bing Index API.
*
* @param string $url
* The url we are updating.
*/
public function updateUrl($url) {
$this->callApi($url);
}
/**
* Mechanism to call the API.
*
* @param string $url
* The url we are calling.
*/
protected function callApi($url) {
$domain = $this->state->get('bing_index_api_base_domain');
$apiKey = $this->state->get('bing_index_api_key');
if (!$domain || !$apiKey) {
$this->loggerFactory->error('Please check Bing Api settings: domain and key');
return;
}
$response = $this->client->post(self::END_POINT . $apiKey, [
'json' => [
'siteUrl' => $domain,
'urlList' => [$domain . $url],
],
'headers' => [
'Content-type' => 'application/json; charset=utf-8',
],
]);
$status_code = $response->getStatusCode();
// Let the peoples know what happened.
switch ($status_code) {
case '200':
$this->loggerFactory->notice('Successfully updated %url', [
'%url' => $url,
]);
break;
default:
$body = json_decode($response->getBody()->getContents(), TRUE);
$msg = $body["error"]["message"] ?? 'Bing Index API Returned a Status code of ' . $status_code;
$this->loggerFactory->error($msg);
break;
}
}
}
<?php
namespace Drupal\bing_indexing_api\Service;
use Drupal\Component\Serialization\Json;
use Drupal\Core\State\StateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;
/**
* Service class for calling the Bing Indexing API.
*
* @ingroup bing_index_api
*/
class BingIndexingApi {
use StringTranslationTrait;
/**
* The Bing Index API End Point.
*/
const END_POINT = 'https://www.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=';
/**
* Constructs BingIndexingApi.
*
* @param \Drupal\Core\State\StateInterface $state
* The State Service.
* @param \Psr\Log\LoggerInterface $logger
* The Logging Service.
* @param \GuzzleHttp\ClientInterface $client
* Http Client.
*/
public function __construct(protected StateInterface $state, protected LoggerInterface $logger, protected ClientInterface $client) {
}
/**
* Reindex url in the Bing Index API.
*
* @param string $url
* The URL to be reindexed.
*/
public function reindexUrl(string $url): void {
$this->callApi($url);
}
/**
* Requests URL reindexing in the Bing API.
*
* @param string $url
* The url to reindex in the Bing.
*/
private function callApi(string $url): void {
$base_domain = $this->state->get('bing_index_api_base_domain');
$api_key = $this->state->get('bing_index_api_key');
if (!$base_domain || !$api_key) {
$this->logger->error($this->t('Check the Bing API settings: the domain or API key is missing.'));
return;
}
try {
$response = $this->client->request('POST', self::END_POINT . $api_key, [
'json' => [
'siteUrl' => $base_domain,
'urlList' => [$base_domain . $url],
],
'headers' => [
'Content-type' => 'application/json; charset=utf-8',
],
]);
$status_code = $response->getStatusCode();
switch ($status_code) {
case '200':
$this->logger->notice('The Bing Index API: successfully updated @url', ['@url' => $url]);
break;
default:
$body = Json::decode($response->getBody()->getContents());
$body = is_array($body) ? $body : [];
$this->logger->error($this->t('The Bing Index API returned a status code of @status_code for @url. Response message: @message', [
'@status_code' => $status_code,
'@url' => $url,
'@message' => $body['error']['message'] ?? '',
]));
}
}
catch (\Exception | GuzzleException $exception) {
$this->logger->error($exception->getMessage());
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment