Kontakt - Datenschutz

Subversion

<?php
/**
 * Link model
 *
 * @category  YD
 * @package   Web
 * @author    Sven Drieling <sd@sven-drieling.de>
 * @copyright 2013-2014 Sven Drieling
 * @license   http://opensource.org/licenses/mit-license.php MIT license
 * @version   0.1.0alpha1
 */

namespace YD\Web\Links;

require_once __DIR__ . '/helperFunctions.php';


/**
 *
 **/
class Link {
    private $keys    = ['id', 'created', 'title', 'uri', 'description'];
    private $values  = [];
    private $escapeCallback = null;

    public $messages = [];


    function __construct($args = []) {
        foreach($this->keys as $key) {
            $this->values[$key] = '';
            if(isset($args[$key])) {
                $this->$key = trim($args[$key]); // TODO Remove trim()?
            }
        }
    }


    public function setEscapeCallback($callback) {
        $this->escapeCallback = $callback;
    }


    public function validate() {
        $this->messages = [];


        if(!\preg_match('/^(\d+|)$/', $this->id)) { // TODO Force integer
            $this->messages[] = 'id is not valid.';
        }

        if('' === $this->title) {
            $this->messages[] = 'title required.';
        }

        if(\strlen($this->title) > 150) {
            $this->messages[] = 'title is too long.';
        }

        if('' === $this->uri) {
            $this->messages[] = 'uri required.';
        }

        if(\strlen($this->uri) > 512) {
            $this->messages[] = 'uri is too long.';
        }

        if(false === \filter_var($this->uri, FILTER_VALIDATE_URL)) {
            $this->messages[] = 'uri is not valid.';
        }


        return !(count($this->messages) > 0);
    }


    public function __get($name) {
        $escape = false;
        if('§' === \substr($name, 0, 2)) { // info Requires UTF-8
            $escape = true;
            $name   = \substr($name, 2);
        }

        if(isset($this->values[$name])) {
            $value = $this->values[$name];
            if($escape) {
                if(is_null($this->escapeCallback)) {
                    $value = e($value);
                } else {
                    $closure = $this->escapeCallback;
                    $value = $closure($value);
                }
            }


            return $value;
        }

        throw new \Exception("'$name' does not exists.");
    }


    public function __set($name, $value) {
        // TODO Errror handling for unknown keys
        if(\in_array($name, $this->keys)) {
            // TODO Improve
            if('description' === $name) {
                $value = \preg_replace("(\r\n|\r)", "\n", $value);
            }

            $this->values[$name] = $value;
        }
    }
}
?>