PHP code example of mcustiel / php-simple-request

1. Go to this page and download the library: Download mcustiel/php-simple-request 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/ */

    

mcustiel / php-simple-request example snippets


namespace Your\Namespace;

class PersonRequest 
{
    private $firstName;
    private $lastName;
    private $age;
    
    // getters and setters (setters are 

namespace Your\Namespace;
use Mcustiel\SimpleRequest\Annotation\Filter\Trim;
use Mcustiel\SimpleRequest\Annotation\Filter\UpperCase;

class PersonRequest 
{
    /**
     * @Trim
     */
    private $firstName;
    /**
     * @Trim
     * @UpperCase
     */
    private $lastName;
    private $age;
    
    // getters and setters (setters are 

namespace Your\Namespace;
use Mcustiel\SimpleRequest\Annotation\Filter\Trim;
use Mcustiel\SimpleRequest\Annotation\Filter\UpperCase;
use Mcustiel\SimpleRequest\Annotation\Validator\NotEmpty;
use Mcustiel\SimpleRequest\Annotation\Validator\MaxLength;
use Mcustiel\SimpleRequest\Annotation\Validator\Integer;

class PersonRequest 
{
    /**
     * @Trim
     * @NotEmpty
     */
    private $firstName;
    /**
     * @Trim
     * @UpperCase
     * @NotEmpty
     * @MaxLength(32)
     */
    private $lastName;
    /**
     * @Integer
     */
    private $age;
    
    // getters and setters (setters are 

use Mcustiel\SimpleRequest\RequestBuilder;
use Your\Namespace\PersonRequest;
use Mcustiel\SimpleRequest\Exceptions\InvalidRequestException;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Mcustiel\SimpleRequest\ParserGenerator;
use Mcustiel\SimpleRequest\Services\PhpReflectionService;
use Mcustiel\SimpleRequest\Services\DoctrineAnnotationService;
use Mcustiel\SimpleRequest\Strategies\AnnotationParserFactory;
use Mcustiel\SimpleRequest\FirstErrorRequestParser;

$requestBuilder = new RequestBuilder(
    new FilesystemAdapter(),
    new ParserGenerator(
        new DoctrineAnnotationService(),
        new AnnotationParserFactory(),
        new PhpReflectionService
    )
);

try {
    $personRequest = $requestBuilder->parseRequest($_POST, PersonRequest::class);
} catch (InvalidRequestException $e) {
    die("The request is invalid: " . $e->getMessage());
}
// Now you can use the validated and filtered personRequest to access the requestData.

$personRequest = $requestBuilder->parseRequest($_POST['person'], PersonRequest::class);

$request = file_get_contents('php://input');
$personRequest = $requestBuilder->parseRequest(json_decode($request, true), PersonRequest::class, , new FirstErrorRequestParser());

use Mcustiel\SimpleRequest\RequestBuilder;
use Your\Namespace\PersonRequest;
use Mcustiel\SimpleRequest\Exceptions\InvalidRequestException;
use Mcustiel\SimpleRequest\AllErrorsRequestParser;

$requestBuilder = new RequestBuilder();

try {
    $personRequest = $requestBuilder->parseRequest(
        $_POST, 
        PersonRequest::class,
        RequestBuilder::RETURN_ALL_ERRORS_IN_EXCEPTION
    );
} catch (InvalidRequestException $e) {
    $listOfErrors = $e->getErrors();   // This call returns only one error for the default behavior
}
// Now you can use the validated and filtered personRequest to access the requestData.

use Mcustiel\SimpleRequest\Annotation as SRA;

class CoupleRequest
{
    /**
     * @SRA\Validator\DateTimeFormat("Y-m-d")
     */
    private $togetherSince;
    /**
     * @SRA\ParseAs("\Your\Namespace\PersonRequest")
     */
    private $person1;
    /**
     * @SRA\ParseAs("\Your\Namespace\PersonRequest")
     */
    private $person2;
    
    //... Getters and setters (setters are 

$requestBuilder = new RequestBuilder(
    new AnyPsr6PoolAdapter(),
    new ParserGenerator(new AnnotationReader(), new AnnotationParserFactory())
);

/**
 * @Capitalize
 */
private $name;
// Will convert, for instance, mariano to Mariano.
/**
 * @Capitalize(true)
 */
private $fullName;
// Will convert, for instance, mariano custiel to Mariano Custiel.

/**
 * @CustomFilter(class="Vendor\\App\\MyFilters\\MyFilter", value="yourSpecifier")
 */
private $somethingHardToFilter;
// Will call Vendor\\App\\MyFilters\\MyFilter::filter($value) using "yourSpecifier".

/**
 * @DefaultValue("I am a default value")
 */
private $thisCanHaveADefault;

/**
 * @RegexReplace(pattern="/[^a-z0-9_]/i", replacement="_")
 */
private $onlyAlnumAndUnderscores;
// Will replace all non alphanumeric characters with underscores.

/**
 * @StringReplace(pattern="E", replacement="3")
 */
private $whyAmIChangingThis;
// Will replace all non E with 3.

/**
 * @AllOf({@Integer, @Minimum(0), @Maximum(100)})
 */
private $percentage;
// Will match an integer between 0 and 100.

/**
 * @Alpha
 */
private $onlyLetters;
// Will match a string containing only letters.

/**
 * @AlphaNumeric
 */
private $lettersAndNumbers;
// Will match a string containing only alphanumeric characters.

/**
 * @AnyOf({@Integer, @IPV6})
 */
private $integerOrIpv6;
// Will match an integer or an IPV6.

/**
 * @CustomValidator(class="Vendor\\App\\MyValidators\\MyValidator", value="yourSpecifier")
 */
private $somethingHardToCheck;
// Will call Vendor\\App\\MyValidators\\MyValidator::validate($value) using "yourSpecifier".

/**
 * @DateTime
 */
private $dateTime;
// Matches 2005-08-15T15:52:01+00:00

/**
 * @DateTimeFormat("M d, Y")
 */
private $dayOfBirth;
// Matches Oct 17, 1981

/**
 * @Email
 */
private $email;

/**
 * @Enum('value1', 'value2', 'value3')
 */
private $enum;
// Will match the strings value1, value2 or value3.

/**
 * @ExclusiveMaximum(0)
 */
private $negativeReals;
// Will match any number < 0.

/**
 * @ExclusiveMinimum(0)
 */
private $age;
// Will match any number > 0.

/**
 * @Hexa
 */
private $htmlColor;

/**
 * @Hostname
 */
private $responseDomain;

/**
 * @Float
 */
private $meters;
// accepts 1, 1.1, etc.

/**
 * @Float(true)
 */
private $meters;
// accepts 1.0, 1.1, etc.

/**
 * @Integer
 */
private $seconds;
// accepts 1, 2, -3, 0, etc.

/**
 * @Integer(false)
 */
private $majorVersion;
// accepts 1, 2.0, 3, etc.

/**
 * @IPV4
 */
private $ip;
// accepts 0.0.0.0, 255.255.255.255, etc.

/**
 * @IPV6
 */
private $ip;
// accepts ::A000:A000, A000::A000, A000::A000::, 2001:0000:3238:DFE1:63:0000:0000:FEFB, etc.

/**
 * @Items(items=@Integer, additionalItems=true)
 */
private $arrayOfInt;
// accepts Arrays of int of any size.

/**
 * @MacAddress
 */
private $mac;

/**
 * @Maximum(0)
 */
private $negativeRealsOrZero;
// Will match any number <= 0.

/**
 * @MaxItems(3)
 */
private $stoogesOnScreen;
// accepts [], ['curly'], ['curly', 'larry'] and ['curly', 'larry', 'moe'].

/**
 * @MaxLength(4)
 */
private $pin;
// accepts empty string, 1, 12, 123 and 1234.

/**
 * @MaxProperties(3)
 */
private $stoogesOnScreen;
// accepts (stdClass) [], (stdClass)['stooge1'->'curly'], (array)['stooge1'=>'curly', 'stooge2'=>'larry'], ['curly', 'larry', 'moe'].

/**
 * @Minimum(-273)
 */
private $temperatureInCelsius;
// Will match any number >= -273.

/**
 * @MinItems(2)
 */
private $players;
// accepts ['alice', 'bob'], ['a' => 'alice', 'b' => 'bob'], ['alice', 'bob', 'carol'].

/**
 * @MinLength(8)
 */
private $password;
// accepts 'password', 'password1', 'password1234' and all those very secure passwords.

/**
 * @MinProperties(2)
 */
private $players;
// accepts ['a' => 'alice', 'b' => 'bob'], ['alice', 'bob', 'carol'], stdclass(a->'alice', 'b'->'bob');

/**
 * @MultipleOf(2)
 */
private $evenNumber;
// accepts 8, 20, 100, etc.

/**
 * @Not(@MultipleOf(2))
 */
private $oddNumber;
// accepts 3, 15, 97, etc.

/**
 * @NotEmpty
 */
private $password;
// accepts 1, 'A', ['a'], etc.

/**
 * @NotNull
 */
private $mandatoryField;
// accepts '', 0, [], 1, 'A', ['a'], etc.

/**
 * @AnyOf(@Integer, @IPV6)
 */
private $integerOrIpv6;
// Will match an integer 'xor' an IPV6.

/**
 * @Items(properties={"name", @NotEmpty, "age", @Numeric}, additionalProperties=true)
 */
private $person;
// accepts Arrays or objects containing a not empty name property and a numeric age property. Can contain other properties (because additionalProperties is true)

/**
 * @RegExp("/[a-z]*/i")
 */
private $onlyAlpha;
// accepts '', 'a', 'A', 'ab', etc.

/**
 * @Required({"name", "age", "sex"})
 */
private $person;
// accepts ['name' => 'Alice', 'age' => 28, 'sex' => 'f', 'lastName' => 'Smith' ]

/**
 * @TwitterAccount
 */
private $twitterAccount;
// accepts '@user', '@user_name_1', etc.

/**
 * @Type("array")
 */
private $iCanOnlyBeAnArray;

/**
 * @UniqueItems
 */
private $noRepeatedValues;

/**
 * @Uri
 */
private $webpage;
// accepts 'localhost', 'www.server.com', 'http://www.webserver.com/page.php?t=1#anchor', etc
javascript
    "
        "mcustiel/php-simple-request": "*"
    }
javascript  
{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/mcustiel/php-simple-request"
        }
    ],
    "