pwwang/fs.php

PHP file system utilities

0.1.3 2016-01-18 08:40 UTC

This package is auto-updated.

Last update: 2024-04-11 13:32:24 UTC


README

A filesystem utilities for php.

Install

Install via Composer:

"require": {
    "pwwang/fs.php": "*"
}

or composer require pwwang/fs.php

Usage

use pw\fs\fs;
use pw\fs\file;
use pw\fs\dir;
use pw\fs\link;

// path sanitizer
$fs = new fs ("a///b//\\c//d");
// $fs->path() == 'a/b/c/d';
$fs = new fs ("./a/./b\\c\d");
// $fs->path() == 'a/b/c/d';
$fs = new fs ("./a/./b\\c\d/.");
// $fs->path() == 'a/b/c/d';
$fs = new fs ("./z/../a/./b\\c\d/.");
// $fs->path() == 'a/b/c/d';
$fs = new fs ("z/../a/./b\\c.txt\d/..");
// $fs->path() == 'a/b/c.txt';
// $fs->isAbs() === false;
// $fs->abs() === '/<path>/<path2>/.../a/b/c.txt';
// $fs->exists()
// $fs->dirname() === 'a/b';
// $fs->filename() === 'c.txt';
// $fs->basename() === 'c';
// $fs->ext() === 'txt'; // not dot
$link = new link ("a/b/c.link");
$link->create("a/b/c.txt");
$link->remove();

// file data
$contStr = '<?php return [1,2,3];';
$f1 = new file('a.php');  // or $f1 = (new fs('a.php'))->file();
$f2 = new file('a.txt');

$f1->contents($contStr);
$f2->contents($contStr);
// $f1->data() === [1,2,3];
// $f2->data() === $contStr;
// $f1->contents() === $contStr;
// $f2->contents() === $contStr;

$str = "1\n\n2\n3\n4\n\n5\n6\n7\n";
$f1->contents($str);
// $f1->lines() === [1,2,3,4,5,6,7];
// $f1->lines(1) === [2,3,4,5,6,7];
// $f1->lines(-2) === [1,2,3,4,5];
// $f1->lines(1, false) === ['', 2,3,4, '', 5,6,7, ''];

$dir1 = new dir(__DIR__ . DIRECTORY_SEPARATOR . "test1");
$subdir = $dir1->path("a/b/c");

$subdir = new dir($subdir);
$subdir->create();
// recursively created

$dir2 = new dir(__DIR__ . DIRECTORY_SEPARATOR . "test2");

$files = [
	$dir1->path("b/c/d/a.txt"),
	$dir1->path("e/c.txt"),
	$dir1->path("x/d/c.txt"),
	$dir1->path("x/d/p")
];
foreach ($files as $file) {
	$fs = new fs($file);
	$ext = $fs->ext();
	if ($ext) $fs->create();
	else $fs->dir()->create();
}
/* $dir1->contents(false) === [
	__DIR__ . DIRECTORY_SEPARATOR . "test1/a/b/c",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/a/b",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/a",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/b/c/d/a.txt",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/b/c/d",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/b/c",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/b",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/e/c.txt",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/e",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/x/d/c.txt",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/x/d/p",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/x/d",
	__DIR__ . DIRECTORY_SEPARATOR . "test1/x"
]; */

$dir1 -> rcopy2 ($dir2);

// (new fs($dir2->path("b/c/d/a.txt")))->exists() === true;

$dir1->rremove();
$dir2->rremove();
// $dir1->exists() === false;
// $dir2->exists() === false;