PHP code example of horat1us / yii2-header-environment

1. Go to this page and download the library: Download horat1us/yii2-header-environment library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

horat1us / yii2-header-environment example snippets




namespace App\Controllers;

use yii\web;
use Horat1us\HeaderEnvironment;

class SiteController extends web\Controller
{
    public function behaviors()
    {
        $behaviors = []; // Some your production behaviors
        if(YII_ENV_TEST) {
            $behaviors['environment'] = [
                'class' => HeaderEnvironment\Behavior::class,
                'header' => 'Set-Environment', // default
            ];
        } 
    }

    public function actionIndex()
    {
        $request = \Yii::$app->request;

        $salt = $request->post('salt');
        $sign = $request->post('sign');

        $secret = getenv('SECRET');

        \Yii::$app->response->statusCode = md5($salt . $secret) === $sign
            ? 200
            : 400;
    }
}



namespace App\Tests;

class ApiTest {
    public function testSignChecking(\ApiTester $I) {
        $secret = 'persist-secret';
        $salt = mt_rand();
        $sign = md5($salt . $secret);
        
        $I->haveHttpHeader('Set-Environment', json_encode([
            'SECRET' => $secret,
        ]));
        $I->sendPOST('/site/index', [
            'salt' => $salt,
            'sign' => $sign,
        ]);
        $I->seeResponseCodeIs(200);

        $I->haveHttpHeader('Set-Environment', json_encode([
            'SECRET' => null, // Delete environment
        ]));
        $I->sendPOST('/site/index', [
            'salt' => $salt,
            'sign' => $sign,
        ]);
        $I->seeResponseCodeIs(400);
    }
}