Created
June 1, 2015 20:53
-
-
Save igor822/054192f8416c8e4756e3 to your computer and use it in GitHub Desktop.
Class 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 | |
namespace FileComponent; | |
/** | |
* Class File | |
* @package FileComponent | |
*/ | |
class File | |
{ | |
const READ_ONLY = 'r'; | |
const READ_WRITE = 'r+'; | |
const WRITE_ONLY_BEGIN_FILE = 'w'; | |
const READ_WRITE_BEGIN_FILE = 'w+'; | |
const WRITE_ONLY_END_FILE = 'a'; | |
const READ_WRITE_END_FILE = 'a+'; | |
const CREATE_TO_WRITE = 'x'; | |
const CREATE_TO_READ_WRITE = 'x+'; | |
private $name; | |
private $mode; | |
private $resource; | |
/** | |
* @param string $fileName | |
* @param string $mode | |
*/ | |
public function __construct($fileName, $mode = self::READ_ONLY) | |
{ | |
$this->name = $fileName; | |
$this->mode = $mode; | |
} | |
/** | |
* @throws \Exception | |
*/ | |
public function open() | |
{ | |
if ($this->exists()) { | |
$this->validateMode(); | |
} | |
$this->resource = fopen($this->name, $this->mode); | |
} | |
/** | |
* @param string $content | |
*/ | |
public function write($content) | |
{ | |
if (!$this->isOpen()) { | |
$this->open(); | |
} | |
fwrite($this->resource, $content); | |
} | |
public function writeFile($file, $content) | |
{ | |
} | |
public function close() | |
{ | |
fclose($this->resource); | |
} | |
/** | |
* @throws \Exception | |
* @return bool | |
*/ | |
public function validateMode() | |
{ | |
if ($this->mode == self::CREATE_TO_READ_WRITE || $this->mode == self::CREATE_TO_WRITE) { | |
throw new \Exception('This mode to open file is not allowed because the file is already created'); | |
} | |
return true; | |
} | |
/** | |
* @return bool | |
*/ | |
public function exists() | |
{ | |
return file_exists($this->name) ? true : false; | |
} | |
/** | |
* @return bool | |
*/ | |
public function isOpen() | |
{ | |
return !empty($this->resource) ? true : false; | |
} | |
public static function __callStatic($name, $arguments) | |
{ | |
static $instance = null; | |
if ($instance == null) { | |
$class = new static(); | |
} | |
return call_user_func_array([__CLASS__, $name], $arguments); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment