AccessControls.php

<?php


namespace Phad\Test\Main;

/**
 * Used for testing code that's written in the documentation
 *
 */
class AccessControls extends \Phad\Tester {

    public function testFnAccessPrefix(){

        $phad = $this->phad();

        $this->test("Allow access for existing function that returns true");
        $can_do = $phad->can_access(['access'=>"fn:\\Phad\\Test\\Main\\fn_access_allowed"]);
        $this->compare(true, $can_do, true);

        $this->test("Block access for existing function that returns false");
        $can_do = $phad->can_access(['access'=>"fn:\\Phad\\Test\\Main\\fn_access_blocked"]);
        $this->compare(false, $can_do, true);


        $this->test("Exception for PHP function that returns non-bool truthy value");
        try {
            $this->catch('Exception')
                ->containing("MUST return strict boolean `true` or `false` when used as an access control");
            $can_do = $phad->can_access(['access'=>"fn:\\Phad\\Test\\Main\\fn_access_nonbool_true"]);
        } catch (\Exception $e){
            $this->throw($e);
        }


        $this->test("Exception for PHP function that returns non-bool falsy value");
        try {
            $this->catch('Exception')
                ->containing("MUST return strict boolean `true` or `false` when used as an access control");
            $can_do = $phad->can_access(['access'=>"fn:\\Phad\\Test\\Main\\fn_access_nonbool_false"]);
        } catch (\Exception $e){
            $this->throw($e);
        }


        $this->test("Exception for PHP function does not exist");
        try {
            $this->catch('Exception')
                ->containing('PHP function')
                ->containing("does not exist, so")
                ->containing("cannot be processed")
            ;
            $can_do = $phad->can_access(['access'=>"fn:\\Phad\\Test\\Main\\non_existant_function"]);
        } catch (\Exception $e){
            $this->throw($e);
        }

        $this->test("Access 'fn:phpfunctionname' works when implemented on an actual item template");
        $view = $this->item('Access/PHPFunction',[]).'';

        $this->str_contains($view, 'Allowed Content');
        $this->str_not_contains($view, 'Blocked Text');

    }

}


function fn_access_allowed(): bool {

    return true;
}

function fn_access_blocked(): bool {

    return false;
}

function fn_access_nonbool_true() {
    return 1;
}

function fn_access_nonbool_false() {
    return 0;
}