File.php

<?php

namespace Tlf\Stuff;

/**
 * An oop-style file acessor. it's neat, i guess ... but most the time i just need the built in php functions 
 */
class File {

    public $ext;
    public $path;
    public $content = false;

    public $baseDir;
    public $relPath;

    public function __construct($baseDir, $relPath, $content = false){
        $this->ext = pathinfo($relPath, PATHINFO_EXTENSION);
        $relPath = str_replace(['///','//'],'/',$relPath);
        $this->relPath = $relPath;
        $this->baseDir = $baseDir;
        $this->path = $baseDir.'/'.$relPath;
        $this->path = str_replace(['///','//'],'/',$this->path);
        $this->content = $content;
    }

    public function content(){
        if ($this->content===false){
            $this->content = file_get_contents($this->path);
        }

        return $this->content;
    }

    /**
     * Write content to disk
     *
     * @verb
     * @verbAbc()
     * @verbAbcDef(A, value)
     */
    public function write(){
        $path = $this->path;
        $baseDir = $this->baseDir;
        if (!is_dir($baseDir)){
            throw new \Exception("'$baseDir' is not a directory. Cannot write '$path'");
        }

        $rel = $this->relPath;
        $relDir = dirname($rel);
        $file = basename($rel);
        $parts = preg_split('/(\\|\/)/', $relDir);
        if ($parts[0]=='')array_shift($parts);

        $writeDir = $baseDir;
        $perms = fileperms($baseDir);
        $writeDir = $baseDir.'/'.$relDir;
        if (realpath($writeDir)==false){
            // echo "\nDir: $writeDir\n";
            @mkdir($writeDir, $perms, true);
        }
        file_put_contents($path, $this->content);
    }

    public function __toString(){
        return $this->content();
    }
}