PHP code example of phpdevcommunity / php-requestkit

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

    

phpdevcommunity / php-requestkit example snippets




use PhpDevCommunity\RequestKit\Schema\Schema;
use PhpDevCommunity\RequestKit\Type;

$userSchema = Schema::create([
    'username' => Type::string()->length(5, 20)->



use PhpDevCommunity\RequestKit\Exceptions\InvalidDataException;

// ... (Schema creation from step 1) ...

$requestData = [
    'username' => 'john_doe',
    'email' => '[email protected]',
    'age' => '30', // Can be string, will be cast to int
];

try {
    $validatedData = $userSchema->process($requestData);
    // Access validated data as an array-like object
    $username = $validatedData->get('username');
    $email = $validatedData->get('email');
    $age = $validatedData->get('age');

    // ... continue processing with validated data ...

    print_r($validatedData->toArray()); // Output validated data as array

} catch (InvalidDataException $e) {
    // Handle validation errors
    $errors = $e->getErrors();
    print_r($errors);
}



namespace MonApi\Controller;

use PhpDevCommunity\RequestKit\Schema\Schema;
use PhpDevCommunity\RequestKit\Type;
use PhpDevCommunity\RequestKit\Exceptions\InvalidDataException;

class UserController
{
    public function createUser(array $requestData)
    {
        $schema = Schema::create([
            'user' => Type::item([
                'username' => Type::string()->length(5, 20)->]);

        try {
            $validatedData = $schema->process($requestData);
            // Access validated data directly using dot notation
            $username = $validatedData->get('user.username');
            $email = $validatedData->get('user.email');
            $age = $validatedData->get('user.age');
            $roles = $validatedData->get('user.roles');
            $street = $validatedData->get('user.address.street');
            $city = $validatedData->get('user.address.city');

            // Process validated data (e.g., save to database)
            // ...
            return $validatedData; // Or return a JSON response
        } catch (InvalidDataException $e) {
            // Handle validation errors and return an appropriate error response
            http_response_code(400); // Bad Request
            return ['errors' => $e->getErrors()]; // Or return a JSON error response
        }
    }
}

// Usage example (assuming $requestData is the parsed request body)
$controller = new UserController();
$requestData = [
    'user' => [
        'username' => 'john_doe',
        'email' => '[email protected]',
        'age' => 30,
        'roles' => ['admin', 'user'],
        'address' => [
            'street' => 'Main Street',
            'city' => 'London',
        ],
    ],
];

$result = $controller->createUser($requestData);
print_r($result);



namespace MonApi\Controller;

use PhpDevCommunity\RequestKit\Schema\Schema;
use PhpDevCommunity\RequestKit\Type;
use PhpDevCommunity\RequestKit\Exceptions\InvalidDataException;

class ProductController
{
    public function getProduct(array $urlParams)
    {
        $schema = Schema::create([
            'id' => Type::int()->= $validatedParams->get('category');
            $page = $validatedParams->get('page'); // Will be 1 if 'page' is not in $urlParams

            // Retrieve product using validated parameters
            // ...
            return $validatedParams; // Or return a JSON response
        } catch (InvalidDataException $e) {
            // Handle validation errors
            http_response_code(400); // Bad Request
            return ['errors' => $e->getErrors()]; // Or return a JSON error response
        }
    }
}

// Usage example (assuming $urlParams is extracted from $_GET)
$controller = new ProductController();
$urlParams = ['id' => 123, 'category' => 'electronics'];
$result = $controller->getProduct($urlParams);
print_r($result);



namespace MonApi\Controller;

use PhpDevCommunity\RequestKit\Schema\Schema;
use PhpDevCommunity\RequestKit\Type;
use PhpDevCommunity\RequestKit\Exceptions\InvalidDataException;

class OrderController
{
    public function createOrders(array $ordersData)
    {
        $orderSchema = Type::item([
            'product_id' => Type::int()->rstProductId = $validatedOrders->get('orders.0.product_id');

            // Process validated orders
            // ...
            return $validatedOrders; // Or return a JSON response
        } catch (InvalidDataException $e) {
            // Handle validation errors
            http_response_code(400); // Bad Request
            return ['errors' => $e->getErrors()]; // Or return a JSON error response
        }
    }
}

// Usage example (assuming $ordersData is the parsed request body)
$controller = new OrderController();
$ordersData = [
    'orders' => [
        ['product_id' => 1, 'quantity' => 2],
        ['product_id' => 2, 'quantity' => 1],
        ['product_id' => 'invalid', 'quantity' => 0], // Will trigger validation errors
    ],
];

$result = $controller->createOrders($ordersData);
print_r($result); // Will print error array if validation fails


// ... inside a catch block for InvalidDataException ...

    } catch (InvalidDataException $e) {
        $errors = $e->getErrors();
        // $errors will be like:
        // [
        //    'orders.2.product_id' => 'Value must be an integer, got: string',
        //    'orders.2.quantity' => 'quantity must be at least 1',
        // ]
        return ['errors' => $errors];
    }


// ... inside a catch block for InvalidDataException ...

    } catch (InvalidDataException $e) {
        $productIdError = $e->getError('orders.2.product_id');
        if ($productIdError) {
            // $productIdError will be: 'Value must be an integer, got: string'
            return ['errors' => ['product_id_error' => $productIdError]]; // Structure error response as needed
        }
    }


// ... inside a catch block for InvalidDataException ...

    } catch (InvalidDataException $e) {
        $response = $e->toResponse();
        // $response will be like:
        // [
        //     'status' => 'error',
        //     'message' => 'Validation failed',
        //     'errors' => [ /* ... detailed errors from getErrors() ... */ ],
        // ]
        http_response_code($response['code']); // Set appropriate HTTP status code (e.g., 400)
        return $response;
    }


// ... inside a catch block for InvalidDataException ...

    } catch (InvalidDataException $e) {
        $message = $e->getMessage(); // General error message (e.g., "Validation failed")
        $code = $e->getCode();       //  Error code (you can customize this)

        return [
            'message' => $message,
            'code' => $code,
            'errors' => $e->getErrors(), // Detailed errors
        ];
    }


use PhpDevCommunity\RequestKit\Schema\Schema;
use PhpDevCommunity\RequestKit\Type;

$baseUserSchema = Schema::create([
    'name' => Type::string()->  'address' => Type::item([
        'city' => Type::string(),
        'zip' => Type::string()->length(5,10),
    ])
]);

// $extendedUserSchema now 
bash
composer