<?php

/**
 * Twig extension to make AWS Instance-Id visible in templates
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\Tools\AWSBundle\Twig\Extension;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;

/**
 * Class AWS
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\Tools\AWSBundle\Twig\Extension
 */
class AWS extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
{
    const SERVICE_URL = 'http://169.254.169.254/latest/meta-data/instance-id';

    /**
     * Guzzle client
     *
     * @var ClientInterface
     */
    private $client;

    /**
     * AWS-Instance-Id
     *
     * @var string
     */
    private $awsInstanceId;

    /**
     * AWS constructor.
     */
    public function __construct()
    {
        $this->client = new Client();
    }

    /**
     * Get extension-name
     *
     * @return string
     */
    public function getName()
    {
        return 'sso-aws-extension';
    }

    /**
     * Get global variables
     *
     * @return array
     */
    public function getGlobals()
    {
        return array(
            'awsInstanceId' => $this->awsInstanceId()
        );
    }

    /**
     * Get aws instance id
     *
     * @return string
     */
    private function awsInstanceId()
    {
        // Detect AWS environment
        if (false === getenv('APP_LOGS')) {
            return '';
        }
        if (null === $this->awsInstanceId) {
            try {
                $this->awsInstanceId = (string)$this->client->get(static::SERVICE_URL)->getBody()->getContents();
            } catch (\Exception $exception) {
                $this->awsInstanceId = 'unknown';
            }
        }
        return $this->awsInstanceId;
    }
}
