Skip to content

Commit 078d10f

Browse files
committed
Add internal documentation
1 parent 452dd9a commit 078d10f

34 files changed

+844
-204
lines changed

README.md

Lines changed: 48 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,30 @@
1-
Json-Works
2-
==========
1+
# Json-Works
32

4-
A PHP library to create, edit, query and validate [JSON](https://www.json.org/).
3+
A PHP library to create, edit, query and validate [JSON][json].
54

6-
## Contents
7-
* [About](#about)
8-
* [Installation](#installation)
9-
* [Usage](#usage)
10-
* [License](#license)
5+
## Installation
6+
7+
Install the latest version with:
8+
9+
```bash
10+
$ composer require johnstevenson/json-works
11+
```
12+
13+
## Requirements
1114

12-
## About
15+
* PHP 7.4 minimum, although using the latest PHP version is highly recommended.
1316

14-
The library is intended to be used with nested json structures, or with json data that needs validation. Or in any situation where you would find it is easier to do something like this:
17+
## Usage
18+
19+
The library is intended to be used with complex json structures, or with json data that needs
20+
validation. Full usage information is available in the [documentation](docs/doc.md).
21+
22+
* [Overview](#overview)
23+
* [Validation](#validation)
24+
25+
### Overview
26+
Json-Works allows you to create, edit and query json data using [JSON Pointer][pointer] syntax. For
27+
example:
1528

1629
```php
1730
<?php
@@ -81,7 +94,23 @@ $document->deleteValue('/users/0');
8194

8295
### Validation
8396

84-
Json-Works includes an implementation of [JSON Schema][schema], version 4. This allows you to validate your data. The following example schema describes an array containing objects whose properties are all required and whose types are defined.
97+
Json-Works includes an implementation of [JSON Schema][schema], version 4, which allows you to
98+
validate json data. If the document contains invalid or missing value data, the validation will fail
99+
with the error in `$document->getError()`.
100+
101+
```php
102+
$document = new JohnStevenson\JsonWorks\Document();
103+
104+
$document->loadData('path/to/data.json');
105+
$document->loadScheme('path/to/schema.json');
106+
107+
if (!$document->validate()) {
108+
$error = $document->getError();
109+
}
110+
```
111+
112+
You can also validate data whilst building a document. The following example schema describes an
113+
array containing objects whose properties are all required and whose types are defined.
85114

86115
```json
87116
// schemas can be very simple
@@ -95,57 +124,26 @@ Json-Works includes an implementation of [JSON Schema][schema], version 4. This
95124
}
96125
}
97126
```
98-
Now when you try to add values, Json-Works will only do so if they are valid. So you have to check.
127+
128+
Now you can check if your data is valid:
99129

100130
```php
101131
$document->loadSchema($schema);
132+
$document->addValue('/-', ['firstName'=> 'Fred']);
102133

103-
$result = $document->addValue('/-', array('firstName'=> 'Fred', 'lastName' => 'Bloggs'));
104-
# true
105-
106-
$result = $document->addValue('/-', array('firstName'=> 'Fred', 'lastName' => 3));
107-
# false, lastName is not a string
108-
109-
$result = $document->addValue('/0', array('firstName'=> 'Fred'));
110-
# true, required values are not checked when we are building
111-
112-
# but are checked if we validate directly
113-
114-
$result = $document->validate();
115-
# false - required lastName is missing
116-
```
117-
118-
Without a schema, any value can be added anywhere.
119-
120-
<a name="Installation"></a>
121-
## Installation
122-
This package is available via [Composer][composer] as `johnstevenson/json-works`.
123-
Either run the following command in your project directory:
124-
125-
```
126-
composer require "johnstevenson/json-works=1.1.*"
127-
```
128-
129-
or add the requirement to your `composer.json` file:
130-
131-
```json
132-
{
133-
"require": {
134-
"johnstevenson/json-works": "1.1.*"
135-
}
134+
if (!$document->validate()) {
135+
$error = $document->getError();
136+
# "Property: '/0'. Error: is missing required property 'lastName'"
136137
}
137138
```
138139

139-
## Usage
140-
141-
Full usage [documentation][wiki] is available in the Wiki.
140+
Without a schema, any value can be added anywhere.
142141

143142
## License
144143

145144
Json-Works is licensed under the MIT License - see the `LICENSE` file for details.
146145

146+
[json]: https://www.rfc-editor.org/rfc/rfc8259
147147
[pointer]: https://www.rfc-editor.org/rfc/rfc6901
148148
[schema]: https://json-schema.org/
149149
[composer]: https://getcomposer.org
150-
[wiki]:https://github.com/johnstevenson/json-works/wiki/Home
151-

docs/doc.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Json-Works Documentation
2+
3+
Json-Works is a PHP library that allows you to create, edit, query and validate json data. The main
4+
foundation is the [Document class](document.md) and this section contains most of the information
5+
you need to start using the library.
6+
7+
* **[Document class](document.md)**
8+
* **[Formatter class](formatter.md)**
9+
* **[Loader class](formatter.md)**
10+
* **[Tokenizer class](formatter.md)**
11+
* **[Schema](schema.md)**
12+

docs/document.md

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
# Document
2+
3+
This class is the foundation of Json-Works, allowing you to load, create, query, edit, validate and
4+
output json data.
5+
6+
```php
7+
<?php
8+
namespace JohnStevenson\JsonWorks;
9+
10+
$document = new JohnStevenson\JsonWorks\Document();
11+
```
12+
13+
### Contents
14+
* [Overview](#overview)
15+
* [Json Build and Query](#json-build-and-query)
16+
* [Json Format](#json-format)
17+
* [Load Data](#load-data)
18+
* [Schema Validation](#schema-validation)
19+
20+
## Overview
21+
22+
### Paths and Pointers
23+
In order to reference an element in a json structure [JSON Pointer][pointer] syntax is used, which
24+
takes the form `/path/to/item`. Starting from the root of the data, each token in the path is
25+
prefixed with a `/` and points to a matching property-name for objects or a numeric index for
26+
arrays.
27+
28+
#### Forward-slashes in property names
29+
Because the forward-slash is used as a delimiter, it must be *encoded* if it appears in a property
30+
name. This is done by replacing it with `~1`. However, the tilde `~` may also be in the property
31+
name so this must be encoded first, by replacing it with `~0`.
32+
33+
Json-Works has methods for encoding/decoding paths in the [Tokenizer class][tokenizer].
34+
35+
#### Pointers to array values
36+
Note that a pointer to an array value is either a digit or sequence of digits (leading-zeros are not
37+
allowed), or the special-case `/-` token, which indicates that a value should be added to the end.
38+
39+
#### Pointers to empty property keys
40+
An empty `""` property key is valid (if somewhat unusual), and is represented by appending a `/`
41+
to the element. For example, `prop1/` references the number 10 in `{ "prop": { "": 10 } }`.
42+
43+
### Input data
44+
The data that you pass to methods that require it, or even the document itself, can either be an
45+
object, an array or a class with accessible non-static properties. The data is always copied, which
46+
will break any references and transform associative arrays to objects.
47+
48+
```php
49+
<?php
50+
# using an object ...
51+
$data = new stdClass();
52+
$data->firstName = 'Fred';
53+
$data->lastName = 'Bloggs';
54+
55+
# or using an array ...
56+
$data = ['firstName' => 'Fred', 'lastName' => 'Bloggs'];
57+
58+
# or using a class
59+
$data = new PersonClass('Fred', 'Bloggs');
60+
61+
# Add the data to an existing document ...
62+
$document->addValue($path, $data);
63+
64+
# or load it into a new document
65+
$document->loadData($data);
66+
67+
# $document->getData() returns an unreferenced stdClass object
68+
```
69+
70+
## Json Build and Query
71+
These methods all take at least one *$path* parameter (see
72+
[Paths And Pointers](#paths-and-pointers)) which can either be an array or a string.
73+
74+
* if it is an array, all items are treated as un-encoded and will be built into a single encoded
75+
path.
76+
* if it is a string, the value is treated as a single path that has already been encoded.
77+
78+
By using an array you can leave the encoding to Json-Works. In the example below we want to
79+
reference a nested element named `with/slash`, which obviously needs encoding.
80+
81+
```php
82+
<?php
83+
# we can encode it ourselves
84+
$tokenizer = new JohnStevenson\JsonWorks\Tokenizer()
85+
$path = $tokenizer::add('prop1', 'with/slash');
86+
87+
# or we can let the library do it
88+
$path = ['prop1', 'with/slash'];
89+
90+
$document->addValue($path, ...);
91+
```
92+
93+
All methods, except *getValue()*, return a bool to indicate if they were successful. In failure
94+
cases the error is in `$document->getError()`.
95+
96+
* [addValue()](#addvalue)
97+
* [copyValue()](#copyvalue)
98+
* [deleteValue()](#deletevalue)
99+
* [getValue()](#getvalue)
100+
* [hasValue()](#hasvalue)
101+
* [moveValue()](#movevalue)
102+
103+
104+
### addValue
105+
bool **addValue** ( mixed `$path`, mixed `$value` )
106+
107+
Returns true if the value is added to *$path*. If *$path* does not exists, Json-Works will try and
108+
create it, returning false if it is unable to do so with the error in `$document->getError()`.
109+
110+
If you wish to create objects that have array-like keys (digits or `-`) then you must create the
111+
base object first (or it must already exist) otherwise an array will be created or an error will
112+
occur.
113+
114+
```php
115+
<?php
116+
$document->addValue('prop1/0', 'myValue');
117+
# creates an array at prop1: [ "myValue" ]
118+
119+
$document->addValue('prop1', new \stdClass());
120+
$document->addValue('prop1/0', 'myValue');
121+
# creates an object at prop1: { "0": "myValue" }
122+
```
123+
124+
### copyValue
125+
bool **copyValue** ( mixed `$fromPath`, mixed `$toPath` )
126+
127+
Returns true if the value at *$fromPath* is copied to *$toPath*.
128+
129+
### deleteValue
130+
bool **deleteValue** ( mixed `$path` )
131+
132+
Returns true if the value at *$path* is deleted.
133+
134+
### getValue
135+
mixed **getValue** ( mixed `$path`, [ mixed `$default` = null ] )
136+
137+
Returns the value found at *$path*, or *$default*.
138+
139+
### hasValue
140+
bool **hasValue** ( mixed `$path`, mixed `&$value` )
141+
142+
Returns true if a value is found at *$path*, placing it in *$value*. Note that *$value* will be null
143+
if the function returns false.
144+
145+
### moveValue
146+
bool **moveValue** ( mixed `$fromPath`, mixed `$toPath` )
147+
148+
Returns true if the value at *$fromPath* is firstly copied to *$toPath*, then deleted from
149+
*$fromPath*.
150+
151+
*Back to:* [Contents](#contents)
152+
153+
## Json Format
154+
These methods format the document data. Json-Works does not call them automatically so their usage
155+
is left to the discretion of the implementation. The [Formatter class][formatter] is used
156+
internally.
157+
158+
* [tidy()](#tidy)
159+
* [toJson()](#tojson)
160+
161+
### tidy
162+
void **tidy** ( [ bool `$order` = false ] )
163+
164+
Removes empty objects and arrays from the data. If *$order* is true and a schema has been loaded the
165+
function re-orders the data using the schema content.
166+
167+
### toJson
168+
string **toJson** ( bool `$pretty` )
169+
170+
Returns a json-encoded string of `$document->data`. If *$pretty* is true, the output will be
171+
pretty-printed.
172+
173+
*Back to:* [Contents](#contents)
174+
175+
## Load Data
176+
These methods load either json data or a json schema. The [Loader class][loader] is used internally.
177+
Input can either be:
178+
179+
* a json string, requiring a successful call to _json_decode_.
180+
* a filename, requiring a successful call to _file_get_contents_ then _json_decode_.
181+
* a PHP data type specific to the method.
182+
183+
* [loadData()](#loaddata)
184+
* [loadSchema()](#loadschema)
185+
186+
### loadData
187+
void **loadData** ( mixed `$data` )
188+
189+
Accepts most PHP data types because a JSON text is not technically restricted to objects and arrays.
190+
On success the *$data* is copied and stored internally. It is accessible using
191+
`$document->getData()`. Throws a *RuntimeException* if the data is a resource.
192+
193+
### loadSchema
194+
void **loadSchema** ( mixed `$schema` )
195+
196+
Throws a `RuntimeException` if *$schema* does not result in a PHP object when processed.
197+
198+
*Back to:* [Contents](#contents)
199+
200+
## Schema Validation
201+
Json-Works provides an implementation of JSON Schema version 4. Please read [Schema][schema] for
202+
more details.
203+
204+
### validate
205+
bool **validate** ()
206+
207+
Returns the result of validating the data against the loaded schema. If false is returned the error
208+
will be in `$document->getError()`. If no schema has been loaded this method will always return
209+
true.
210+
211+
212+
```php
213+
$document->loadData('path/to/data.json');
214+
$document->loadScheme('path/to/schema.json');
215+
216+
if (!$document->validate()) {
217+
$error = $document->getError();
218+
}
219+
```
220+
221+
*Back to:* [Contents](#contents)
222+
223+
[pointer]: https://www.rfc-editor.org/rfc/rfc6901
224+
[formatter]: formatter.md
225+
[loader]: loader.md
226+
[schema]: schema.md
227+
[tokenizer]: tokenizer.md

0 commit comments

Comments
 (0)