MDDoImageURL.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * @package Kohana/Codebench
  4. * @category Tests
  5. * @author Geert De Deckere <geert@idoe.be>
  6. */
  7. class Bench_MDDoImageURL extends Codebench {
  8. public $description =
  9. 'Optimization for the <code>doImageURL()</code> method of <code>Kohana_Kodoc_Markdown</code>
  10. for the Kohana Userguide.';
  11. public $loops = 10000;
  12. public $subjects = [
  13. // Valid matches
  14. '![Alt text](http://img.skitch.com/20091019-rud5mmqbf776jwua6hx9nm1n.png)',
  15. '![Alt text](https://img.skitch.com/20091019-rud5mmqbf776jwua6hx9nm1n.png)',
  16. '![Alt text](otherprotocol://image.png "Optional title")',
  17. '![Alt text](img/install.png "Optional title")',
  18. '![Alt text containing [square] brackets](img/install.png)',
  19. '![Empty src]()',
  20. // Invalid matches
  21. '![Alt text](img/install.png "No closing parenthesis"',
  22. ];
  23. public function bench_original($subject)
  24. {
  25. return preg_replace_callback('~!\[(.+?)\]\((\S*(?:\s*".+?")?)\)~', [$this, '_add_image_url_original'], $subject);
  26. }
  27. protected function _add_image_url_original($matches)
  28. {
  29. if ($matches[2] AND strpos($matches[2], '://') === FALSE)
  30. {
  31. // Add the base url to the link URL
  32. $matches[2] = 'http://BASE/'.$matches[2];
  33. }
  34. // Recreate the link
  35. return "![{$matches[1]}]({$matches[2]})";
  36. }
  37. public function bench_optimized_callback($subject)
  38. {
  39. // Moved the check for "://" to the regex, simplifying the callback function
  40. return preg_replace_callback('~!\[(.+?)\]\((?!\w++://)(\S*(?:\s*+".+?")?)\)~', [$this, '_add_image_url_optimized'], $subject);
  41. }
  42. protected function _add_image_url_optimized($matches)
  43. {
  44. // Add the base url to the link URL
  45. $matches[2] = 'http://BASE/'.$matches[2];
  46. // Recreate the link
  47. return "![{$matches[1]}]({$matches[2]})";
  48. }
  49. public function bench_callback_gone($subject)
  50. {
  51. // All the optimized callback was doing now, is prepend some text to the URL.
  52. // We don't need a callback for that, and that should be clearly faster.
  53. return preg_replace('~(!\[.+?\]\()(?!\w++://)(\S*(?:\s*+".+?")?\))~', '$1http://BASE/$2', $subject);
  54. }
  55. }