1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (http://nette.org)
5: * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
6: */
7:
8: namespace Nette\PhpGenerator;
9:
10: use Nette\Object;
11: use Nette\Utils\Strings;
12:
13:
14: /**
15: * Instance of PHP file.
16: *
17: * Generates:
18: * - opening tag (<?php)
19: * - doc comments
20: * - one or more namespaces
21: *
22: * @author Jakub Kulhan <jakub.kulhan@gmail.com>
23: */
24: class PhpFile extends Object
25: {
26: /** @var string[] */
27: private $documents;
28:
29: /** @var PhpNamespace[] */
30: private $namespaces = array();
31:
32:
33: /**
34: * @return string[]
35: */
36: public function getDocuments()
37: {
38: return $this->documents;
39: }
40:
41:
42: /**
43: * @param string[]
44: * @return self
45: */
46: public function setDocuments(array $documents)
47: {
48: $this->documents = $documents;
49: return $this;
50: }
51:
52:
53: /**
54: * @param string
55: * @return self
56: */
57: public function addDocument($document)
58: {
59: $this->documents[] = $document;
60: return $this;
61: }
62:
63:
64: /**
65: * @param string
66: * @return ClassType
67: */
68: public function addClass($name)
69: {
70: return $this
71: ->addNamespace(Helpers::extractNamespace($name))
72: ->addClass(Helpers::extractShortName($name));
73: }
74:
75:
76: /**
77: * @param string
78: * @return ClassType
79: */
80: public function addInterface($name)
81: {
82: return $this
83: ->addNamespace(Helpers::extractNamespace($name))
84: ->addInterface(Helpers::extractShortName($name));
85: }
86:
87:
88: /**
89: * @param string
90: * @return ClassType
91: */
92: public function addTrait($name)
93: {
94: return $this
95: ->addNamespace(Helpers::extractNamespace($name))
96: ->addTrait(Helpers::extractShortName($name));
97: }
98:
99:
100: /**
101: * @param string NULL means global namespace
102: * @return PhpNamespace
103: */
104: public function addNamespace($name)
105: {
106: if (!isset($this->namespaces[$name])) {
107: $this->namespaces[$name] = new PhpNamespace($name);
108: }
109: return $this->namespaces[$name];
110: }
111:
112:
113: /**
114: * @return string PHP code
115: */
116: public function __toString()
117: {
118: foreach ($this->namespaces as $namespace) {
119: $namespace->setBracketedSyntax(isset($this->namespaces[NULL]));
120: }
121:
122: return Strings::normalize(
123: "<?php\n"
124: . ($this->documents ? "\n" . str_replace("\n", "\n * ", "/**\n" . implode("\n", (array) $this->documents)) . "\n */\n\n" : '')
125: . implode("\n\n", $this->namespaces)
126: ) . "\n";
127: }
128:
129: }
130: