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

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

    protected $_wpuser;
    public $_metacache = []; // 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;
    }

    /**
     * @deprecated This method has caused MANY headaches with it's caching implementation.
     *             It bypasses the metacache (which gets updated when any meta field is set
     *             or retrieved), so causes the data used elsewhwere to be stale. BAD STUFF.
     * @param $key
     *
     * @return mixed
     */
    public function __get($key) {
        if (isset($this->_wpuser->{$key})) {
            return $this->_wpuser->{$key};
        }

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

    /**
     * Magically set a meta value and persist it to the store.
     *
     * @param $key
     * @param $val
     */
    public function __set($key, $val) {
        $this->setMeta($key, $val);
        // Update the meta cache
        $this->_metacache[$key] = $val;
    }

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

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

        // For some (stupid) reason, WP_User has these 2 meta_key fields in its global parameters...
        if (isset($this->_metacache['first_name'])) {
            $this->_wpuser->first_name = $this->_metacache['first_name'];
        }

        if (isset($this->_metacache['last_name'])) {
            $this->_wpuser->last_name = $this->_metacache['last_name'];
        }
    }

    public function __call($method, $params) {
        if (method_exists($this->_wpuser, $method)) {
            $this->setUser();
            return call_user_func_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]);
    }
}