File tree Expand file tree Collapse file tree 3 files changed +56
-2
lines changed Expand file tree Collapse file tree 3 files changed +56
-2
lines changed Original file line number Diff line number Diff line change @@ -390,6 +390,10 @@ $namespace = new Nette\PhpGenerator\PhpNamespace('Foo');
390
390
$class = $namespace->addClass('Task');
391
391
$interface = $namespace->addInterface('Countable');
392
392
$trait = $namespace->addTrait('NameAware');
393
+
394
+ // or
395
+ $class = new Nette\PhpGenerator\ClassType('Task');
396
+ $namespace->add($class);
393
397
```
394
398
395
399
If the class already exists, it will be overwritten.
Original file line number Diff line number Diff line change @@ -145,10 +145,25 @@ public function unresolveName(string $name): string
145
145
}
146
146
147
147
148
- public function addClass (string $ name ): ClassType
148
+ /**
149
+ * @return static
150
+ */
151
+ public function add (ClassType $ class ): self
149
152
{
153
+ $ name = $ class ->getName ();
154
+ if ($ name === null ) {
155
+ throw new Nette \InvalidArgumentException ('Class does not have a name. ' );
156
+ }
150
157
$ this ->addUse ($ this ->name . '\\' . $ name );
151
- return $ this ->classes [$ name ] = new ClassType ($ name , $ this );
158
+ $ this ->classes [$ name ] = $ class ;
159
+ return $ this ;
160
+ }
161
+
162
+
163
+ public function addClass (string $ name ): ClassType
164
+ {
165
+ $ this ->add ($ class = new ClassType ($ name , $ this ));
166
+ return $ class ;
152
167
}
153
168
154
169
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ declare (strict_types=1 );
4
+
5
+ use Nette \PhpGenerator \ClassType ;
6
+ use Nette \PhpGenerator \PhpNamespace ;
7
+ use Tester \Assert ;
8
+
9
+ require __DIR__ . '/../bootstrap.php ' ;
10
+
11
+
12
+ Assert::exception (function () {
13
+ (new PhpNamespace ('Foo ' ))->add (new ClassType );
14
+ }, Nette \InvalidArgumentException::class, 'Class does not have a name. ' );
15
+
16
+
17
+ $ namespace = (new PhpNamespace ('Foo ' ))
18
+ ->add ($ classA = new ClassType ('A ' ))
19
+ ->add ($ classB = new ClassType ('B ' , new PhpNamespace ('X ' )));
20
+
21
+
22
+ same ('namespace Foo;
23
+
24
+ class A
25
+ {
26
+ }
27
+
28
+ class B
29
+ {
30
+ }
31
+ ' , (string ) $ namespace );
32
+
33
+ // namespaces are not changed
34
+ Assert::null ($ classA ->getNamespace ());
35
+ Assert::same ('X ' , $ classB ->getNamespace ()->getName ());
You can’t perform that action at this time.
0 commit comments