AudioLinksFilter.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Drupal\edlp_corpus\Plugin\Filter;
  3. use Drupal\Component\Utility\Html;
  4. // use Drupal\Component\Utility\Unicode;
  5. // use Drupal\Component\Utility\Xss;
  6. use Drupal\filter\FilterProcessResult;
  7. use Drupal\filter\Plugin\FilterBase;
  8. use Drupal\Core\Url;
  9. // use Drupal\Core\Template\Attribute;
  10. /**
  11. * Provides a filter to convert audio links.
  12. *
  13. * @Filter(
  14. * id = "audio_links",
  15. * title = @Translation("Audio Links"),
  16. * description = @Translation("Convert enregistrement links to audio links"),
  17. * type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
  18. * )
  19. */
  20. class AudioLinksFilter extends FilterBase {
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function process($text, $langcode) {
  25. $result = new FilterProcessResult($text);
  26. $dom = Html::load($text);
  27. $xpath = new \DOMXPath($dom);
  28. foreach ($xpath->query('//a[contains(@href, "node/")]') as $link) {
  29. $href = $link->getAttribute('href');
  30. preg_match('/^\/?node\/(\d+)$/', $href, $matches);
  31. // dpm($matches[1]);
  32. $node = entity_load('node', $matches[1]);
  33. if(!$node) continue;
  34. if($node->getType() != "enregistrement") continue;
  35. // dpm($node->getTitle());
  36. $options = ['absolute' => TRUE];
  37. $url = Url::fromRoute('entity.node.canonical', ['node' => $node->id()], $options);
  38. $system_path = $url->getInternalPath();
  39. // get the audio file url
  40. $field_son_values = $node->get('field_son')->getValue();
  41. $son_fid = count($field_son_values) ? $field_son_values[0]['target_id'] : "";
  42. $son_file = \Drupal\file\Entity\File::load($son_fid);
  43. $son_url = null;
  44. if($son_file){
  45. $son_uri = $son_file->getFileUri();
  46. $son_url = file_create_url($son_uri);
  47. }
  48. // set the link classes
  49. $class = $link->getAttribute('class');
  50. $class .= $class == '' ? '':' ';
  51. $class .= 'audio-link ajax-link';
  52. // finnally add all the attributes
  53. $link->SetAttribute('data-drupal-link-system-path', $system_path);
  54. $link->SetAttribute('audio_url', $son_url);
  55. $link->SetAttribute('nid', $node->id());
  56. $link->SetAttribute('class', $class);
  57. }
  58. $result->setProcessedText(Html::serialize($dom));
  59. return $result;
  60. }
  61. }