User.php 1.76 KB
<?php
namespace Tz\WordPress\Tools;
use WP_User;

class User {
    public $ID = 0;
    public $id = 0;

    protected $_wpuser;
    public $_metacache = Array(); // should be protected, need to figure out how invisible byte works with serialize and not using base64 encode

    public function __construct($id, $name = '', $blog_id = '') {
        $this->_wpuser = new WP_User($id, $name, $blog_id);
        $this->id = $this->ID = $this->_wpuser->id;
    }

    public function __get($key) {
        if (isset($this->_wpuser->{$key})) {
            return $this->_wpuser->{$key};
        }

        return $this->getMeta($key, true);
    }

    public function __set($key, $val) {
        $this->setMeta($key, $val);
    }

    public function __sleep() {
        return Array('_metacache', 'id', 'ID');
    }

    public function __wakeup() {
        $this->_wpuser = new WP_User(0);
    }

    public function __call($method, $params) {
        if (method_exists($this->_wpuser, $method)) {
            $this->setUser();
            return call_user_func_array(Array($this->_wpuser, $method), $params);
        }

        $classname = get_class($this->_wpuser);
        trigger_error("Call to undefined method {$class}::{$method}() in " . __FILE__ . " on line " . __LINE__, E_USER_ERROR);
    }

    protected function setUser() {
        if ($this->id != $this->_wpuser->id) {
            $this->_wpuser = new WP_User($this->id);
        }
    }

    public function getMeta($key, $single = true) {
        if (isset($this->_metacache[$key])) {
            return $this->_metacache[$key];
        }

        return get_user_meta($this->ID, $key, $single);
    }

    public function setMeta($key, $val) {
        update_user_meta($this->ID, $key, $val);
        unset($this->_metacache[$key]);
    }
}