Skip to content

Commit 4a034f6

Browse files
authored
Merge pull request #46 from xp-framework/feature/child-package
Add Package::child() to return child packages
2 parents 590433f + 604617e commit 4a034f6

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@ $package->literal(); // 'org\example'
187187
$package->type('Fixture'); // Type instance
188188
$package->types(); // iterable with Type instances
189189
$package->parent() // Package or NULL
190+
$package->child('impl') // Child package "org.example.impl" or NULL
190191
$package->children(); // iterable with Package instances
191192
$package->classLoaders(); // iterable with lang.ClassLoader instances
192193
```

src/main/php/lang/reflection/Package.class.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,21 @@ public function parent() {
5454
return false === $p ? new Package() : new Package(substr($this->name, 0, $p));
5555
}
5656

57+
/**
58+
* Returns a child package with a given name. Returns NULL if the child package
59+
* does not exist.
60+
*
61+
* @return ?self
62+
*/
63+
public function child(string $name) {
64+
$child= ($this->name ? $this->name.'.' : '').strtr($name, '\\', '.');
65+
if (ClassLoader::getDefault()->providesPackage($child)) {
66+
return new self($child);
67+
} else {
68+
return null;
69+
}
70+
}
71+
5772
/**
5873
* Returns this package's child packages
5974
*

src/test/php/lang/reflection/unittest/PackageTest.class.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,27 @@ public function global_package_has_no_parent() {
5151
Assert::null((new Package())->parent());
5252
}
5353

54+
#[Test]
55+
public function non_existant_child() {
56+
Assert::null((new Package())->child('lang.non_existant_package'));
57+
}
58+
59+
#[Test, Values(['reflection.unittest', 'reflection\\unittest'])]
60+
public function resolve_child($reference) {
61+
Assert::equals(
62+
new Package('lang.reflection.unittest'),
63+
(new Package('lang'))->child($reference)
64+
);
65+
}
66+
67+
#[Test, Values(['lang.reflection.unittest', 'lang\\reflection\\unittest'])]
68+
public function toplevel_child($reference) {
69+
Assert::equals(
70+
new Package('lang.reflection.unittest'),
71+
(new Package())->child($reference)
72+
);
73+
}
74+
5475
#[Test]
5576
public function children() {
5677
Assert::equals(

0 commit comments

Comments
 (0)