<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private 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  2020 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace LifeStyle\Tools\CipheringBundle\Api\Ciphering\Configuration;

use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class EncryptionDetector
 *
 * @copyright  2020 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package LifeStyle\Tools\CipheringBundle\Api\Ciphering\Configuration
 */
class EncryptionDetector
{
    /**
     * @var RequestStack
     */
    private $requestStack;

    /**
     * @var Index
     */
    private $configuration;

    /**
     * EncryptionDetector constructor.
     * @param RequestStack $requestStack
     * @param Index $configuration
     */
    public function __construct(RequestStack $requestStack, Index $configuration)
    {
        $this->requestStack = $requestStack;
        $this->configuration = $configuration;
    }

    /**
     * @return bool
     */
    public function useOpenSsl()
    {
        return !function_exists('mcrypt_encrypt') || false !== $this->findOpenSslCypherNameIndex();
    }

    /**
     * @return string
     */
    public function getOpenSslCypherName()
    {
        $idx = (int)$this->findOpenSslCypherNameIndex();
        $cypherNames = $this->configuration->getOpenSslCipherNames();
        return isset($cypherNames[$idx]) ? $cypherNames[$idx] : $cypherNames[0];
    }

    /**
     * @return int|false
     */
    private function findOpenSslCypherNameIndex()
    {
        $request = $this->requestStack->getMasterRequest();
        $idx = $request->headers->get('X-SSL-ENCRYPT-IDX', false);
        return false === $idx ? $this->configuration->isOpenSslFallback() : (int)$idx;
    }
}
