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