Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
15 changes: 15 additions & 0 deletions src/main/php/lang/reflection/Package.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down
21 changes: 21 additions & 0 deletions src/test/php/lang/reflection/unittest/PackageTest.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading