Repository URL to install this package:
|
Version:
2.0.1 ▾
|
<?php
namespace Drupal\dds_devel\Form;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\entity_reference_revisions\Plugin\Field\FieldType\EntityReferenceRevisionsItem;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;
use InvalidArgumentException;
class ParagraphUsageForm extends FormBase {
protected $paragraphStorage;
/**
* Returns a unique string identifying the form.
*
* The returned ID should be a unique string that can be a valid PHP function
* name, since it's used in hook implementation names such as
* hook_form_FORM_ID_alter().
*
* @return string
* The unique string identifying the form.
*/
public function getFormId() {
return 'dds_devel_paragraph_usage';
}
/**
* Form constructor.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return array
* The form structure.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = [];
$type = $form_state->getValue('type');
$paragraph_types = \Drupal::service('entity_type.bundle.info')->getBundleInfo('paragraph');
$options = [];
foreach ($paragraph_types as $paragraph_type_id => $paragraph_type) {
$options[$paragraph_type_id] = $paragraph_type['label'];
}
$form['type'] = [
'#type' => 'select',
'#options' => $options,
'#default_value' => $type
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Find usage')
];
if (!empty($type)) {
$this->paragraphStorage = \Drupal::entityTypeManager()->getStorage('paragraph');
$ids = \Drupal::entityQuery('paragraph')
->condition('type', $type)
->execute();
try {
$entities = \Drupal::entityTypeManager()->getStorage('paragraph')
->loadMultiple($ids);
} catch (InvalidPluginDefinitionException $e) {
// TODO: Error logging
} catch (PluginNotFoundException $e) {
// TODO: Error logging
}
$nodes = [];
/** @var Paragraph $paragraph */
foreach ($entities as $id => $paragraph) {
$node = $this->getNodeParent($paragraph);
if (!is_null($node) && empty($nodes[$node->id()])) {
$nodes[$node->id()] = $node;
}
}
$form['space'] = [ '#markup' => '<br/><br/>'];
$form['list'] = array(
'#type' => 'table',
'#header' => array(
$this->t('Title'),
$this->t('Link'),
$this->t('Count'),
$this->t('Published')
),
'#empty' => $this->t('No usage was found.'),
// TableSelect: Injects a first column containing the selection widget into
// each table row.
// Note that you also need to set #tableselect on each form submit button
// that relies on non-empty selection values (see below).
'#tableselect' => FALSE,
);
/** @var Node $node */
foreach ($nodes as $nid => $node) {
$count = $this->getNodeCount($node, $type);
if ($count > 0) {
$form['list'][$node->id()]['title'] = [
'#plain_text' => $node->label(),
];
$alias = \Drupal::service('path_alias.manager')
->getAliasByPath('/node/' . $node->id());
$url = $this->TextToUrl($alias);
if ($url !== FALSE) {
$form['list'][$node->id()]['link'] = [
'#type' => 'link',
'#title' => $alias,
'#url' => $url,
];
}
$form['list'][$node->id()]['count'] = [
'#plain_text' => $count
];
$form['list'][$node->id()]['published'] = [
'#plain_text' => $node->isPublished() ? $this->t('Published') : $this->t('Unpublished')
];
}
}
} else {
$form['list'] = [
'#type' => 'hidden'
];
}
return $form;
}
/**
* Form submission handler.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state->setRebuild();
}
/**
* @param \Drupal\paragraphs\Entity\Paragraph $paragraph
*
* @return \Drupal\Core\Entity\EntityInterface|null
*/
protected function getNodeParent(Paragraph $paragraph) {
$parent = $paragraph->getParentEntity();
while (!is_null($parent) && $parent->getEntityTypeId() !== 'node') {
if (method_exists($parent, 'getParentEntity')) {
$parent = $parent->getParentEntity();
} else {
\Drupal::messenger()->addWarning($this->t('Paragraph usage found on entity of type %entity_type.', ['%entity_type' => $parent->getEntityType()->getLabel()]), FALSE);
$parent = null;
}
}
return $parent;
}
/**
* @param \Drupal\node\Entity\Node $node
* @param string $type
*
* @return int
*/
protected function getNodeCount(Node $node, $type) {
$count = 0;
/** @var FieldItemList $field */
foreach ($node->getFields() as $field) {
if ($field->getFieldDefinition()->getType() == 'entity_reference_revisions') {
/** @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList $paragraphs */
$paragraphs = $field;
if ($paragraphs->getSetting('target_type') == 'paragraph') {
/** @var EntityReferenceRevisionsItem $item */
foreach ($paragraphs as $item) {
/** @var Paragraph $paragraph */
$paragraph = null;
if (!empty($item->getValue()['entity'])) {
$paragraph = $item->getValue()['entity'];
} elseif (!empty($item->getValue()['target_revision_id'])) {
$paragraph = $this->paragraphStorage->loadRevision($item->getValue()['target_revision_id']);
}
if (!is_null($paragraph)) {
if ($paragraph->bundle() == $type) {
$count++;
}
else {
$count += $this->getParagraphCount($paragraph, $type);
}
}
}
}
}
}
return $count;
}
/**
* @param \Drupal\paragraphs\Entity\Paragraph $paragraph
* @param string $type
*
* @return int
*/
protected function getParagraphCount(Paragraph $paragraph, $type) {
$count = 0;
/** @var FieldItemList $field */
foreach ($paragraph->getFields() as $field) {
if ($field->getFieldDefinition()->getType() == 'entity_reference_revisions') {
/** @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList $paragraphs */
$paragraphs = $field;
if ($paragraphs->getSetting('target_type') == 'paragraph') {
/** @var EntityReferenceRevisionsItem $item */
foreach ($paragraphs as $item) {
/** @var Paragraph $new_paragraph */
$new_paragraph = null;
if (!empty($item->getValue()['entity'])) {
$new_paragraph = $item->getValue()['entity'];
} elseif (!empty($item->getValue()['target_revision_id'])) {
$new_paragraph = $this->paragraphStorage->loadRevision($item->getValue()['target_revision_id']);
}
if (!is_null($new_paragraph)) {
if ($new_paragraph->bundle() == $type) {
$count++;
} else {
$count += $this->getParagraphCount($new_paragraph, $type);
}
}
}
}
}
}
return $count;
}
/**
* @param string $text
* @return \Drupal\Core\Url|bool
*/
function TextToUrl($text) {
if (empty($text)) {
$text = '#';
}
if (strpos(strtolower($text), 'http:') === 0 || strpos(strtolower($text), 'https:') === 0) {
try {
$result = Url::fromUri($text);
} catch(InvalidArgumentException $e) {
$result = FALSE;
}
}
else {
try {
$result = Url::fromUserInput($text);
} catch (InvalidArgumentException $e) {
$result = FALSE;
}
}
return $result;
}
}