polyfony-inc/polyfony

View on GitHub
Private/Polyfony/Form/Captcha.php

Summary

Maintainability
A
0 mins
Test Coverage
<?php

namespace Polyfony\Form;
use Gregwar\Captcha\CaptchaBuilder;
use \Polyfony\Config as Config;
use \Polyfony\Request as Request;
use \Polyfony\Store\Session as Session;
use \Polyfony\Hashs as Hashs;
use \Polyfony\Element as Element;
use \Polyfony\Response as Response;
use \Polyfony\Form as Form;


// This class is only a wrapper for Gregwar/Captcha 
class Captcha extends Integrity {

    const DEFAULT_LENGTH = 6;
    const DEFAULT_WIDTH = 150;
    const DEFAULT_HEIGHT = 40;
    const DEFAULT_MUST_FAIL_OCR_TEST = false;

    // the actual captcha object (Gregwar/Captcha)
    private $captcha = null;

    // this will instanciate a captcha
    public function __construct(
        int $length = self::DEFAULT_LENGTH, 
        int $width = self::DEFAULT_WIDTH,
        int $height = self::DEFAULT_HEIGHT,
        bool $must_fail_ocr_test = self::DEFAULT_MUST_FAIL_OCR_TEST
    ) {

        // instancing a captcha will disable browser and framework caching
        // as to prevent mismatching captcha
        Response::disableBrowserCache();
        Response::disableOutputCache();

        // a phrase will be generated by the builder, and will live in the PHP session
        $this->captcha = new CaptchaBuilder($length);

        // build it, with additional parameters (size, and OCR pre-testing)
        $must_fail_ocr_test ? 
            $this->captcha->buildAgainstOCR($width, $height) :
            $this->captcha->build($width, $height);

        // store it in the current session
        Integrity::putInSession(
            Config::get('form','captcha_name'), 
            (string) $this->getValue()
        );

    }

    // get the value of the captcha, for manual use
    public function getValue() :string {

        // return as is
        return $this->captcha->getPhrase();

    }

    public function __toString() {

        // an inline captcha image element
        return (string) new Element('img', [
            'src'    =>$this->captcha->inline(),
            'class'    =>Config::get('form','captcha_name')
        ]);

    }

    // this will produce an input field to type the captcha
    public static function input(array $attributes = []) :Element {
        
        return Form::input(Config::get('form','captcha_name'), null, $attributes);

    }

    // this will check, upon posting the form, that it is legitimate
    public static function enforce(bool $prevent_redirection = false) :void {
        // actually enforce using the inherited enforce method
        self::enforceFor(
            Config::get('form','captcha_name'), 
            [
                'missing'=>'Polyfony/Form/Captcha::enforce() missing Captcha',
                'invalid'=>'Polyfony/Form/Captcha::enforce() invalid Captcha'
            ], 
            $prevent_redirection
        );

    }
    
}

?>