Version 1
[yaffs-website] / web / core / modules / filter / src / Plugin / Filter / FilterAlign.php
1 <?php
2
3 namespace Drupal\filter\Plugin\Filter;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\filter\FilterProcessResult;
7 use Drupal\filter\Plugin\FilterBase;
8
9 /**
10  * Provides a filter to align elements.
11  *
12  * @Filter(
13  *   id = "filter_align",
14  *   title = @Translation("Align images"),
15  *   description = @Translation("Uses a <code>data-align</code> attribute on <code>&lt;img&gt;</code> tags to align images."),
16  *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
17  * )
18  */
19 class FilterAlign extends FilterBase {
20
21   /**
22    * {@inheritdoc}
23    */
24   public function process($text, $langcode) {
25     $result = new FilterProcessResult($text);
26
27     if (stristr($text, 'data-align') !== FALSE) {
28       $dom = Html::load($text);
29       $xpath = new \DOMXPath($dom);
30       foreach ($xpath->query('//*[@data-align]') as $node) {
31         // Read the data-align attribute's value, then delete it.
32         $align = $node->getAttribute('data-align');
33         $node->removeAttribute('data-align');
34
35         // If one of the allowed alignments, add the corresponding class.
36         if (in_array($align, ['left', 'center', 'right'])) {
37           $classes = $node->getAttribute('class');
38           $classes = (strlen($classes) > 0) ? explode(' ', $classes) : [];
39           $classes[] = 'align-' . $align;
40           $node->setAttribute('class', implode(' ', $classes));
41         }
42       }
43       $result->setProcessedText(Html::serialize($dom));
44     }
45
46     return $result;
47   }
48
49   /**
50    * {@inheritdoc}
51    */
52   public function tips($long = FALSE) {
53     if ($long) {
54       return $this->t('
55         <p>You can align images, videos, blockquotes and so on to the left, right or center. Examples:</p>
56         <ul>
57           <li>Align an image to the left: <code>&lt;img src="" data-align="left" /&gt;</code></li>
58           <li>Align an image to the center: <code>&lt;img src="" data-align="center" /&gt;</code></li>
59           <li>Align an image to the right: <code>&lt;img src="" data-align="right" /&gt;</code></li>
60           <li>… and you can apply this to other elements as well: <code>&lt;video src="" data-align="center" /&gt;</code></li>
61         </ul>');
62     }
63     else {
64       return $this->t('You can align images (<code>data-align="center"</code>), but also videos, blockquotes, and so on.');
65     }
66   }
67
68 }