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;
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
23: {
24: use Nette\SmartObject;
25: use Traits\CommentAware;
26:
27: /** @var PhpNamespace[] */
28: private $namespaces = [];
29:
30:
31: /**
32: * @param string
33: * @return ClassType
34: */
35: public function addClass($name)
36: {
37: return $this
38: ->addNamespace(Helpers::extractNamespace($name))
39: ->addClass(Helpers::extractShortName($name));
40: }
41:
42:
43: /**
44: * @param string
45: * @return ClassType
46: */
47: public function addInterface($name)
48: {
49: return $this
50: ->addNamespace(Helpers::extractNamespace($name))
51: ->addInterface(Helpers::extractShortName($name));
52: }
53:
54:
55: /**
56: * @param string
57: * @return ClassType
58: */
59: public function addTrait($name)
60: {
61: return $this
62: ->addNamespace(Helpers::extractNamespace($name))
63: ->addTrait(Helpers::extractShortName($name));
64: }
65:
66:
67: /**
68: * @param string null means global namespace
69: * @return PhpNamespace
70: */
71: public function addNamespace($name)
72: {
73: if (!isset($this->namespaces[$name])) {
74: $this->namespaces[$name] = new PhpNamespace($name);
75: }
76: return $this->namespaces[$name];
77: }
78:
79:
80: /**
81: * @return string PHP code
82: */
83: public function __toString()
84: {
85: foreach ($this->namespaces as $namespace) {
86: $namespace->setBracketedSyntax(count($this->namespaces) > 1 && isset($this->namespaces[null]));
87: }
88:
89: return Strings::normalize(
90: "<?php\n"
91: . ($this->comment ? "\n" . Helpers::formatDocComment($this->comment . "\n") . "\n" : '')
92: . implode("\n\n", $this->namespaces)
93: ) . "\n";
94: }
95: }
96: