FactoryGenerator.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. /*
  3. Copyright (c) 2009 hamcrest.org
  4. */
  5. /**
  6. * Controls the process of extracting @factory doctags
  7. * and generating factory method files.
  8. *
  9. * Uses File_Iterator to scan for PHP files.
  10. */
  11. class FactoryGenerator
  12. {
  13. /**
  14. * Path to the Hamcrest PHP files to process.
  15. *
  16. * @var string
  17. */
  18. private $path;
  19. /**
  20. * @var array of FactoryFile
  21. */
  22. private $factoryFiles;
  23. public function __construct($path)
  24. {
  25. $this->path = $path;
  26. $this->factoryFiles = array();
  27. }
  28. public function addFactoryFile(FactoryFile $factoryFile)
  29. {
  30. $this->factoryFiles[] = $factoryFile;
  31. }
  32. public function generate()
  33. {
  34. $classes = $this->getClassesWithFactoryMethods();
  35. foreach ($classes as $class) {
  36. foreach ($class->getMethods() as $method) {
  37. foreach ($method->getCalls() as $call) {
  38. foreach ($this->factoryFiles as $file) {
  39. $file->addCall($call);
  40. }
  41. }
  42. }
  43. }
  44. }
  45. public function write()
  46. {
  47. foreach ($this->factoryFiles as $file) {
  48. $file->build();
  49. $file->write();
  50. }
  51. }
  52. public function getClassesWithFactoryMethods()
  53. {
  54. $classes = array();
  55. $files = $this->getSortedFiles();
  56. foreach ($files as $file) {
  57. $class = $this->getFactoryClass($file);
  58. if ($class !== null) {
  59. $classes[] = $class;
  60. }
  61. }
  62. return $classes;
  63. }
  64. public function getSortedFiles()
  65. {
  66. $iter = \File_Iterator_Factory::getFileIterator($this->path, '.php');
  67. $files = array();
  68. foreach ($iter as $file) {
  69. $files[] = $file;
  70. }
  71. sort($files, SORT_STRING);
  72. return $files;
  73. }
  74. public function getFactoryClass($file)
  75. {
  76. $name = $this->getFactoryClassName($file);
  77. if ($name !== null) {
  78. require_once $file;
  79. if (class_exists($name)) {
  80. $class = new FactoryClass(substr($file, strpos($file, 'Hamcrest/')), new ReflectionClass($name));
  81. if ($class->isFactory()) {
  82. return $class;
  83. }
  84. }
  85. }
  86. return null;
  87. }
  88. public function getFactoryClassName($file)
  89. {
  90. $content = file_get_contents($file);
  91. if (preg_match('/namespace\s+(.+);/', $content, $namespace)
  92. && preg_match('/\n\s*class\s+(\w+)\s+extends\b/', $content, $className)
  93. && preg_match('/@factory\b/', $content)
  94. ) {
  95. return $namespace[1] . '\\' . $className[1];
  96. }
  97. return null;
  98. }
  99. }