<?php
/*
	Resale is forbidden!
	Copyright © Alexander Sunvas*
	http://eleanor-cms.ru
	a@eleanor-cms.ru
	*Pseudonym
*/
class YaAuth
{
	protected
		/** @property string $token Полученный token от Яндекса */
		$token,
		/** @property int $created Время создания token-а, timestamp */
		$created,
		/** @property int $ttl Время жизни token-а в секундах */
		$ttl,
		/** @property array $config Переданный классу конфиг */
		$config;

	/**
	 * @param array $config
	 * @throws EE
	 */
	public function __construct(array$config)
	{
		if(!isset($config['user'],$config['password'],$config['id'],$config['secret']))
			throw new EE('Unable to create YaAuth object because of wrong confir',EE::DEV);
		$this->config=$config;
	}

	/**
	 * Получение токена от Яндекса
	 * @return string
	 * @throws EE
	 */
	public function GetToken()
	{
		if($this->token and $this->ttl>0 and time()<=($this->ttl+$this->created))
			return$this->token;

		$curl=curl_init('https://oauth.yandex.ru/token');

		curl_setopt_array($curl,array(
			CURLOPT_HEADER=>0,
			CURLOPT_CONNECTTIMEOUT=>1,
			CURLOPT_FRESH_CONNECT=>1,
			CURLOPT_RETURNTRANSFER=>1,
			CURLOPT_FORBID_REUSE=>1,
			CURLOPT_TIMEOUT=>4,
			CURLOPT_SSL_VERIFYPEER=>false,
			CURLOPT_POST=>true,
			CURLOPT_POSTFIELDS=>array(
				'grant_type'=>'password',
				'client_id'=>$this->config['id'],
				'client_secret'=>$this->config['secret'],
				'username'=>$this->config['user'],
				'password'=>$this->config['password'],
			),
		));

		$json=curl_exec($curl);
		$code=curl_getinfo($curl,CURLINFO_HTTP_CODE);

		curl_close($curl);

		if(!$json)
			throw new EE('Empty response',EE::UNIT);

		if($code!=200 and $code!=400)
			throw new EE('Request Status is '.$code,EE::ENV);

		$json=json_decode($json,true);

		if(!empty($result['error']))
			throw new EE($result['error'],EE::UNIT);

		if(!isset($json['access_token'],$json['expires_in']))
			throw new EE('EMPTY_TOKEN',EE::UNIT);

		$this->token=$json['access_token'];
		$this->ttl=(int)$json['expires_in'];
		$this->created=(int)time();

		return$this->token;
  }
}