02-PicoExcerpt.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * Creates a excerpt for the contents of each page (as of Pico v0.9 and older)
  4. *
  5. * This plugin exists for backward compatibility and is disabled by default.
  6. * It gets automatically enabled when {@link PicoDeprecated} is enabled. You
  7. * can avoid this by calling {@link PicoExcerpt::setEnabled()}.
  8. *
  9. * This plugin doesn't do its job very well and depends on
  10. * {@link PicoParsePagesContent}, what heavily impacts Pico's performance. You
  11. * should either use the Description meta header field or write something own.
  12. * Best solution seems to be a filter for twig, see e.g.
  13. * {@link https://gist.github.com/james2doyle/6629712}.
  14. *
  15. * @author Daniel Rudolf
  16. * @link http://picocms.org
  17. * @license http://opensource.org/licenses/MIT The MIT License
  18. * @version 1.0
  19. */
  20. class PicoExcerpt extends AbstractPicoPlugin
  21. {
  22. /**
  23. * This plugin is disabled by default
  24. *
  25. * @see AbstractPicoPlugin::$enabled
  26. */
  27. protected $enabled = false;
  28. /**
  29. * This plugin depends on PicoParsePagesContent
  30. *
  31. * @see PicoParsePagesContent
  32. * @see AbstractPicoPlugin::$dependsOn
  33. */
  34. protected $dependsOn = array('PicoParsePagesContent');
  35. /**
  36. * Adds the default excerpt length of 50 words to the config
  37. *
  38. * @see DummyPlugin::onConfigLoaded()
  39. */
  40. public function onConfigLoaded(array &$config)
  41. {
  42. if (!isset($config['excerpt_length'])) {
  43. $config['excerpt_length'] = 50;
  44. }
  45. }
  46. /**
  47. * Creates a excerpt for the contents of each page
  48. *
  49. * @see PicoExcerpt::createExcerpt()
  50. * @see DummyPlugin::onSinglePageLoaded()
  51. */
  52. public function onSinglePageLoaded(array &$pageData)
  53. {
  54. if (!isset($pageData['excerpt'])) {
  55. $pageData['excerpt'] = $this->createExcerpt(
  56. strip_tags($pageData['content']),
  57. $this->getConfig('excerpt_length')
  58. );
  59. }
  60. }
  61. /**
  62. * Helper function to create a excerpt of a string
  63. *
  64. * @param string $string the string to create a excerpt from
  65. * @param int $wordLimit the maximum number of words the excerpt should be long
  66. * @return string excerpt of $string
  67. */
  68. protected function createExcerpt($string, $wordLimit)
  69. {
  70. $words = explode(' ', $string);
  71. if (count($words) > $wordLimit) {
  72. return trim(implode(' ', array_slice($words, 0, $wordLimit))) . '&hellip;';
  73. }
  74. return $string;
  75. }
  76. }