PHP code example of jdesrosiers / silex-json-schema-provider

1. Go to this page and download the library: Download jdesrosiers/silex-json-schema-provider 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/ */

    

jdesrosiers / silex-json-schema-provider example snippets


$app->register(new JDesrosiers\Silex\Provider\JsonSchemaServiceProvider());

$schemaJson = <<<SCHEMA
{
    "$schema": "http://json-schema.org/draft-04/hyper-schema#",
    "type": "object",
    "properties": {
        "id": {
            "type": "string"
        }
    }
}
SCHEMA;
$app["json-schema.schema-store"]->add("/schema/foo", json_decode($schemaJson));
$schema = $app["json-schema.schema-store"]->get("/schema/foo");
$validation = $app["json-schema.validator"]->validate($data, $schema);

$app->get("/foo/{id}", function ($id) use ($app) {
    $app["json-schema.describedBy"] = "/schema/foo";
    return JsonResponse::create(array("id" => $id));
});

$app["json-schema.schema-store"]->add("/schema/foo", $app["schemaRepository"]->fetch("foo"));

$app->put("/foo/{id}", function (Request $request, $id) use ($app) {
    $data = json_decode($request->getContent());

    $schema = $app["json-schema.schema-store"]->get("/schema/foo");
    $validation = $app["json-schema.validator"]->validate($data, $schema);
    if (!$validation->valid) {
        $error = array("validationErrors" => $validation->errors);
        return JsonResponse::create($error, Response::HTTP_BAD_REQUEST);
    }

    $isCreated = !$app["fooRepository"]->contains($id);
    $app["fooRepository"]->save($id, $data);

    $app["json-schema.describedBy"] = "/schema/foo";
    return JsonResponse::create($data, $isCreated ? Response::HTTP_CREATED : Response::HTTP_OK);
});