You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.6 KiB

  1. <?php
  2. /**
  3. * Generates array of classes for autoload
  4. *
  5. * @copyright NetMonsters <team@netmonsters.ru>
  6. * @link http://netmonsters.ru
  7. * @package Majestic
  8. * @subpackage util
  9. * @since 2010-02-24
  10. * @version SVN: $Id$
  11. * @filesource $URL$
  12. */
  13. /**
  14. * @todo Refactoring writing, locking
  15. */
  16. class AutoloadBuilder
  17. {
  18. protected $autoload;
  19. protected $dirs;
  20. protected $handler;
  21. protected $regex = '/(class|interface) ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/';
  22. public function __construct($autoload, $dirs = array())
  23. {
  24. $this->autoload = $autoload;
  25. $this->dirs = $dirs;
  26. }
  27. public function build()
  28. {
  29. $this->openAutoload();
  30. // for dublicates check
  31. $classes = array();
  32. foreach ($this->dirs as $dir) {
  33. $iterator = new RecursiveIteratorIterator(
  34. new RecursiveDirectoryIterator($dir),
  35. RecursiveIteratorIterator::LEAVES_ONLY
  36. );
  37. foreach ($iterator as $file) {
  38. // skip non php files
  39. $e = explode('.', $file->getFileName());
  40. if ((end($e) !== 'php') || strstr((string)$file, 'test')) {
  41. continue;
  42. }
  43. $content = file_get_contents($file->getRealPath());
  44. $matches = array();
  45. $relative_path = substr($file->getRealPath(), strlen(PATH));
  46. if (preg_match_all($this->regex, $content, $matches, PREG_SET_ORDER)) {
  47. foreach ($matches as $match) {
  48. if (array_key_exists($match[2], $classes)) {
  49. continue;
  50. }
  51. $string = "'{$match[2]}'=>'" . $relative_path . "',\n";
  52. $this->write($string);
  53. $classes[$match[2]] = $file->getRealPath();
  54. }
  55. }
  56. }
  57. }
  58. $this->closeAutoload();
  59. }
  60. protected function openAutoload()
  61. {
  62. $this->write("<?php\n// This file is autogenerated by \n// " . __FILE__ . " script.\nreturn array(\n");
  63. }
  64. protected function closeAutoload()
  65. {
  66. if ($this->write(');')) {
  67. fclose($this->handler);
  68. }
  69. }
  70. protected function write($string)
  71. {
  72. if (! $this->handler) {
  73. if (! $this->handler = fopen($this->autoload, 'w')) {
  74. trigger_error("{$this->autoload} is not writable", E_USER_ERROR);
  75. }
  76. }
  77. return (bool) fwrite($this->handler, $string);
  78. }
  79. }