Last active
September 25, 2017 21:23
-
-
Save naosim/4bd4aefe6f687b8a3fcb1b365519c933 to your computer and use it in GitHub Desktop.
File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function rstrpos ($haystack, $needle) { | |
$size = strlen ($haystack); | |
$pos = strpos(strrev($haystack), $needle); | |
if ($pos === false) { | |
return false; | |
} | |
return $size - $pos; | |
} | |
class File { | |
protected $value; // string | |
function __construct(string $value) { | |
$this->value = $value; | |
} | |
public function getValue(): string { | |
return $this->value; | |
} | |
// get 'name.txt' when value is './path/to/file/name.txt' | |
// get null when value is './path/to/file'. (not has dot in last segment name) | |
function get_file_name(): ?string { | |
$ary = explode('/', $this->value); | |
$result = $ary[count($ary) - 1]; | |
if(strpos($result, '.') === false) { | |
return null; | |
} | |
return $result; | |
} | |
// get './path/to/file' when value is './path/to/file/name.txt' | |
function get_dir_path(): string { | |
if($this->get_file_name() === null) { | |
return $this->getValue(); | |
} | |
$last_index = rstrpos($this->getValue(), '/'); | |
if($last_index === false || $last_index == 0) { | |
return $this->getValue(); | |
} | |
return substr($this->getValue(), 0, $last_index - 1); | |
} | |
function mkdirs_if_not_exists(): bool { | |
$p = $this->get_dir_path(); | |
if(file_exists($p)) { | |
return true; | |
} | |
return mkdir($p, 0777, true); | |
} | |
function save_text(string $text) { | |
if(file_exists($this->getValue())) { | |
unlink($this->getValue()); | |
} | |
$this->mkdirs_if_not_exists(); | |
file_put_contents($this->getValue(), $text); | |
chmod($this->getValue(), '0777'); | |
} | |
function exists() { | |
return file_exists($this->getValue()); | |
} | |
function load_text() { | |
return file_get_contents($this->getValue()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment