diff --git a/README.md b/README.md index c7b594f..8a40b8b 100755 --- a/README.md +++ b/README.md @@ -187,6 +187,7 @@ $package->literal(); // 'org\example' $package->type('Fixture'); // Type instance $package->types(); // iterable with Type instances $package->parent() // Package or NULL +$package->child('impl') // Child package "org.example.impl" or NULL $package->children(); // iterable with Package instances $package->classLoaders(); // iterable with lang.ClassLoader instances ``` diff --git a/src/main/php/lang/reflection/Package.class.php b/src/main/php/lang/reflection/Package.class.php index 92088bb..4ba20b0 100755 --- a/src/main/php/lang/reflection/Package.class.php +++ b/src/main/php/lang/reflection/Package.class.php @@ -54,6 +54,21 @@ public function parent() { return false === $p ? new Package() : new Package(substr($this->name, 0, $p)); } + /** + * Returns a child package with a given name. Returns NULL if the child package + * does not exist. + * + * @return ?self + */ + public function child(string $name) { + $child= ($this->name ? $this->name.'.' : '').strtr($name, '\\', '.'); + if (ClassLoader::getDefault()->providesPackage($child)) { + return new self($child); + } else { + return null; + } + } + /** * Returns this package's child packages * diff --git a/src/test/php/lang/reflection/unittest/PackageTest.class.php b/src/test/php/lang/reflection/unittest/PackageTest.class.php index 90ca737..9c4c397 100755 --- a/src/test/php/lang/reflection/unittest/PackageTest.class.php +++ b/src/test/php/lang/reflection/unittest/PackageTest.class.php @@ -51,6 +51,27 @@ public function global_package_has_no_parent() { Assert::null((new Package())->parent()); } + #[Test] + public function non_existant_child() { + Assert::null((new Package())->child('lang.non_existant_package')); + } + + #[Test, Values(['reflection.unittest', 'reflection\\unittest'])] + public function resolve_child($reference) { + Assert::equals( + new Package('lang.reflection.unittest'), + (new Package('lang'))->child($reference) + ); + } + + #[Test, Values(['lang.reflection.unittest', 'lang\\reflection\\unittest'])] + public function toplevel_child($reference) { + Assert::equals( + new Package('lang.reflection.unittest'), + (new Package())->child($reference) + ); + } + #[Test] public function children() { Assert::equals(