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