PHP code example of webcore / validation-traits

1. Go to this page and download the library: Download webcore/validation-traits 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/ */

    

webcore / validation-traits example snippets


interface SingleValueObjectInterface
{
    /**
     * @return mixed
     */
    public function getValue();

    /**
     * Compare two SingleValueObject and tells whether they can be considered equal
     *
     * @param  SingleValueObjectInterface $object
     * @return bool
     */
    public function sameValueAs(SingleValueObjectInterface $object);
}

//example/Token.php

class Token implements SingleValueObjectInterface
{
    use SingleValueObjectTrait, NotEmptyTrait, Base64Trait, LengthTrait;

    protected function validation($value)
    {
        $this->validateNotEmpty($value);
        $this->validateBase64($value);
        $this->validateLength($value, 64);
    }
}

//example/example.php

//nette/tester
use Tester\Assert;

//valid value
$value = str_repeat('BeerNowThere0sATemporarySolution', 2);
$tokenFoo = new Token($value);
Assert::same("BeerNowThere0sATemporarySolutionBeerNowThere0sATemporarySolution", $tokenFoo->getValue());

//compare with another object of same value
$tokenBar = new Token("BeerNowThere0sATemporarySolutionBeerNowThere0sATemporarySolution");
$areSame = $tokenBar->sameValueAs($tokenFoo);
Assert::true($areSame);

//compare with another object of different value
$value = str_repeat('CraftBeerLovers0', 4); //
$tokenPub = new Token($value);
Assert::same("CraftBeerLovers0CraftBeerLovers0CraftBeerLovers0CraftBeerLovers0", $tokenPub->getValue());
$areSame = $tokenPub->sameValueAs($tokenBar);
Assert::false($areSame);

//invalid values
Assert::exception(
    function () {
        new Token(null);
    },
    InvalidArgumentException::class,
    "Token must be not empty"
);

Assert::exception(
    function () {
        new Token("InvalidTokenLength123456789");
    },
    InvalidArgumentException::class,
    "Token must be 64 characters long"
);

Assert::exception(
    function () {
        $value = str_repeat('?!@#$%^&', 8);
        new Token($value);
    },
    InvalidArgumentException::class,
    "Token must be valid base_64"
);