Path.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. <?php
  2. namespace Path;
  3. use Generator;
  4. use Path\Exception\FileExistsException;
  5. use Path\Exception\FileNotFoundException;
  6. use Path\Exception\IOException;
  7. use RuntimeException;
  8. use Throwable;
  9. /**
  10. * Represents a file or directory path.
  11. *
  12. * @package olinox14/path
  13. */
  14. class Path
  15. {
  16. /**
  17. * File exists
  18. */
  19. const F_OK = 0;
  20. /**
  21. * Has read permission on the file
  22. */
  23. const R_OK = 4;
  24. /**
  25. * Has write permission on the file
  26. */
  27. const W_OK = 2;
  28. /**
  29. * Has execute permission on the file
  30. */
  31. const X_OK = 1;
  32. protected string $path;
  33. protected mixed $handle;
  34. protected BuiltinProxy $builtin;
  35. /**
  36. * Joins two or more parts of a path together, inserting '/' as needed.
  37. * If any component is an absolute path, all previous path components
  38. * will be discarded. An empty last part will result in a path that
  39. * ends with a separator.
  40. *
  41. * TODO: see if necessary : https://github.com/python/cpython/blob/d22c066b802592932f9eb18434782299e80ca42e/Lib/posixpath.py#L81
  42. *
  43. * @param string|Path $path The base path
  44. * @param string ...$parts The parts of the path to be joined.
  45. * @return string The resulting path after joining the parts using the directory separator.
  46. */
  47. public static function join(string|self $path, string|self ...$parts): string
  48. {
  49. $path = (string)$path;
  50. $parts = array_map(fn($x) => (string)$x, $parts);
  51. foreach ($parts as $part) {
  52. if (str_starts_with($part, DIRECTORY_SEPARATOR)) {
  53. $path = $part;
  54. } elseif (!$path || str_ends_with($path, DIRECTORY_SEPARATOR)) {
  55. $path .= $part;
  56. } else {
  57. $path .= DIRECTORY_SEPARATOR . $part;
  58. }
  59. }
  60. return $path;
  61. }
  62. /**
  63. * Copies a directory and its contents recursively from the source directory to the destination directory.
  64. *
  65. * @param string|self $src The source directory to be copied. It can be a string representing the directory path
  66. * or an instance of the same class.
  67. * @param string|self $dst The destination directory where the source directory and its contents will be copied.
  68. * It can be a string representing the directory path or an instance of the same class.
  69. *
  70. * @return void
  71. * TODO: see https://stackoverflow.com/a/12763962/4279120
  72. * TODO: en faire une méthode non statique et tester
  73. *
  74. * @throws FileNotFoundException
  75. * @throws FileExistsException
  76. * @throws IOException
  77. */
  78. public static function copy_dir(string|self $src, string|self $dst): void
  79. {
  80. $src = (string)$src;
  81. $dst = (string)$dst;
  82. if (!is_dir($src)) {
  83. throw new FileNotFoundException("Directory does not exist : " . $src);
  84. }
  85. if (!is_dir($dst)) {
  86. throw new FileNotFoundException("Directory does not exist : " . $dst);
  87. }
  88. $newDir = self::join($dst, pathinfo($src, PATHINFO_FILENAME));
  89. if (file_exists($newDir)) {
  90. throw new FileExistsException("Directory already exists : " . $newDir);
  91. }
  92. self::_copy_dir($src, $dst);
  93. }
  94. /**
  95. * [internal] Recursively copies a directory from source to destination.
  96. * TODO: en faire une méthode non statique et tester
  97. * @param string $src The path to the source directory.
  98. * @param string $dst The path to the destination directory.
  99. * @return void
  100. * @throws FileNotFoundException If a file within the source directory does not exist.
  101. * @throws IOException
  102. */
  103. private static function _copy_dir(string $src, string $dst): void
  104. {
  105. $dir = opendir($src);
  106. if (!is_dir($dst)) {
  107. mkdir($dst);
  108. }
  109. try {
  110. while (($file = readdir($dir)) !== false) {
  111. if ($file === '.' || $file === '..') {
  112. continue;
  113. }
  114. $path = self::join($src, $file);
  115. $newPath = self::join($dst, $file);
  116. if (is_dir($path)) {
  117. self::_copy_dir($path, $newPath);
  118. } else if(is_file($path)) {
  119. $success = copy($path, $newPath);
  120. if (!$success) {
  121. throw new IOException("Error copying file {$path} to {$newPath}");
  122. }
  123. } else {
  124. throw new FileNotFoundException("File does not exist : " . $path);
  125. }
  126. }
  127. } finally {
  128. closedir($dir);
  129. }
  130. }
  131. protected function rrmdir(): bool
  132. {
  133. if (!is_dir($this->path)) {
  134. return false;
  135. }
  136. foreach (scandir($this->path) as $object) {
  137. if ($object == "." || $object == "..") {
  138. continue;
  139. }
  140. if (is_dir($this->path. DIRECTORY_SEPARATOR .$object) && !is_link($this->path ."/".$object)) {
  141. $this->rrmdir();
  142. }
  143. else {
  144. unlink($this->path . DIRECTORY_SEPARATOR . $object);
  145. }
  146. }
  147. return rmdir($this->path);
  148. }
  149. public function __construct(string|self $path)
  150. {
  151. $this->builtin = new BuiltinProxy();
  152. $this->path = (string)$path;
  153. $this->handle = null;
  154. return $this;
  155. }
  156. public function __toString(): string {
  157. return $this->path;
  158. }
  159. protected function cast(string|self $path): self
  160. {
  161. return new self($path);
  162. }
  163. /**
  164. * Retrieves the current path of the file or directory
  165. *
  166. * @return string The path of the file or directory
  167. */
  168. public function path(): string
  169. {
  170. return $this->path;
  171. }
  172. /**
  173. * Checks if the given path is equal to the current path.
  174. *
  175. * @param string|Path $path The path to compare against.
  176. *
  177. * @return bool Returns true if the given path is equal to the current path, false otherwise.
  178. */
  179. public function eq(string|self $path): bool {
  180. return $this->cast($path)->path() === $this->path();
  181. }
  182. /**
  183. * Appends parts to the current path.
  184. *
  185. * @see Path::join()
  186. *
  187. * @param string ...$parts The parts to be appended to the current path.
  188. * @return self Returns an instance of the class with the appended path.
  189. */
  190. public function append(string ...$parts): self
  191. {
  192. $this->path = self::join($this->path, ...$parts);
  193. return $this;
  194. }
  195. /**
  196. * Returns an absolute version of the current path.
  197. *
  198. * @return self
  199. * TODO: make an alias `realpath`
  200. * @throws IOException
  201. */
  202. public function absPath(): self
  203. {
  204. $absPath = $this->builtin->realpath($this->path);
  205. if ($absPath === false) {
  206. throw new IOException("Error while getting abspath of `" . $this->path . "`");
  207. }
  208. return $this->cast($absPath);
  209. }
  210. /**
  211. * > Alias for absPath()
  212. * @throws IOException
  213. */
  214. public function realpath(): self
  215. {
  216. return $this->absPath();
  217. }
  218. /**
  219. * Checks the access rights for a given file or directory.
  220. * From the python `os.access` method
  221. *
  222. * @param int $mode The access mode to check. Permitted values:
  223. * - F_OK: checks for the existence of the file or directory.
  224. * - R_OK: checks for read permission.
  225. * - W_OK: checks for write permission.
  226. * - X_OK: checks for execute permission.
  227. * @return bool Returns true if the permission check is successful; otherwise, returns false.
  228. */
  229. function access(int $mode): bool
  230. {
  231. return match ($mode) {
  232. self::F_OK => $this->builtin->file_exists($this->path),
  233. self::R_OK => $this->builtin->is_readable($this->path),
  234. self::W_OK => $this->builtin->is_writable($this->path),
  235. self::X_OK => $this->builtin->is_executable($this->path),
  236. default => throw new RuntimeException('Invalid mode'),
  237. };
  238. }
  239. /**
  240. * Retrieves the last access time of a file or directory.
  241. *
  242. * @return string|null The last access time of the file or directory in 'Y-m-d H:i:s' format.
  243. * Returns null if the file or directory does not exist or on error.
  244. */
  245. function atime(): ?string
  246. {
  247. $time = $this->builtin->fileatime($this->path);
  248. if ($time === false) {
  249. return null;
  250. }
  251. return $this->builtin->date('Y-m-d H:i:s', $time);
  252. }
  253. /**
  254. * Retrieves the creation time of a file or directory.
  255. *
  256. * @return string|null The creation time of the file or directory in 'Y-m-d H:i:s' format,
  257. * or null if the time could not be retrieved.
  258. */
  259. function ctime(): ?string
  260. {
  261. $time = $this->builtin->filectime($this->path);
  262. if ($time === false) {
  263. return null;
  264. }
  265. return $this->builtin->date('Y-m-d H:i:s', $time);
  266. }
  267. /**
  268. * Retrieves the last modified time of a file or directory.
  269. *
  270. * @return string|null The last modified time of the file or directory in the format 'Y-m-d H:i:s', or null if the time cannot be determined.
  271. */
  272. function mtime(): ?string
  273. {
  274. $time = $this->builtin->filemtime($this->path);
  275. if ($time === false) {
  276. return null;
  277. }
  278. return $this->builtin->date('Y-m-d H:i:s', $time);
  279. }
  280. /**
  281. * Check if the path refers to a regular file.
  282. *
  283. * @return bool Returns true if the path refers to a regular file, otherwise returns false.
  284. */
  285. public function isFile(): bool
  286. {
  287. return $this->builtin->is_file($this->path);
  288. }
  289. /**
  290. * Check if the given path is a directory.
  291. *
  292. * @return bool Returns true if the path is a directory, false otherwise.
  293. */
  294. public function isDir(): bool
  295. {
  296. return $this->builtin->is_dir($this->path);
  297. }
  298. /**
  299. * Get the extension of the given path.
  300. *
  301. * @return string Returns the extension of the path as a string if it exists, or an empty string otherwise.
  302. */
  303. public function ext(): string
  304. {
  305. return $this->builtin->pathinfo($this->path, PATHINFO_EXTENSION);
  306. }
  307. /**
  308. * Get the base name of the path.
  309. *
  310. * @return string The base name of the path.
  311. */
  312. public function basename(): string
  313. {
  314. return $this->builtin->pathinfo($this->path, PATHINFO_BASENAME);
  315. }
  316. /**
  317. * Changes the current working directory.
  318. *
  319. * @param string|self $path The path to the directory to change into.
  320. * It can be either a string containing the path or an instance of the same class.
  321. * @return bool True on success, false on failure.
  322. */
  323. public function cd(string|self $path): bool
  324. {
  325. return $this->builtin->chdir((string)$path);
  326. }
  327. /**
  328. * > alias for Path->cd($path)
  329. *
  330. * @param string|Path $path
  331. * @return bool
  332. */
  333. public function chdir(string|self $path): bool
  334. {
  335. return $this->cd($path);
  336. }
  337. /**
  338. * Get the name of the file or path.
  339. *
  340. * @return string Returns the name of the file without its extension
  341. */
  342. public function name(): string
  343. {
  344. return $this->builtin->pathinfo($this->path, PATHINFO_FILENAME);
  345. }
  346. public function normcase()
  347. {
  348. // TODO: implement https://docs.python.org/3/library/os.path.html#os.path.normcase
  349. }
  350. public function normpath()
  351. {
  352. // TODO: implement https://docs.python.org/3/library/os.path.html#os.path.normpath
  353. }
  354. /**
  355. * Creates a new directory.
  356. *
  357. * @param int $mode (optional) The permissions for the new directory. Default is 0777.
  358. * @param bool $recursive (optional) Indicates whether to create parent directories if they do not exist. Default is false.
  359. *
  360. * @return void
  361. * @throws FileExistsException
  362. * @throws IOException
  363. */
  364. public function mkdir(int $mode = 0777, bool $recursive = false): void
  365. {
  366. // TODO: may we make $mode the second arg, and mimic the mode of the parent if not provided?
  367. if ($this->isDir()) {
  368. if (!$recursive) {
  369. throw new FileExistsException("Directory already exists : " . $this);
  370. } else {
  371. return;
  372. }
  373. }
  374. if ($this->isFile()) {
  375. throw new FileExistsException("A file with this name already exists : " . $this);
  376. }
  377. $result = $this->builtin->mkdir($this->path, $mode, $recursive);
  378. if (!$result) {
  379. throw new IOException("Error why creating the new directory : " . $this->path);
  380. }
  381. }
  382. /**
  383. * Deletes a file or a directory.
  384. *
  385. * @return void
  386. * @throws FileNotFoundException
  387. * @throws IOException
  388. */
  389. public function delete(): void
  390. {
  391. if ($this->isFile()) {
  392. $result = $this->builtin->unlink($this->path);
  393. if (!$result) {
  394. throw new IOException("Error why deleting file : " . $this->path);
  395. }
  396. } else if ($this->isDir()) {
  397. $result = $this->builtin->rmdir($this->path);
  398. if (!$result) {
  399. throw new IOException("Error why deleting directory : " . $this->path);
  400. }
  401. } else {
  402. throw new FileNotFoundException("File does not exist : " . $this);
  403. }
  404. }
  405. /**
  406. * Copy data and mode bits (“cp src dst”). Return the file’s destination.
  407. * The destination may be a directory.
  408. * If follow_symlinks is false, symlinks won’t be followed. This resembles GNU’s “cp -P src dst”.
  409. * TODO: implements the follow_symlinks functionality
  410. *
  411. * @param string|self $destination The destination path or object to copy the file to.
  412. * @throws FileNotFoundException If the source file does not exist or is not a file.
  413. * @throws FileExistsException
  414. * @throws IOException
  415. */
  416. public function copy(string|self $destination, bool $follow_symlinks = false): self
  417. {
  418. if (!$this->isFile()) {
  419. throw new FileNotFoundException("File does not exist or is not a file : " . $this);
  420. }
  421. $destination = (string)$destination; // TODO: add an absPath method to the dest?
  422. if ($this->builtin->is_dir($destination)) {
  423. $destination = self::join($destination, $this->basename());
  424. }
  425. if ($this->builtin->file_exists($destination)) {
  426. throw new FileExistsException("File already exists : " . $destination);
  427. }
  428. $success = $this->builtin->copy($this->path, $destination);
  429. if (!$success) {
  430. throw new IOException("Error copying file {$this->path} to {$destination}");
  431. }
  432. return $this->cast($destination);
  433. }
  434. /**
  435. * Copies the content of a file or directory to the specified destination.
  436. *
  437. * @param string|self $destination The destination path or directory to copy the content to.
  438. * @param bool $follow_symlinks (Optional) Whether to follow symbolic links.
  439. * @return self The object on which the method is called.
  440. * @throws FileExistsException If the destination path or directory already exists.
  441. * @throws FileNotFoundException If the source file or directory does not exist.
  442. * @throws IOException
  443. */
  444. public function copy_tree(string|self $destination, bool $follow_symlinks = false): self
  445. {
  446. // TODO: voir à faire la synthèse de copytree et https://path.readthedocs.io/en/latest/api.html#path.Path.merge_tree
  447. if ($this->isFile()) {
  448. $destination = (string)$destination;
  449. if ($this->builtin->is_dir($destination)) {
  450. $destination = self::join($destination, $this->basename());
  451. }
  452. if ($this->builtin->file_exists($destination)) {
  453. throw new FileExistsException("File or dir already exists : " . $destination);
  454. }
  455. $success = $this->builtin->copy($this->path, $destination);
  456. if (!$success) {
  457. throw new IOException("Error copying file {$this->path} to {$destination}");
  458. }
  459. } else if ($this->isDir()) {
  460. self::copy_dir($this, $destination);
  461. } else {
  462. throw new FileNotFoundException("File or dir does not exist : " . $this);
  463. }
  464. return new self($destination);
  465. }
  466. /**
  467. * Moves a file or directory to a new location.
  468. * Returns the path of the newly created file or directory.
  469. *
  470. * @param string|Path $destination The new location where the file or directory should be moved to.
  471. *
  472. * @return Path
  473. * @throws FileExistsException
  474. * @throws IOException
  475. */
  476. public function move(string|self $destination): self
  477. {
  478. // TODO: comparer à https://path.readthedocs.io/en/latest/api.html#path.Path.move
  479. $destination = (string)$destination;
  480. if ($this->builtin->is_dir($destination)) {
  481. $destination = self::join($destination, $this->basename());
  482. }
  483. if ($this->builtin->file_exists($destination)) {
  484. throw new FileExistsException("File or dir already exists : " . $destination);
  485. }
  486. $success = $this->builtin->rename($this->path, $destination);
  487. if (!$success) {
  488. throw new IOException("Error while moving " . $this->path . " to " . $destination);
  489. }
  490. return $this->cast($destination);
  491. }
  492. /**
  493. * Updates the access and modification time of a file or creates a new empty file if it doesn't exist.
  494. *
  495. * @param int|\DateTime|null $time (optional) The access and modification time to set. Default is the current time.
  496. * @param int|\DateTime|null $atime (optional) The access time to set. Default is the value of $time.
  497. *
  498. * @return void
  499. * @throws IOException
  500. */
  501. public function touch(int|\DateTime $time = null, int|\DateTime $atime = null): void
  502. {
  503. if ($time instanceof \DateTime) {
  504. $time = $time->getTimestamp();
  505. }
  506. if ($atime instanceof \DateTime) {
  507. $atime = $atime->getTimestamp();
  508. }
  509. $success = $this->builtin->touch($this->path, $time, $atime);
  510. if (!$success) {
  511. throw new IOException("Error while touching " . $this->path);
  512. }
  513. }
  514. /**
  515. * Calculates the size of a file.
  516. *
  517. * @return int The size of the file in bytes.
  518. * @throws FileNotFoundException
  519. * @throws IOException
  520. */
  521. public function size(): int
  522. {
  523. if (!$this->isFile()) {
  524. throw new FileNotFoundException("File does not exist : " . $this->path);
  525. }
  526. $result = $this->builtin->filesize($this->path);
  527. if ($result === false) {
  528. throw new IOException("Error while getting the size of " . $this->path);
  529. }
  530. return $result;
  531. }
  532. /**
  533. * Retrieves the parent directory of a file or directory path.
  534. *
  535. * @return self The parent directory of the specified path.
  536. */
  537. public function parent(): self
  538. {
  539. // TODO: check on special cases
  540. // TODO: add the levels argument?
  541. return $this->cast(
  542. $this->builtin->dirname($this->path)
  543. );
  544. }
  545. /**
  546. * Alias for Path->parent() method
  547. *
  548. * @return self
  549. */
  550. public function dirname(): self
  551. {
  552. // TODO: add the levels argument?
  553. return $this->parent();
  554. }
  555. /**
  556. * List of this directory’s subdirectories.
  557. *
  558. * The elements of the list are Path objects.
  559. * This does not walk recursively into subdirectories (but see walkdirs()).
  560. *
  561. * Accepts parameters to iterdir().
  562. *
  563. * @return array
  564. * @throws FileNotFoundException
  565. */
  566. public function dirs(): array
  567. {
  568. if (!$this->builtin->is_dir($this->path)) {
  569. throw new FileNotFoundException("Directory does not exist: " . $this->path);
  570. }
  571. $dirs = [];
  572. foreach ($this->builtin->scandir($this->path) as $filename) {
  573. if ('.' === $filename) continue;
  574. if ('..' === $filename) continue;
  575. if ($this->builtin->is_dir(self::join($this->path, $filename))) {
  576. $dirs[] = $filename;
  577. }
  578. }
  579. return $dirs;
  580. }
  581. /**
  582. * Retrieves an array of files present in the directory.
  583. *
  584. * @return array An array of files present in the directory.
  585. * @throws FileNotFoundException If the directory specified in the path does not exist.
  586. */
  587. public function files(): array
  588. {
  589. if (!$this->builtin->is_dir($this->path)) {
  590. throw new FileNotFoundException("Directory does not exist: " . $this->path);
  591. }
  592. $files = [];
  593. foreach ($this->builtin->scandir($this->path) as $filename) {
  594. if ('.' === $filename) continue;
  595. if ('..' === $filename) continue;
  596. if ($this->builtin->is_file(self::join($this->path, $filename))) {
  597. $files[] = $filename;
  598. }
  599. }
  600. return $files;
  601. }
  602. public function fnmatch()
  603. {
  604. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.fnmatch
  605. }
  606. /**
  607. * Retrieves the content of a file.
  608. *
  609. * @return bool|string The content of the file as a string.
  610. * @throws FileNotFoundException|IOException
  611. */
  612. public function getContent(): bool|string
  613. {
  614. if (!$this->builtin->is_file($this->path)) {
  615. throw new FileNotFoundException("File does not exist : " . $this->path);
  616. }
  617. $text = $this->builtin->file_get_contents($this->path);
  618. if ($text === false) {
  619. throw new IOException("Error reading file {$this->path}");
  620. }
  621. return $text;
  622. }
  623. /**
  624. * Writes contents to a file.
  625. *
  626. * @param string $content The contents to be written to the file.
  627. * @return int
  628. * @throws FileNotFoundException
  629. * @throws IOException
  630. */
  631. public function putContent(string $content, bool $append = false): int
  632. {
  633. if (!$this->builtin->is_file($this->path)) {
  634. throw new FileNotFoundException("File does not exist : " . $this->path);
  635. }
  636. // TODO: review use-cases
  637. // TODO: complete the input types
  638. // TODO: add a condition on the creation of the file if not existing
  639. $result = $this->builtin->file_put_contents(
  640. $this->path,
  641. $content,
  642. $append ? FILE_APPEND : 0
  643. );
  644. if ($result === False) {
  645. throw new IOException("Error while putting content into $this->path");
  646. }
  647. return $result;
  648. }
  649. /**
  650. * @throws IOException
  651. * @throws FileNotFoundException
  652. */
  653. public function putLines(array $lines): int
  654. {
  655. return $this->putContent(implode(PHP_EOL, $lines));
  656. }
  657. /**
  658. * Retrieves the permissions of a file or directory.
  659. *
  660. * @return int The permissions of the file or directory in octal notation.
  661. * @throws FileNotFoundException
  662. * @throws IOException
  663. */
  664. public function getPermissions(): int
  665. {
  666. if (!$this->isFile()) {
  667. throw new FileNotFoundException("File or dir does not exist : " . $this->path);
  668. }
  669. $perms = $this->builtin->fileperms($this->path);
  670. if ($perms === false) {
  671. throw new IOException("Error while getting permissions on " . $this->path);
  672. }
  673. return (int)substr(sprintf('%o', $perms), -4);
  674. }
  675. // TODO: add some more user-friendly methods to get permissions (read, write, exec...)
  676. /**
  677. * Changes the permissions of a file or directory.
  678. *
  679. * @param int $permissions The new permissions to set. The value should be an octal number.
  680. * @throws FileNotFoundException
  681. * @throws IOException
  682. */
  683. public function setPermissions(int $permissions): void
  684. {
  685. if (!$this->isFile()) {
  686. throw new FileNotFoundException("File or dir does not exist : " . $this->path);
  687. }
  688. $this->builtin->clearstatcache(); // TODO: check for a better way of dealing with PHP cache
  689. $success = $this->builtin->chmod($this->path, $permissions);
  690. if ($success === false) {
  691. throw new IOException("Error while setting permissions on " . $this->path);
  692. }
  693. }
  694. /**
  695. * Changes ownership of the file.
  696. *
  697. * @param string $user The new owner username.
  698. * @param string $group The new owner group name.
  699. * @throws FileNotFoundException
  700. * @throws IOException
  701. */
  702. public function setOwner(string $user, string $group): void
  703. {
  704. if (!$this->isFile()) {
  705. throw new FileNotFoundException("File or dir does not exist : " . $this->path);
  706. }
  707. $this->builtin->clearstatcache(); // TODO: check for a better way of dealing with PHP cache
  708. $success =
  709. $this->builtin->chown($this->path, $user) &&
  710. $this->builtin->chgrp($this->path, $group);
  711. if ($success === false) {
  712. throw new IOException("Error while setting owner of " . $this->path);
  713. }
  714. }
  715. public function setATime()
  716. {
  717. // TODO: implement
  718. }
  719. public function setCTime()
  720. {
  721. // TODO: implement
  722. }
  723. public function setMTime()
  724. {
  725. // TODO: implement
  726. }
  727. public function setUTime()
  728. {
  729. // TODO: implement
  730. }
  731. /**
  732. * Checks if a file exists.
  733. *
  734. * @return bool Returns true if the file exists, false otherwise.
  735. */
  736. public function exists(): bool
  737. {
  738. return $this->builtin->file_exists($this->path);
  739. }
  740. public function samefile()
  741. {
  742. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.samefile
  743. }
  744. public function expand()
  745. {
  746. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.expand
  747. }
  748. public function expand_user()
  749. {
  750. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.expanduser
  751. }
  752. public function expand_vars()
  753. {
  754. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.expandvars
  755. }
  756. /**
  757. * Retrieves a list of files and directories that match a specified pattern.
  758. *
  759. * @param string $pattern The pattern to search for.
  760. * @return array A list of files and directories that match the pattern.
  761. * @throws FileNotFoundException
  762. * @throws IOException
  763. */
  764. public function glob(string $pattern): array
  765. {
  766. if (!$this->isDir()) {
  767. throw new FileNotFoundException("Dir does not exist : " . $this->path);
  768. }
  769. $pattern = self::join($this->path, $pattern);
  770. $result = $this->builtin->glob($pattern);
  771. if ($result === false) {
  772. throw new IOException("Error while getting blob on " . $this->path);
  773. }
  774. return array_map(
  775. function (string $s) { return new static($s); },
  776. $result
  777. );
  778. }
  779. public function remove()
  780. {
  781. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.remove
  782. }
  783. public function remove_p()
  784. {
  785. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.remove_p
  786. }
  787. /**
  788. * Removes a directory and its contents recursively.
  789. *
  790. * @throws FileNotFoundException
  791. * @throws IOException
  792. */
  793. public function rmdir(bool $recursive = false): void
  794. {
  795. if (!$this->isDir()) {
  796. throw new FileNotFoundException("{$this->path} is not a directory");
  797. }
  798. // TODO: maybe we could only rely on the recursive method?
  799. $result = $recursive ? $this->rrmdir() : $this->builtin->rmdir($this->path);
  800. if ($result === false) {
  801. throw new IOException("Error while removing directory : " . $this->path);
  802. }
  803. }
  804. public function rename()
  805. {
  806. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.rename
  807. }
  808. public function renames()
  809. {
  810. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.renames
  811. }
  812. public function read_hash()
  813. {
  814. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.read_hash
  815. }
  816. public function read_hexhash()
  817. {
  818. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.read_hexhash
  819. }
  820. public function read_md5()
  821. {
  822. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.read_md5
  823. }
  824. public function read_text()
  825. {
  826. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.read_text
  827. }
  828. public function readlink()
  829. {
  830. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.readlink
  831. }
  832. public function readlinkabs()
  833. {
  834. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.readlinkabs
  835. }
  836. /**
  837. * Opens a file in the specified mode.
  838. *
  839. * @param string $mode The mode in which to open the file. Defaults to 'r'.
  840. * @return resource|false Returns a file pointer resource on success, or false on failure.
  841. * @throws FileNotFoundException If the path does not refer to a file.
  842. * @throws IOException If the file fails to open.
  843. */
  844. public function open(string $mode = 'r'): mixed
  845. {
  846. if (!$this->isFile()) {
  847. throw new FileNotFoundException("{$this->path} is not a file");
  848. }
  849. $handle = $this->builtin->fopen($this->path, $mode);
  850. if ($handle === false) {
  851. throw new IOException("Failed opening file {$this->path}");
  852. }
  853. return $handle;
  854. }
  855. /**
  856. * Calls a callback with a file handle opened with the specified mode and closes the handle afterward.
  857. *
  858. * @param callable $callback The callback function to be called with the file handle.
  859. * @param string $mode The mode in which to open the file. Defaults to 'r'.
  860. * @throws Throwable If an exception is thrown within the callback function.
  861. */
  862. public function with(callable $callback, string $mode = 'r'): mixed
  863. {
  864. $handle = $this->open($mode);
  865. try {
  866. return $callback($handle);
  867. } finally {
  868. $closed = $this->builtin->fclose($handle);
  869. if (!$closed) {
  870. throw new IOException("Could not close the file stream : " .$this->path);
  871. }
  872. }
  873. }
  874. /**
  875. * Retrieves chunks of data from the file.
  876. *
  877. * @param int $chunk_size The size of each chunk in bytes. Defaults to 8192.
  878. * @return Generator Returns a generator that yields each chunk of data read from the file.
  879. * @throws FileNotFoundException
  880. * @throws IOException
  881. * @throws Throwable
  882. */
  883. public function chunks(int $chunk_size = 8192): Generator
  884. {
  885. $handle = $this->open('rb');
  886. try {
  887. while (!$this->builtin->feof($handle)) {
  888. yield $this->builtin->fread($handle, $chunk_size);
  889. }
  890. } finally {
  891. $closed = $this->builtin->fclose($handle);
  892. if (!$closed) {
  893. throw new IOException("Could not close the file stream : " .$this->path);
  894. }
  895. }
  896. }
  897. /**
  898. * Check whether this path is absolute.
  899. *
  900. * @return bool
  901. */
  902. public function isAbs(): bool
  903. {
  904. return str_starts_with($this->path, '/');
  905. }
  906. /**
  907. * > Alias for Path->setPermissions() method
  908. * Changes permissions of the file.
  909. *
  910. * @param int $mode The new permissions (octal).
  911. * @throws FileNotFoundException|IOException
  912. */
  913. public function chmod(int $mode): void
  914. {
  915. $this->setPermissions($mode);
  916. }
  917. /**
  918. * > Alias for Path->setOwner() method
  919. * Changes ownership of the file.
  920. *
  921. * @param string $user The new owner username.
  922. * @param string $group The new owner group name.
  923. * @throws FileNotFoundException|IOException
  924. */
  925. public function chown(string $user, string $group): void
  926. {
  927. $this->setOwner($user, $group);
  928. }
  929. /**
  930. * Changes the root directory of the current process to the specified directory.
  931. *
  932. * @throws IOException
  933. */
  934. public function chroot(): void
  935. {
  936. $success = $this->builtin->chroot($this->path);
  937. if (!$success) {
  938. throw new IOException("Error changing root directory to " . $this->path);
  939. }
  940. }
  941. /**
  942. * Checks if the file is a symbolic link.
  943. *
  944. * @return bool
  945. */
  946. public function isLink(): bool
  947. {
  948. return $this->builtin->is_link($this->path);
  949. }
  950. public function isMount()
  951. {
  952. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.ismount
  953. }
  954. protected function getDirectoryIterator(): \DirectoryIterator
  955. {
  956. // TODO: make it public?
  957. return new \DirectoryIterator($this->path);
  958. }
  959. /**
  960. * Iterate over the files in this directory.
  961. *
  962. * @return Generator
  963. * @throws FileNotFoundException if the path is not a directory.
  964. */
  965. public function iterDir(): Generator
  966. {
  967. if (!$this->isDir()) {
  968. throw new FileNotFoundException("{$this->path} is not a directory");
  969. }
  970. foreach ($this->getDirectoryIterator() as $fileInfo) {
  971. // TODO: use the DirectoryIterator everywhere else?
  972. if ($fileInfo->isDot()) {
  973. continue;
  974. }
  975. yield $fileInfo->getFilename();
  976. }
  977. }
  978. public function lines()
  979. {
  980. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.lines
  981. }
  982. /**
  983. * Create a hard link pointing to a path.
  984. *
  985. * @param string|Path $target
  986. * @throws FileExistsException
  987. * @throws FileNotFoundException
  988. * @throws IOException
  989. */
  990. public function link(string|self $target): void
  991. {
  992. // TODO: manage dirs and files here
  993. if (!$this->isFile()) {
  994. throw new FileNotFoundException("{$this->path} is not a file");
  995. }
  996. $target = $this->cast($target);
  997. if ($target->isFile()) {
  998. throw new FileExistsException($target . " already exist");
  999. }
  1000. $success = $this->builtin->link($this->path, (string)$target);
  1001. if ($success === false) {
  1002. throw new IOException("Error while creating the link from " . $this->path . " to " . $target);
  1003. }
  1004. }
  1005. /**
  1006. * Like stat(), but do not follow symbolic links.
  1007. *
  1008. * @return array
  1009. * @throws IOException
  1010. */
  1011. public function lstat(): array
  1012. {
  1013. $result = $this->builtin->lstat($this->path);
  1014. if ($result === false) {
  1015. throw new IOException("Error while getting lstat of " . $this->path);
  1016. }
  1017. return $result;
  1018. }
  1019. public function splitDrive()
  1020. {
  1021. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.splitdrive
  1022. }
  1023. public function stat() {
  1024. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.stat
  1025. }
  1026. public function symlink()
  1027. {
  1028. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.symlink
  1029. }
  1030. public function unlink()
  1031. {
  1032. // TODO: implement https://path.readthedocs.io/en/latest/api.html#path.Path.unlink
  1033. }
  1034. /**
  1035. * Returns the individual parts of this path.
  1036. * The eventual leading directory separator is kept.
  1037. *
  1038. * Ex:
  1039. *
  1040. * Path('/foo/bar/baz').parts()
  1041. * >>> '/', 'foo', 'bar', 'baz'
  1042. *
  1043. * @return array
  1044. */
  1045. public function parts(): array
  1046. {
  1047. $parts = [];
  1048. if (str_starts_with($this->path, DIRECTORY_SEPARATOR)) {
  1049. $parts[] = DIRECTORY_SEPARATOR;
  1050. }
  1051. $parts += explode(DIRECTORY_SEPARATOR, $this->path);
  1052. return $parts;
  1053. }
  1054. /**
  1055. * Compute a version of this path that is relative to another path.
  1056. *
  1057. * @param string|Path $basePath
  1058. * @return string
  1059. * @throws FileNotFoundException
  1060. * @throws IOException
  1061. */
  1062. public function getRelativePath(string|self $basePath): string
  1063. {
  1064. if (!$this->exists()) {
  1065. throw new FileNotFoundException("{$this->path} is not a file or directory");
  1066. }
  1067. $path = (string)$this->absPath();
  1068. $basePath = (string)$basePath;
  1069. $realBasePath = $this->builtin->realpath($basePath);
  1070. if ($realBasePath === false) {
  1071. throw new FileNotFoundException("$basePath does not exist or unable to get a real path");
  1072. }
  1073. $pathParts = explode(DIRECTORY_SEPARATOR, $path);
  1074. $baseParts = explode(DIRECTORY_SEPARATOR, $realBasePath);
  1075. while (count($pathParts) && count($baseParts) && ($pathParts[0] == $baseParts[0])) {
  1076. array_shift($pathParts);
  1077. array_shift($baseParts);
  1078. }
  1079. return str_repeat('..' . DIRECTORY_SEPARATOR, count($baseParts)) . implode(DIRECTORY_SEPARATOR, $pathParts);
  1080. }
  1081. }