Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to customize default messages #80

Closed
mauriciocarvalho01 opened this issue May 4, 2021 · 6 comments
Closed

How to customize default messages #80

mauriciocarvalho01 opened this issue May 4, 2021 · 6 comments

Comments

@mauriciocarvalho01
Copy link

Hi,
I'm using it for valid, but I want to customize the default messages.

Thanks.

@sorinsarca
Copy link
Member

Hi,
a good starting point is https://opis.io/json-schema/2.x/php-error-formatter.html#format-method
You can keep a map of keywords and messages.

Here is a simple example:

$kw_map = [
  'minimum' => 'Too low',
  'maximum' => 'Too high',
  // ... other keywords
];

$custom = function (ValidationError $error) use ($kw_map, $formatter) {
    $schema = $error->schema()->info();

    return [
            'my_custom_message' => $kw_map[$error->keyword()] ?? 'Unknown error';

            'keyword' => $error->keyword(),
            'args' => $error->args(),
            'message' => $error->message(),
            'formattedMessage' => $formatter->formatErrorMessage($error),
    ];
};

$errors = $formatter->format($error, false, $custom);

However, we prepare v2.2.0 and we'll add an easy way to format errors directly from schema.

@sorinsarca
Copy link
Member

Correction: we already added support to format error messages directly from schema, we just have to write the docs :)

@mauriciocarvalho01
Copy link
Author

mauriciocarvalho01 commented May 4, 2021

Thanks,

I came to this result, but it still does not work

"numero_rps": {
	"type": "string",
	"minLength": 1,
	"maxLength": 15,
	"pattern": "[0-9]$",
	"$errors": {
		"maxLength": "O tamanho deve ser maior que 1",
		"minLength": "O tamanho deve ser menor que que 15",
		"pattern": "O padrão é números de 0 a 9"
	}
}

Where am I going wrong?

@mauriciocarvalho01
Copy link
Author

mauriciocarvalho01 commented May 4, 2021

{
	"type": "object",
	"properties": {
		"app_secret": {
			"type": "string"
		},
		"app_key": {
			"type": "string"
		},
		"param": {
			"type": "object",
			"properties": {
				"data_emissao": {
					"type": "string",
					"format": "date-time"
				},
				"status": {
					"type": "string",
					"pattern": "[1-2-]+$"
				},
				"numero_rps": {
					"type": "string",
					"minLength": 1,
					"maxLength": 15,
					"pattern": "[0-9]$", 
					"$errors": { // No work
						"maxLength": "O tamanho deve ser maior que 1",
						"minLength": "O tamanho deve ser menor que que 15",
						"pattern": "O padrão é números de 0 a 9"
					  }
				},
				"prestador": {
					"type": "object",
					"properties": {
						"cnpj": {
							"type": "string",
							"minLength": 11,
							"maxLength": 14,
							"pattern": "[0-9]{14}$"
						},
						"inscricao_municipal": {
							"type": "string",
							"minLength": 1,
							"maxLength": 15,
							"pattern": "[0-9]$"
						},
						"codigo_municipio": {
							"type": "string",
							"pattern": "[0-9]{7}$"
						}
					},
					"required": [
						"cnpj",
						"inscricao_municipal",
						"codigo_municipio"
					]
				},
				"tomador": {
					"type": "object",
					"properties": {
						"cpf": {
							"type": [
								"string",
								"null"
							],
							"pattern": "[0-9]{11}$"
						},
						"cnpj": {
							"type": [
								"string",
								"null"
							],
							"minLength": 11,
							"maxLength": 14,
							"pattern": "[0-9]{14}$"
						},
						"razao_social": {
							"type": "string",
							"minLength": 1,
							"maxLength": 115
						},
						"inscricao_municipal": {
							"type": [
								"string",
								"null"
							],
							"minLength": 1,
							"maxLength": 15
						},
						"endereco": {
							"type": [
								"object",
								"null"
							],
							"properties": {
								"cidade": {
									"type": "string",
									"minLength": 1,
									"maxLength": 125
								},
								"numero": {
									"type": "string",
									"minLength": 1,
									"maxLength": 10
								},
								"complemento": {
									"type": [
										"string",
										"null"
									],
									"minLength": 1,
									"maxLength": 60
								},
								"bairro": {
									"type": "string",
									"minLength": 1,
									"maxLength": 60
								},
								"codigo_municipio": {
									"type": "string",
									"pattern": "[0-9]{7}$"
								},
								"uf": {
									"type": "string",
									"maxLength": 2
								},
								"cep": {
									"type": "string",
									"pattern": "^[0-9]{8}$"
								}
							},
							"required": [
								"cidade",
								"numero",
								"bairro",
								"codigo_municipio",
								"uf",
								"cep"
							]
						}
					},
					"required": [
						"razao_social"
					]
				},
				"servico": {
					"type": "object",
					"properties": {
						"item_lista_servico": {
							"type": "string",
							"minLength": 1,
							"maxLength": 5
						},
						"codigo_tributacao_municipio": {
							"type": "string",
							"minLength": 1,
							"maxLength": 20
						},
						"discriminacao": {
							"type": "string",
							"minLength": 1,
							"maxLength": 2000
						},
						"codigo_municipio": {
							"type": "string",
							"pattern": "[0-9]{7}$"
						},
						"valores": {
							"type": "object",
							"properties": {
								"valor_servicos": {
									"type": "number"
								},
								"valor_deducoes": {
									"type": [
										"number",
										"null"
									]
								},
								"valor_pis": {
									"type": [
										"number",
										"null"
									]
								},
								"valor_cofins": {
									"type": [
										"number",
										"null"
									]
								},
								"valor_inss": {
									"type": [
										"number",
										"null"
									]
								},
								"valor_ir": {
									"type": [
										"number",
										"null"
									]
								},
								"valor_csll": {
									"type": [
										"number",
										"null"
									]
								},
								"iss_retido": {
									"type": "integer",
									"maximum": 2
								},
								"valor_iss": {
									"type": [
										"number",
										"null"
									]
								},
								"valor_iss_retido": {
									"type": [
										"number",
										"null"
									]
								},
								"outras_retencoes": {
									"type": [
										"number",
										"null"
									]
								},
								"basecalculo": {
									"type": [
										"number",
										"null"
									]
								},
								"aliquota": {
									"type": [
										"number",
										"null"
									]
								},
								"valor_liquido": {
									"type": [
										"number",
										"null"
									]
								},
								"desconto_incondicionado": {
									"type": [
										"number",
										"null"
									]
								},
								"desconto_condicionado": {
									"type": [
										"number",
										"null"
									]
								},
								"percentual_carga_tributaria": {
									"type": [
										"number",
										"null"
									]
								},
								"valor_carga_tributaria": {
									"type": [
										"number",
										"null"
									]
								}
							},
							"required": [
								"valor_servicos"
							]
						}
					},
					"required": [
						"item_lista_servico",
						"codigo_tributacao_municipio",
						"discriminacao",
						"valores"
					]
				},
				"intermediador_servico": {
					"type": [
						"object",
						"null"
					],
					"properties": {
						"razao_social": {
							"type": "string",
							"minLength": 1,
							"maxLength": 115
						},
						"cnpj": {
							"type": [
								"string",
								"null"
							],
							"minLength": 11,
							"maxLength": 14,
							"pattern": "[0-9]{14}$"
						},
						"cpf": {
							"type": [
								"string",
								"null"
							],
							"pattern": "[0-9]{11}$"
						},
						"inscricao_municipal": {
							"type": [
								"string",
								"null"
							],
							"minLength": 1,
							"maxLength": 15
						}
					},
					"required": [
						"razao_social"
					]
				},
				"construcao_civil": {
					"type": [
						"object",
						"null"
					],
					"properties": {
						"codigo_obra": {
							"type": "string",
							"minLength": 1,
							"maxLength": 15
						},
						"art": {
							"type": "string",
							"minLength": 1,
							"maxLength": 15
						}
					},
					"required": [
						"codigo_obra",
						"art"
					]
				}
			},
			"required": [
				"prestador",
				"data_emissao",
				"status",
				"tomador",
				"servico"
			]
		}
	},
	"required": [
		"param",
		"app_key",
		"app_secret"
	]
}

@sorinsarca
Copy link
Member

sorinsarca commented May 4, 2021

Here is an example on how to format messages from schema. Currently, we don't have docs for this, but it is pretty simple to use

Use the $error property (not $errors)

<?php

use Opis\JsonSchema\Validator;
use Opis\JsonSchema\Errors\ErrorFormatter;

$validator = new Validator();

$schema = <<<'JSON'
{
    "$error": {
        "required": {
            "name": "Please provide a name"
        }
    },
    "type": "object",
    "properties": {
        "name": {
            "$error": {
                "type": "Name should be a string",
                "minLength": "Name length must be at least {min} chars, found {length}",
                "maxLength": "Name is too long, only {max} chars are allowed, found {length}"
            },
            "type": "string",
            "minLength": 3,
            "maxLength": 5
        },
        "age": {
            "$error": {
                "minimum": "You must be at least {min} years long"
            },
            "type": "number",
            "minimum": 18
        }
    },
    "required": ["name"]
}
JSON;

$schema = json_decode($schema);

$formatter = new ErrorFormatter();

$result = $validator->validate((object)[], $schema);
print_r($formatter->format($result->error(), false));

/*
Array
(
    [/] => Please provide a name
)
*/

$result = $validator->validate((object)[
    'name' => 12 // not a string
], $schema);
print_r($formatter->format($result->error(), false));

/*
Array
(
    [/name] => Name should be a string
)
*/

$result = $validator->validate((object)[
    'name' => 'op' // too short
], $schema);
print_r($formatter->format($result->error(), false));

/*
Array
(
    [/name] => Name length must be at least 3 chars, found 2
)
*/

$result = $validator->validate((object)[
    'name' => 'opis/json-schema' // too long
], $schema);
print_r($formatter->format($result->error(), false));

/*
Array
(
    [/name] => Name is too long, only 5 chars are allowed, found 16
)
*/

$result = $validator->validate((object)[
    'name' => 'opis', // ok
    'age' => '18', // not a number (default error message)
], $schema);
print_r($formatter->format($result->error(), false));

/*
Array
(
    [/age] => The data (string) must match the type: number
)
*/

$result = $validator->validate((object)[
    'name' => 'opis', // ok
    'age' => 10, // too low
], $schema);
print_r($formatter->format($result->error(), false));

/*
Array
(
    [/age] => You must be at least 18 years long
)
*/

$result = $validator->validate((object)[
    'name' => 'opis', // ok
    'age' => 18, // ok
], $schema);

if (!$result->hasError()) {
    print_r("OK");
}

/*
OK
*/

@mauriciocarvalho01
Copy link
Author

mauriciocarvalho01 commented May 4, 2021

Ohh thanks, this worked!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants