<?php

###############################################################################
#
# Автор (Author): Brigadir (forum.mydune.ru)
# Дата (Date): 30-01-2016
# Последнее обновление (Latest update): 31-01-2021
#
###############################################################################

class UserData
{
	private $_map;
	private $_index;
	private $_file;

	public function __construct($file = null)
	{
		$this->_map = array();
		$this->_index = 0;
		$this->load($file);
	}

	public function __get($name)
	{
		return
			isset($this->_map[$this->_index][$name])? $this->_map[$this->_index][$name] : null;
	}

	public function __set($name, $value)
	{
		if (is_null($value))
		{
			unset($this->_map[$this->_index][$name]);

			if (empty($this->_map[$this->_index]))
				unset($this->_map[$this->_index]);
		}
		else
			$this->_map[$this->_index][$name] = $value;
	}

	public function select($node_id)
	{
		$this->_index = $node_id;
	}

	public function load($file)
	{
		$this->_file = $file;

		if (!empty($file) && file_exists($file))
		{
			$str = file_get_contents($file);

			if (!empty($str))
				$this->_map = unserialize($str);
		}
		else
			$this->_map = array();
	}

	public function save($file = null)
	{
		return file_put_contents(empty($file)? $this->_file : $file, serialize($this->_map));
	}

	public function fill_attributes($attr_name, $attr_value)
	{
		foreach ($this->_map as $index => $attributes)
			foreach ($attributes as $name => $value)
				if ($name == $attr_name)
				{
					$this->_index = $index;
					$this->{$name} = $attr_value;
				}
	}
}
?>
