Skip to content

Commit d2bfe37

Browse files
committed
docs: Describe tryRelative() and isWithin() in README
Assisted-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 3a8ca39 commit d2bfe37

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,46 @@ $absolute = $relative->absolute('/var/www/app');
9292
echo $path; // Path implements Stringable
9393
```
9494

95+
### Computing relative paths
96+
97+
```php
98+
$path = Path::create('/var/www/app/src/Controller.php');
99+
100+
$path->tryRelative('/var/www/app'); // Path('src/Controller.php')
101+
$path->tryRelative('/var/www/logs'); // Path('../app/src/Controller.php') – may traverse upwards
102+
$path->tryRelative('/var/www/app/src/Controller.php'); // Path('.') – path equals base
103+
104+
// Returns null when a relative path cannot be built at all,
105+
// e.g. for paths on different Windows drives
106+
Path::create('D:/data/file.txt')->tryRelative('C:/Users'); // null
107+
108+
// A relative path is returned as is: Path carries no base of its own
109+
Path::create('src/file.php')->tryRelative('/var/www'); // Path('src/file.php')
110+
```
111+
112+
### Containment checks
113+
114+
```php
115+
$path = Path::create('/var/www/app/src/file.php');
116+
117+
$path->isWithin('/var/www/app'); // true
118+
$path->isWithin('/var/www'); // true
119+
$path->isWithin('/var/log'); // false
120+
$path->isWithin('/var/www-old'); // false – partial segment match doesn't count
121+
122+
// A path is always within itself
123+
Path::create('/var/www')->isWithin('/var/www'); // true
124+
125+
// The base defaults to the current working directory,
126+
// which makes it a convenient guard against path traversal in user input
127+
Path::create('uploads/avatar.png')->isWithin(); // true
128+
Path::create('../../etc/passwd')->isWithin(); // false
129+
```
130+
131+
The check is lexical: paths are compared segment by segment without touching
132+
the filesystem. Segment comparison is case-insensitive on Windows and
133+
case-sensitive on Unix.
134+
95135
### Pattern matching
96136

97137
```php

0 commit comments

Comments
 (0)