<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

class WV42_UserCache {
	private static $pacCache = array();

	const CACHE_NAMESPACE = 'wv42.user';

	/**
	 * gets a reference to a pac user hopefully from cache
	 *
	 * @param int $userId
	 * @return pac_User
	 */
	public static function getPacUser($userId) {
		if (!empty(self::$pacCache[$userId])) return self::$pacCache[$userId];
		self::$pacCache[$userId] = sly_Core::cache()->get(self::CACHE_NAMESPACE, $userId);

		if (self::$pacCache[$userId] === null) {
			$user = new pac_User($userId);
			self::$pacCache[$userId] = $user;
		}

		return self::$pacCache[$userId];
	}

	public static function persist() {
		$cache = sly_Core::cache();

		foreach (self::$pacCache as $userId => $user) {
			$cache->set(self::CACHE_NAMESPACE, $userId, $user);
		}
	}

	public static function delete($userId) {
		unset(self::$pacCache[$userId]);
		sly_Core::cache()->delete(self::CACHE_NAMESPACE, $userId);
	}

	public static function flush() {
		sly_Core::cache()->flush(self::CACHE_NAMESPACE, true);
		self::$pacCache = array();
	}
}
