Skip to content
Snippets Groups Projects
Commit b5fe3aac authored by Eirik Morland's avatar Eirik Morland Committed by Vladimir Roudakov
Browse files

Issue #3271897 by VladimirAus, eiriksm, chakkche, Libbna, bruno.bicudo,...

Issue #3271897 by VladimirAus, eiriksm, chakkche, Libbna, bruno.bicudo, matheusmaciel, Charchil Khandelwal, sharayurajput, samit.310@gmail.com: Fix coding standards for D9
parent 2d9ddf5d
No related branches found
No related tags found
No related merge requests found
Showing
with 760 additions and 230 deletions
build:
environment:
startcontainers:
runcontainers:
create_db:
dbcreate:
codebase:
assemble_codebase:
checkout_core:
checkout.contrib:
fetch:
patch:
composer.core_install:
gather_dependencies:
update_build:
yarn_install:
start_phantomjs:
assessment:
validate_codebase:
phplint:
container_composer:
csslint:
eslint:
phpcs:
sniff-all-files: true
halt-on-fail: true
testing:
run_tests.standard:
types: 'Simpletest,PHPUnit-Unit,PHPUnit-Kernel,PHPUnit-Functional'
run_tests.js:
concurrency: 1
types: 'PHPUnit-FunctionalJavascript'
suppress-deprecations: false
nightwatchjs:
......@@ -14,7 +14,7 @@
*
* @prop {Drupal~behaviorAttach} attach
* Attaches summary behaviors on content type edit forms.
*/
*/
Drupal.behaviors.linkcheckerContentTypes = {
attach: function (context) {
var $context = $(context);
......
......@@ -32,25 +32,25 @@ function linkchecker_help($route_name, RouteMatchInterface $route_match) {
/**
* Conditionally logs a system message.
*
* @param $type
* @param string $type
* The category to which this message belongs. Can be any string, but the
* general practice is to use the name of the module calling watchdog().
* @param $message
* @param string $message
* The message to store in the log. Keep $message translatable
* by not concatenating dynamic values into it! Variables in the
* message should be added by using placeholder strings alongside
* the variables argument to declare the value of the placeholders.
* See t() for documentation on how $message and $variables interact.
* @param $variables
* @param array $variables
* Array of variables to replace in the message on display or
* NULL if message is already translated or not possible to
* translate.
* @param $severity
* The severity of the message; one of the following values as defined in
* @param $link
* @param string $severity
* The severity of the message; one of the following values as defined in.
* @param bool $link
* A link to associate with the message.
*
* @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
* @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
* - WATCHDOG_EMERGENCY: Emergency, system is unusable.
* - RfcLogLevel::ALERT: Alert, action must be taken immediately.
* - RfcLogLevel::CRITICAL: Critical conditions.
......@@ -59,10 +59,11 @@ function linkchecker_help($route_name, RouteMatchInterface $route_match) {
* - RfcLogLevel::NOTICE: (default) Normal but significant conditions.
* - WATCHDOG_INFO: Informational messages.
* - WATCHDOG_DEBUG: Debug-level messages.
*
* @see watchdog_severity_levels()
* @see watchdog()
*/
function linkchecker_watchdog_log($type, $message, $variables = [], $severity = RfcLogLevel::NOTICE, $link = NULL) {
function linkchecker_watchdog_log($type, $message, array $variables = [], $severity = RfcLogLevel::NOTICE, $link = NULL) {
// @FIXME: $link is missing, could be in $variables.
if ($severity <= \Drupal::config('linkchecker.settings')->get('logging.level')) {
$logger = \Drupal::logger($type);
......@@ -127,10 +128,15 @@ function linkchecker_form_field_config_form_alter(&$form, FormStateInterface $fo
$form['#entity_builders'][] = 'linkchecker_form_field_config_form_builder';
}
/**
* Field config form builder.
*/
function linkchecker_form_field_config_form_builder($entity_type, FieldConfigInterface $field_config, &$form, FormStateInterface $form_state) {
if ($form_state->getValue(['third_party_settings', 'linkchecker', 'scan']) === 1) {
$field_config->setThirdPartySetting('linkchecker', 'scan', TRUE);
$field_config->setThirdPartySetting('linkchecker', 'extractor', $form_state->getValue(['third_party_settings', 'linkchecker', 'extractor']));
$field_config->setThirdPartySetting('linkchecker', 'extractor',
$form_state->getValue(['third_party_settings', 'linkchecker', 'extractor'])
);
return;
}
......@@ -290,7 +296,7 @@ function linkchecker_migrate_prepare_row(Row $row, MigrateSourceInterface $sourc
->condition('name', 'linkchecker_scan_' . $entity_type . '_' . $bundle)
->execute()
->fetchField();
$linkchecker_enabled = $result !== FALSE ? unserialize($result) : FALSE;
$linkchecker_enabled = $result !== FALSE ? unserialize($result, ['allowed_classes' => FALSE]) : FALSE;
if ($linkchecker_enabled) {
$row->setSourceProperty(
'linkchecker_config',
......
......@@ -63,7 +63,7 @@ class LinkCheckerCommands extends DrushCommands {
LinkCleanUp $linkCleanUp
) {
parent::__construct();
$this->linkcheckerSetting = $configFactory->get('linkchecker.settings');;
$this->linkcheckerSetting = $configFactory->get('linkchecker.settings');
$this->logger = $logger;
$this->extractorBatch = $extractorBatch;
$this->checkerBatch = $checkerBatch;
......@@ -152,11 +152,11 @@ class LinkCheckerCommands extends DrushCommands {
}
if (empty($baseUrl)) {
throw new \Exception($this->t('You MUST configure the site base_url or provide --uri parameter.'));
throw new \Exception('You MUST configure the site base_url or provide --uri parameter.');
}
if (mb_strpos($baseUrl, 'http') !== 0) {
throw new \Exception($this->t('Base url should start with http scheme (http:// or https://)'));
throw new \Exception('Base url should start with http scheme (http:// or https://)');
}
}
......
This diff is collapsed.
......@@ -19,12 +19,21 @@ class LinkCheckerLinkAccessControlHandler extends EntityAccessControlHandler {
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
protected function checkAccess(
EntityInterface $entity,
$operation,
AccountInterface $account
) {
/** @var \Drupal\linkchecker\LinkCheckerLinkInterface $entity */
if ($account->hasPermission('administer linkchecker')
|| $account->hasPermission('edit linkchecker link settings')) {
return $this->checkParentEntityAccess($entity, $operation, $account);
if (
$account->hasPermission('administer linkchecker') ||
$account->hasPermission('edit linkchecker link settings')
) {
return $this->checkParentEntityAccess(
$entity,
$operation,
$account
);
}
// The permission is required.
......@@ -34,43 +43,66 @@ class LinkCheckerLinkAccessControlHandler extends EntityAccessControlHandler {
/**
* {@inheritdoc}
*/
protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
protected function checkFieldAccess(
$operation,
FieldDefinitionInterface $field_definition,
AccountInterface $account,
FieldItemListInterface $items = NULL
) {
// No user can change read only fields.
if ($operation == 'edit') {
switch ($field_definition->getName()) {
case 'method':
case 'status':
return AccessResult::allowedIfHasPermissions($account, [
'administer linkchecker',
'edit linkchecker link settings',
], 'OR');
return AccessResult::allowedIfHasPermissions(
$account,
[
'administer linkchecker',
'edit linkchecker link settings',
],
'OR'
);
default:
return AccessResult::forbidden();
}
}
// User not allowed to view URL field if he does not have access to parent
// User not allowed to view URL field if it does not have access to parent
// entity.
if ($operation == 'view'
&& isset($items)
&& $field_definition->getName() == 'url') {
return $this->checkParentEntityAccess($items->getEntity(), $operation, $account);
if (
$operation == 'view' &&
isset($items) &&
$field_definition->getName() == 'url'
) {
return $this->checkParentEntityAccess(
$items->getEntity(),
$operation,
$account
);
}
return parent::checkFieldAccess($operation, $field_definition, $account, $items);
return parent::checkFieldAccess(
$operation,
$field_definition,
$account,
$items
);
}
/**
* Helper function for access checking.
*/
protected function checkParentEntityAccess(LinkCheckerLinkInterface $entity, $operation, AccountInterface $account) {
protected function checkParentEntityAccess(
LinkCheckerLinkInterface $entity,
$operation,
AccountInterface $account
) {
$parentEntity = $entity->getParentEntity();
// If parent not exists - forbidden.
if (!isset($parentEntity)) {
return AccessResult::forbidden()
->cachePerPermissions();
return AccessResult::forbidden()->cachePerPermissions();
}
// If user does not have access to parent entity - forbidden.
......@@ -88,7 +120,9 @@ class LinkCheckerLinkAccessControlHandler extends EntityAccessControlHandler {
}
// If user does not have access to field where link is stored - forbidden.
$parentEntityField = $parentEntity->get($entity->getParentEntityFieldName());
$parentEntityField = $parentEntity->get(
$entity->getParentEntityFieldName()
);
if (!$parentEntityField->access($operation, $account)) {
return AccessResult::forbidden()
->addCacheableDependency($parentEntity)
......
......@@ -16,7 +16,7 @@ use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;
/**
* Class LinkCheckerService.
* Defines service to check link.
*/
class LinkCheckerService {
......
......@@ -9,8 +9,9 @@ use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Class LinkCleanUp.
* Use to remove links.
*/
class LinkCleanUp {
......
......@@ -115,7 +115,6 @@ class LinkExtractorBatch {
foreach ($ids as $id) {
$entity = $storage->load($id);
if ($entity instanceof FieldableEntityInterface) {
// Process the entity links.
$links = $this->extractor->extractFromEntity($entity);
$this->extractor->saveLinkMultiple($links);
$this->extractor->updateEntityExtractIndex($entity);
......
......@@ -199,7 +199,7 @@ class LinkExtractorService {
// Decode HTML links into plain text links.
// DOMDocument->loadHTML does not provide the RAW url from code. All html
// entities are already decoded.
// @todo: Try to find a way to get the raw value.
// @todo Try to find a way to get the raw value.
$urlDecoded = $url;
// Prefix protocol relative urls with a protocol to allow link checking.
......@@ -416,7 +416,9 @@ class LinkExtractorService {
// Is url in domain blacklist?
$urls = $this->linkcheckerSetting->get('check.disable_link_check_for_urls');
if (!empty($urls) && preg_match('/' . implode('|', array_map(function ($links) {return preg_quote($links, '/');}, preg_split('/(\r\n?|\n)/', $urls))) . '/', $url)) {
if (!empty($urls) && preg_match('/' . implode('|', array_map(function ($links) {
return preg_quote($links, '/');
}, preg_split('/(\r\n?|\n)/', $urls))) . '/', $url)) {
return TRUE;
}
......@@ -456,9 +458,9 @@ class LinkExtractorService {
$scheme = isset($uri['scheme']) ? $uri['scheme'] . '://' : '';
$user = isset($uri['user']) ? $uri['user'] . ($uri['pass'] ? ':' . $uri['pass'] : '') . '@' : '';
$port = isset($uri['port']) ? $uri['port'] : 80;
$port = $uri['port'] ?? 80;
$host = $uri['host'] . ($port != 80 ? ':' . $port : '');
$path = isset($uri['path']) ? $uri['path'] : '/';
$path = $uri['path'] ?? '/';
// Glue the URL variables.
$absoluteUrl = $scheme . $user . $host . $path;
......
......@@ -6,7 +6,7 @@ use Drupal\Component\Utility\Html;
use Drupal\linkchecker\Plugin\LinkExtractorBase;
/**
* Class HtmlLinkExtractor.
* Extracts html link.
*
* @LinkExtractor(
* id = "html_link_extractor",
......@@ -102,9 +102,8 @@ class HtmlLinkExtractor extends LinkExtractorBase {
// Finds param tags with links in the object tag.
$params = $object->getElementsByTagName('param');
foreach ($params as $param) {
// @todo
// - Try to extract links in unkown "flashvars" values
// (e.g., file=http://, data=http://).
// @todo Try to extract links in unkown "flashvars" values
// (e.g., file=http://, data=http://).
$names = ['archive', 'filename', 'href', 'movie', 'src', 'url'];
if ($param->hasAttribute('name') && in_array($param->getAttribute('name'), $names)) {
$urls[] = $param->getAttribute('value');
......
......@@ -5,7 +5,7 @@ namespace Drupal\linkchecker\Plugin\LinkExtractor;
use Drupal\linkchecker\Plugin\LinkExtractorBase;
/**
* Class LinkLinkExtractor.
* Extracts link from field.
*
* @LinkExtractor(
* id = "link_link_extractor",
......
......@@ -27,7 +27,6 @@ use Symfony\Component\HttpFoundation\RequestStack;
* )
*/
class Repair301 extends LinkStatusHandlerBase {
/**
* Current request.
*
......@@ -38,15 +37,37 @@ class Repair301 extends LinkStatusHandlerBase {
/**
* Repair301 constructor.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, QueueFactory $queueFactory, EntityTypeManagerInterface $entityTypeManager, AccountSwitcherInterface $accountSwitcher, ImmutableConfig $linkcheckerSetting, RequestStack $requestStack) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $queueFactory, $entityTypeManager, $accountSwitcher, $linkcheckerSetting);
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
QueueFactory $queueFactory,
EntityTypeManagerInterface $entityTypeManager,
AccountSwitcherInterface $accountSwitcher,
ImmutableConfig $linkcheckerSetting,
RequestStack $requestStack
) {
parent::__construct(
$configuration,
$plugin_id,
$plugin_definition,
$queueFactory,
$entityTypeManager,
$accountSwitcher,
$linkcheckerSetting
);
$this->request = $requestStack->getCurrentRequest();
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
public static function create(
ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition
) {
return new static(
$configuration,
$plugin_id,
......@@ -62,7 +83,10 @@ class Repair301 extends LinkStatusHandlerBase {
/**
* {@inheritdoc}
*/
protected function getItems(LinkCheckerLinkInterface $link, ResponseInterface $response) {
protected function getItems(
LinkCheckerLinkInterface $link,
ResponseInterface $response
) {
// A HTTP status code of 301 tells us an existing link have changed to
// a new link. The remote site owner was so kind to provide us the new
// link and if we trust this change we are able to replace the old link
......@@ -70,9 +94,7 @@ class Repair301 extends LinkStatusHandlerBase {
$autoRepair301 = $this->linkcheckerSetting->get('error.action_status_code_301');
$redirectUrl = $response->getHeaderLine('Location');
if ($autoRepair301
&& $autoRepair301 <= $link->getFailCount()
&& UrlHelper::isValid($redirectUrl, TRUE)) {
if ($autoRepair301 && $autoRepair301 <= $link->getFailCount() && UrlHelper::isValid($redirectUrl, TRUE)) {
return parent::getItems($link, $response);
}
else {
......@@ -83,19 +105,33 @@ class Repair301 extends LinkStatusHandlerBase {
/**
* {@inheritdoc}
*/
protected function doHandle(LinkCheckerLinkInterface $link, ResponseInterface $response, FieldableEntityInterface $entity) {
$autoRepair301 = $this->linkcheckerSetting->get('error.action_status_code_301');
protected function doHandle(
LinkCheckerLinkInterface $link,
ResponseInterface $response,
FieldableEntityInterface $entity
) {
$autoRepair301 = $this->linkcheckerSetting->get(
'error.action_status_code_301'
);
$redirectUrl = $response->getHeaderLine('Location');
if ($autoRepair301
&& $autoRepair301 <= $link->getFailCount()
&& UrlHelper::isValid($redirectUrl, TRUE)
&& $link->isExists()) {
$values = $entity->get($link->getParentEntityFieldName())->getValue();
if (
$autoRepair301 &&
$autoRepair301 <= $link->getFailCount() &&
UrlHelper::isValid($redirectUrl, TRUE) &&
$link->isExists()
) {
$values = $entity
->get($link->getParentEntityFieldName())
->getValue();
foreach ($values as $key => $value) {
if (isset($value['value'])) {
$values[$key]['value'] = $this->linkReplace($value['value'], $link->getUrl(), $redirectUrl);
$values[$key]['value'] = $this->linkReplace(
$value['value'],
$link->getUrl(),
$redirectUrl
);
}
}
......@@ -119,7 +155,11 @@ class Repair301 extends LinkStatusHandlerBase {
*/
protected function linkReplace($value, $oldLinkAbsolute, $newLinkAbsolute) {
// Don't do any string replacement if one of the values is empty.
if (empty($value) || empty($oldLinkAbsolute) || empty($newLinkAbsolute)) {
if (
empty($value) ||
empty($oldLinkAbsolute) ||
empty($newLinkAbsolute)
) {
return $value;
}
......@@ -127,8 +167,11 @@ class Repair301 extends LinkStatusHandlerBase {
$baseUrl = $this->request->getSchemeAndHttpHost();
}
else {
$httpProtocol = $this->linkcheckerSetting->get('default_url_scheme');
$baseUrl = $httpProtocol . $this->linkcheckerSetting->get('base_path');
$httpProtocol = $this->linkcheckerSetting->get(
'default_url_scheme'
);
$baseUrl =
$httpProtocol . $this->linkcheckerSetting->get('base_path');
}
// Remove protocols and hostname from local URLs.
......@@ -143,26 +186,28 @@ class Repair301 extends LinkStatusHandlerBase {
$newHtmlLink = UrlHelper::filterBadProtocol($newLink);
// Replace links in link fields and text and Links weblink fields.
if (in_array($value, [
$oldHtmlLinkAbsolute,
$oldHtmlLink,
$oldLinkAbsolute,
$oldLink,
])) {
if (
in_array($value, [
$oldHtmlLinkAbsolute,
$oldHtmlLink,
$oldLinkAbsolute,
$oldLink,
])
) {
// Keep old and new links in the same encoding and format and short or
// fully qualified.
$value = str_replace($oldHtmlLinkAbsolute, $newHtmlLinkAbsolute, $value);
$value = str_replace(
$oldHtmlLinkAbsolute,
$newHtmlLinkAbsolute,
$value
);
$value = str_replace($oldHtmlLink, $newHtmlLink, $value);
$value = str_replace($oldLinkAbsolute, $newLinkAbsolute, $value);
$value = str_replace($oldLink, $newLink, $value);
}
else {
// Create an array of links with HTML decoded and encoded URLs.
$oldLinks = [
$oldHtmlLinkAbsolute,
$oldHtmlLink,
$oldLink,
];
$oldLinks = [$oldHtmlLinkAbsolute, $oldHtmlLink, $oldLink];
// Remove duplicate URLs from array if URLs do not have URL parameters.
// If more than one URL parameter exists - one URL in the array will have
......@@ -227,10 +272,14 @@ class Repair301 extends LinkStatusHandlerBase {
if (in_array($embed->getAttribute('src'), $oldLinks)) {
$embed->setAttribute('src', $newHtmlLink);
}
if (in_array($embed->getAttribute('pluginurl'), $oldLinks)) {
if (
in_array($embed->getAttribute('pluginurl'), $oldLinks)
) {
$embed->setAttribute('pluginurl', $newHtmlLink);
}
if (in_array($embed->getAttribute('pluginspage'), $oldLinks)) {
if (
in_array($embed->getAttribute('pluginspage'), $oldLinks)
) {
$embed->setAttribute('pluginspage', $newHtmlLink);
}
}
......@@ -266,26 +315,50 @@ class Repair301 extends LinkStatusHandlerBase {
if (in_array($object->getAttribute('data'), $oldLinks)) {
$object->setAttribute('data', $newHtmlLink);
}
if (in_array($object->getAttribute('codebase'), $oldLinks)) {
if (
in_array($object->getAttribute('codebase'), $oldLinks)
) {
$object->setAttribute('codebase', $newHtmlLink);
}
// Finds param tags with links in the object tag.
$params = $object->getElementsByTagName('param');
foreach ($params as $param) {
// @todo
// - Try to replace links in unknown "flashvars" values
// @todo Try to replace links in unknown "flashvars" values
// (e.g., file=http://, data=http://).
$names = ['archive', 'filename', 'href', 'movie', 'src', 'url'];
if ($param->hasAttribute('name') && in_array($param->getAttribute('name'), $names)) {
if (in_array($param->getAttribute('value'), $oldLinks)) {
$names = [
'archive',
'filename',
'href',
'movie',
'src',
'url',
];
if (
$param->hasAttribute('name') &&
in_array($param->getAttribute('name'), $names)
) {
if (
in_array(
$param->getAttribute('value'),
$oldLinks
)
) {
$param->setAttribute('value', $newHtmlLink);
}
}
$srcs = ['movie'];
if ($param->hasAttribute('src') && in_array($param->getAttribute('src'), $srcs)) {
if (in_array($param->getAttribute('value'), $oldLinks)) {
if (
$param->hasAttribute('src') &&
in_array($param->getAttribute('src'), $srcs)
) {
if (
in_array(
$param->getAttribute('value'),
$oldLinks
)
) {
$param->setAttribute('value', $newHtmlLink);
}
}
......
......@@ -20,7 +20,6 @@ use Drupal\Tests\BrowserTestBase;
* @group linkchecker
*/
class LinkCheckerInterfaceTest extends BrowserTestBase {
use StringTranslationTrait;
/**
......@@ -61,7 +60,11 @@ class LinkCheckerInterfaceTest extends BrowserTestBase {
$node_type->save();
$node_body_field = node_add_body_field($node_type);
$node_body_field->setThirdPartySetting('linkchecker', 'scan', TRUE);
$node_body_field->setThirdPartySetting('linkchecker', 'extractor', 'html_link_extractor');
$node_body_field->setThirdPartySetting(
'linkchecker',
'extractor',
'html_link_extractor'
);
$node_body_field->save();
$block_type = BlockContentType::create([
......@@ -71,45 +74,73 @@ class LinkCheckerInterfaceTest extends BrowserTestBase {
$block_type->save();
$block_body_field = block_content_add_body_field($block_type->id());
$block_body_field->setThirdPartySetting('linkchecker', 'scan', TRUE);
$block_body_field->setThirdPartySetting('linkchecker', 'extractor', 'html_link_extractor');
$block_body_field->setThirdPartySetting(
'linkchecker',
'extractor',
'html_link_extractor'
);
$block_body_field->save();
// Configure basic settings.
$this->config('linkchecker.settings')->set('default_url_scheme', 'http://')->save();
$this->config('linkchecker.settings')->set('base_path', 'example.org/')->save();
$this->config('linkchecker.settings')->set('check.disable_link_check_for_urls', '')->save();
$this->config('linkchecker.settings')->set('check_links_types', LinkCheckerLinkInterface::TYPE_ALL)->save();
$this->config('linkchecker.settings')
->set('default_url_scheme', 'http://')
->save();
$this->config('linkchecker.settings')
->set('base_path', 'example.org/')
->save();
$this->config('linkchecker.settings')
->set('check.disable_link_check_for_urls', '')
->save();
$this->config('linkchecker.settings')
->set('check_links_types', LinkCheckerLinkInterface::TYPE_ALL)
->save();
// Core enables the URL filter for "Full HTML" by default.
// -> Blacklist / Disable URL filter for testing.
$this->config('linkchecker.settings')->set('extract.filter_blacklist', ['filter_url' => 'filter_url'])->save();
$this->config('linkchecker.settings')
->set('extract.filter_blacklist', ['filter_url' => 'filter_url'])
->save();
// Extract from all link checker supported HTML tags.
$this->config('linkchecker.settings')->set('extract.from_a', 1)->save();
$this->config('linkchecker.settings')->set('extract.from_audio', 1)->save();
$this->config('linkchecker.settings')->set('extract.from_embed', 1)->save();
$this->config('linkchecker.settings')->set('extract.from_iframe', 1)->save();
$this->config('linkchecker.settings')->set('extract.from_img', 1)->save();
$this->config('linkchecker.settings')->set('extract.from_object', 1)->save();
$this->config('linkchecker.settings')->set('extract.from_video', 1)->save();
$this->config('linkchecker.settings')
->set('extract.from_a', 1)
->save();
$this->config('linkchecker.settings')
->set('extract.from_audio', 1)
->save();
$this->config('linkchecker.settings')
->set('extract.from_embed', 1)
->save();
$this->config('linkchecker.settings')
->set('extract.from_iframe', 1)
->save();
$this->config('linkchecker.settings')
->set('extract.from_img', 1)
->save();
$this->config('linkchecker.settings')
->set('extract.from_object', 1)
->save();
$this->config('linkchecker.settings')
->set('extract.from_video', 1)
->save();
$permissions = [
// Block permissions.
// Block permissions.
'administer blocks',
// Comment permissions.
// Comment permissions.
'administer comments',
'access comments',
'post comments',
'skip comment approval',
'edit own comments',
// Node permissions.
// Node permissions.
'create page content',
'edit own page content',
// Path aliase permissions.
// Path aliase permissions.
'administer url aliases',
'create url aliases',
// Content filter permissions.
// Content filter permissions.
$full_html_format->getPermissionName(),
];
......@@ -123,7 +154,10 @@ class LinkCheckerInterfaceTest extends BrowserTestBase {
*/
public function testLinkCheckerCreateNodeWithBrokenLinks() {
$url1 = 'http://example.com/node/broken/link';
$body = 'Lorem ipsum dolor sit amet <a href="' . $url1 . '">broken link</a> sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat';
$body =
'Lorem ipsum dolor sit amet <a href="' .
$url1 .
'">broken link</a> sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat';
// Save folder names in variables for reuse.
$random = new Random();
......@@ -134,20 +168,32 @@ class LinkCheckerInterfaceTest extends BrowserTestBase {
$edit = [];
$edit['title[0][value]'] = $random->name(32);
$edit['body[0][value]'] = $body;
//$edit["body[0][format]"] = 'full_html';
// $edit["body[0][format]"] = 'full_html';
$edit['path[0][alias]'] = '/' . $folder1 . '/' . $folder2;
// Extract only full qualified URLs.
$this->config('linkchecker.settings')->set('check_links_types', LinkCheckerLinkInterface::TYPE_EXTERNAL)->save();
$this->config('linkchecker.settings')
->set('check_links_types', LinkCheckerLinkInterface::TYPE_EXTERNAL)
->save();
// Verify path input field appears on add "Basic page" form.
$this->drupalGet('node/add/page');
// Verify path input is present.
$this->assertFieldByName('path[0][alias]', '', 'Path input field present on add Basic page form.');
$this->assertFieldByName(
'path[0][alias]',
'',
'Path input field present on add Basic page form.'
);
// Save node.
$this->drupalPostForm('node/add/page', $edit, $this->t('Save'));
$this->assertText($this->t('@type @title has been created.', ['@type' => 'Basic page', '@title' => $edit["title[0][value]"]]), 'Node was created.');
$this->assertText(
$this->t('@type @title has been created.', [
'@type' => 'Basic page',
'@title' => $edit['title[0][value]'],
]),
'Node was created.'
);
$node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
$this->assertNotEmpty($node);
......@@ -156,10 +202,16 @@ class LinkCheckerInterfaceTest extends BrowserTestBase {
$link = $this->getLinkCheckerLinkByUrl($url1);
if ($link) {
$this->assertIdentical($link->get('url')->value, $url1, new FormattableMarkup('URL %url found.', ['%url' => $url1]));
$this->assertIdentical(
$link->get('url')->value,
$url1,
new FormattableMarkup('URL %url found.', ['%url' => $url1])
);
}
else {
$this->fail(new FormattableMarkup('URL %url not found.', ['%url' => $url1]));
$this->fail(
new FormattableMarkup('URL %url not found.', ['%url' => $url1])
);
}
}
......@@ -168,10 +220,15 @@ class LinkCheckerInterfaceTest extends BrowserTestBase {
*/
public function testLinkCheckerCreateBlockWithBrokenLinks() {
// Confirm that the add block link appears on block overview pages.
$this->drupalGet(Url::fromRoute('entity.block_content.collection')->toString());
$this->drupalGet(
Url::fromRoute('entity.block_content.collection')->toString()
);
$url1 = 'http://example.com/block/broken/link';
$body = 'Lorem ipsum dolor sit amet <a href="' . $url1 . '">broken link</a> sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat';
$body =
'Lorem ipsum dolor sit amet <a href="' .
$url1 .
'">broken link</a> sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat';
// Add a new custom block by filling out the input form on the
// admin/structure/block/add page.
......@@ -181,13 +238,26 @@ class LinkCheckerInterfaceTest extends BrowserTestBase {
'info[0][value]' => $random->name(8),
'body[0][value]' => $body,
];
$this->drupalPostForm(Url::fromRoute('block_content.add_page')->toString(), $custom_block, 'Save');
$this->drupalPostForm(
Url::fromRoute('block_content.add_page')->toString(),
$custom_block,
'Save'
);
// Confirm that the custom block has been created, and then query the
// created bid.
$this->assertText($this->t('@type @title has been created.', ['@type' => 'Basic block', '@title' => $custom_block['info[0][value]']]), 'Custom block successfully created.');
$this->assertText(
$this->t('@type @title has been created.', [
'@type' => 'Basic block',
'@title' => $custom_block['info[0][value]'],
]),
'Custom block successfully created.'
);
// Check that the block exists in the database.
$blocks = \Drupal::entityQuery('block_content')->accessCheck()->condition('info', $custom_block['info[0][value]'])->execute();
$blocks = \Drupal::entityQuery('block_content')
->accessCheck()
->condition('info', $custom_block['info[0][value]'])
->execute();
$block = BlockContent::load(reset($blocks));
$this->assertNotEmpty($block);
......@@ -195,12 +265,18 @@ class LinkCheckerInterfaceTest extends BrowserTestBase {
$link = $this->getLinkCheckerLinkByUrl($url1);
if ($link) {
$this->assertIdentical($link->get('url')->value, $url1, new FormattableMarkup('URL %url found.', ['%url' => $url1]));
$this->assertIdentical(
$link->get('url')->value,
$url1,
new FormattableMarkup('URL %url found.', ['%url' => $url1])
);
}
else {
$this->fail(new FormattableMarkup('URL %url not found.', ['%url' => $url1]));
$this->fail(
new FormattableMarkup('URL %url not found.', ['%url' => $url1])
);
}
}
}
/**
* Get a link checker link entity by the given URl.
......
This diff is collapsed.
......@@ -2,11 +2,8 @@
namespace Drupal\Tests\linkchecker\Kernel;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\KernelTests\KernelTestBase;
use Drupal\linkchecker\Entity\LinkCheckerLink;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\node\Traits\NodeCreationTrait;
......@@ -85,7 +82,7 @@ class LinkcheckerCleanUpTest extends KernelTestBase {
'body' => [
[
'value' => '
<a href="http://httpstat.us/304">The nightmare continues</a>'
<a href="http://httpstat.us/304">The nightmare continues</a>',
],
],
]);
......
......@@ -163,7 +163,7 @@ class LinkcheckerLinkExtractorServiceTest extends KernelTestBase {
'@actual' => $countExtracted,
]));
foreach ($this->getRelativeUrls() as $relativeUrl => $url) {
foreach ($this->getRelativeUrls() as $url) {
$this->assertTrue(in_array($url, $extracted), new FormattableMarkup('URL @url was not extracted!', ['@url' => $url]));
}
}
......
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