|
| 1 | +<?php |
| 2 | +namespace Thunder\Shortcode; |
| 3 | + |
| 4 | +/** |
| 5 | + * @author Tomasz Kowalczyk <tomasz@kowalczyk.cc> |
| 6 | + */ |
| 7 | +final class Processor implements ProcessorInterface |
| 8 | + { |
| 9 | + private $handlers = array(); |
| 10 | + private $extractor; |
| 11 | + private $parser; |
| 12 | + private $defaultHandler; |
| 13 | + |
| 14 | + public function __construct(ExtractorInterface $extractor, ParserInterface $parser) |
| 15 | + { |
| 16 | + $this->extractor = $extractor; |
| 17 | + $this->parser = $parser; |
| 18 | + } |
| 19 | + |
| 20 | + public function addHandler($name, callable $handler) |
| 21 | + { |
| 22 | + if($this->hasHandler($name)) |
| 23 | + { |
| 24 | + $msg = 'Cannot register duplicate shortcode handler for %s!'; |
| 25 | + throw new \RuntimeException(sprintf($msg, $name)); |
| 26 | + } |
| 27 | + |
| 28 | + $this->handlers[$name] = $handler; |
| 29 | + |
| 30 | + return $this; |
| 31 | + } |
| 32 | + |
| 33 | + public function setDefaultHandler(callable $handler) |
| 34 | + { |
| 35 | + $this->defaultHandler = $handler; |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Expects matches sorted by position returned from Extractor. Matches are |
| 40 | + * processed from the last to the first to avoid replace position errors. |
| 41 | + * Edge cases are described in README. |
| 42 | + * |
| 43 | + * @param string $text |
| 44 | + * |
| 45 | + * @return string |
| 46 | + */ |
| 47 | + public function process($text) |
| 48 | + { |
| 49 | + /** @var $matches Match[] */ |
| 50 | + $matches = array_reverse($this->extractor->extract($text)); |
| 51 | + |
| 52 | + foreach($matches as $match) |
| 53 | + { |
| 54 | + $shortcode = $this->parser->parse($match->getString()); |
| 55 | + $shortcode = new Shortcode( |
| 56 | + $shortcode->getName(), |
| 57 | + $shortcode->getParameters(), |
| 58 | + $shortcode->hasContent() ? $this->process($shortcode->getContent()) : null |
| 59 | + ); |
| 60 | + $handler = $this->getHandler($shortcode->getName()); |
| 61 | + if($handler) |
| 62 | + { |
| 63 | + $replace = call_user_func_array($handler, array($shortcode)); |
| 64 | + $text = substr_replace($text, $replace, $match->getPosition(), $match->getLength()); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return $text; |
| 69 | + } |
| 70 | + |
| 71 | + private function getHandler($name) |
| 72 | + { |
| 73 | + return $this->hasHandler($name) |
| 74 | + ? $this->handlers[$name] |
| 75 | + : ($this->defaultHandler ? $this->defaultHandler : null); |
| 76 | + } |
| 77 | + |
| 78 | + private function hasHandler($name) |
| 79 | + { |
| 80 | + return array_key_exists($name, $this->handlers); |
| 81 | + } |
| 82 | + } |
0 commit comments