Media types

Create a new json schema media (MIME) type

A custom media type is an object implementing \Opis\JsonSchema\IMediaType interface. The validate method receives two arguments and must return a boolean (true if the $data has the specified media type, false otherwise).

  • string $data - the data to check
  • string $type - the media type

use Opis\JsonSchema\IMediaType;

class MimeType implements IMediaType
    public function validate(string $data, string $type): bool {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        return $type == $finfo->buffer($data);

Using media types

Before using the contentMediaType keyword in your schemas, make sure to register them in a Opis\JsonSchema\IMediaTypeContainer object, and pass that object to Opis\JsonSchema\IValidator::setMediaType().

  • name: the name you will use in your schemas
  • the media type object that implements Opis\JsonSchema\IMediaType

use Opis\JsonSchema\{

// Create a new FormatContainer
$mediaTypes = new MediaTypeContainer();

// Our mime type checker
$mimeType = new MimeType();

// Register our mime types
$mediaTypes->add("text/html", $mimeType);
$mediaTypes->add("text/xml", $mimeType);

// Create a IValidator
$validator = new Validator();

// Set media types to be used by validator

// Validation ...

Here is an example that uses our media types

  "type": "string",
  "contentMediaType": "text/html"

This schema validates "<html></html>" but doesn’t validate "some string" (text/plain).

On this page