FactoryFile.php
3.0 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
<?php
/*
Copyright (c) 2009 hamcrest.org
*/
abstract class FactoryFile
{
/**
* Hamcrest standard is two spaces for each level of indentation.
*
* @var string
*/
const INDENT = ' ';
private $indent;
private $file;
private $code;
public function __construct($file, $indent)
{
$this->file = $file;
$this->indent = $indent;
}
abstract public function addCall(FactoryCall $call);
abstract public function build();
public function addFileHeader()
{
$this->code = '';
$this->addPart('file_header');
}
public function addPart($name)
{
$this->addCode($this->readPart($name));
}
public function addCode($code)
{
$this->code .= $code;
}
public function readPart($name)
{
return file_get_contents(__DIR__ . "/parts/$name.txt");
}
public function generateFactoryCall(FactoryCall $call)
{
$method = $call->getMethod();
$code = $method->getComment($this->indent) . "\n";
$code .= $this->generateDeclaration($call->getName(), $method);
$code .= $this->generateCall($method);
$code .= $this->generateClosing();
return $code;
}
public function generateDeclaration($name, FactoryMethod $method)
{
$code = $this->indent . $this->getDeclarationModifiers()
. 'function ' . $name . '('
. $this->generateDeclarationArguments($method)
. ')' . "\n" . $this->indent . '{' . "\n";
return $code;
}
public function getDeclarationModifiers()
{
return '';
}
public function generateDeclarationArguments(FactoryMethod $method)
{
if ($method->acceptsVariableArguments()) {
return '/* args... */';
} else {
return $method->getParameterDeclarations();
}
}
public function generateImport(FactoryMethod $method)
{
return $this->indent . self::INDENT . "require_once '" . $method->getClass()->getFile() . "';" . "\n";
}
public function generateCall(FactoryMethod $method)
{
$code = '';
if ($method->acceptsVariableArguments()) {
$code .= $this->indent . self::INDENT . '$args = func_get_args();' . "\n";
}
$code .= $this->indent . self::INDENT . 'return ';
if ($method->acceptsVariableArguments()) {
$code .= 'call_user_func_array(array(\''
. '\\' . $method->getClassName() . '\', \''
. $method->getName() . '\'), $args);' . "\n";
} else {
$code .= '\\' . $method->getClassName() . '::'
. $method->getName() . '('
. $method->getParameterInvocations() . ');' . "\n";
}
return $code;
}
public function generateClosing()
{
return $this->indent . '}' . "\n";
}
public function write()
{
file_put_contents($this->file, $this->code);
}
}