Copie de Tumblr sur Shaarli
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

74 righe
2.2 KiB

  1. <?php
  2. namespace League\HTMLToMarkdown\Converter;
  3. use League\HTMLToMarkdown\ElementInterface;
  4. class PreformattedConverter implements ConverterInterface
  5. {
  6. /**
  7. * @param ElementInterface $element
  8. *
  9. * @return string
  10. */
  11. public function convert(ElementInterface $element)
  12. {
  13. // Store the content of the code block in an array, one entry for each line
  14. $markdown = '';
  15. $code_content = html_entity_decode($element->getChildrenAsString());
  16. $code_content = str_replace(array('<code>', '</code>'), '', $code_content);
  17. $code_content = str_replace(array('<pre>', '</pre>'), '', $code_content);
  18. $lines = preg_split('/\r\n|\r|\n/', $code_content);
  19. $total = count($lines);
  20. // If there's more than one line of code, prepend each line with four spaces and no backticks.
  21. if ($total > 1 || $element->getTagName() === 'pre') {
  22. // Remove the first and last line if they're empty
  23. $first_line = trim($lines[0]);
  24. $last_line = trim($lines[$total - 1]);
  25. $first_line = trim($first_line, '&#xD;'); //trim XML style carriage returns too
  26. $last_line = trim($last_line, '&#xD;');
  27. if (empty($first_line)) {
  28. array_shift($lines);
  29. }
  30. if (empty($last_line)) {
  31. array_pop($lines);
  32. }
  33. $count = 1;
  34. foreach ($lines as $line) {
  35. $line = str_replace('&#xD;', '', $line);
  36. $markdown .= ' ' . $line;
  37. // Add newlines, except final line of the code
  38. if ($count !== $total) {
  39. $markdown .= "\n";
  40. }
  41. $count++;
  42. }
  43. $markdown .= "\n";
  44. } else {
  45. // There's only one line of code. It's a code span, not a block. Just wrap it with backticks.
  46. $markdown .= '`' . $lines[0] . '`';
  47. }
  48. if ($element->getTagName() === 'pre') {
  49. $markdown = "\n" . $markdown . "\n";
  50. }
  51. return $markdown;
  52. }
  53. /**
  54. * @return string[]
  55. */
  56. public function getSupportedTags()
  57. {
  58. return array('pre', 'code');
  59. }
  60. }