<?php
/**
 * GoogleRecaptchaConstraintValidator
 *
 * @author Bertin van den Ham <b.vandenham@visualmedia.nl>
 */
namespace VisualM\FormBundle\Form\Constraint;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class GoogleRecaptchaConstraintValidator
 */
class GoogleRecaptchaConstraintValidator extends ConstraintValidator
{
	/**
	 * @var ContainerInterface
	 */
	private $container;

	public function __construct(ContainerInterface $container) {
		$this->container = $container;
	}

	/**
	 * {@inheritdoc}
	 */
	public function validate( $value, Constraint $constraint ) {

		if(null === $googleRecaptchaSecretKey = $this->container->getParameter('google_recaptcha_secret_key')) {
			throw new ParameterNotFoundException('google_recaptcha_secret_key');
		}

		$remoteip = '';
		$recaptcha_parameters = sprintf("secret=%s&response=%s&remoteip=%s", $googleRecaptchaSecretKey, $value, $remoteip );

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $recaptcha_parameters);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$server_output = curl_exec($ch);
		$recaptcha_response = json_decode($server_output);
		curl_close ($ch);

		if($recaptcha_response->success === false){
			$this->context->buildViolation($constraint->message)->atPath('root')->addViolation();
		}
	}
}