···11# Contributing
2233-Contributions are welcome and will be fully credited.
33+Contributions are **welcome** and will be fully **credited**.
4455-Contributions are accepted via Pull Requests on [Github](https://github.com/social-dept/schema).
55+## Etiquette
6677-# Things you could do
88-If you want to contribute but do not know where to start, this list provides some starting points.
99-- Add license text
1010-- Remove rewriteRules.php
1111-- Set up TravisCI, StyleCI, ScrutinizerCI
1212-- Write a comprehensive ReadMe
77+This project is open source, and as such, the maintainers give their free time to build and maintain the source code held within. They make the code freely available in the hope that it will be of use to other developers. It would be extremely unfair for them to suffer abuse or anger for their hard work.
1381414-## Pull Requests
99+Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the world that developers are civilized and selfless people.
15101616-- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
1111+It's the duty of the maintainer to ensure that all submissions to the project are of sufficient quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
17121818-- **Document any change in behaviour** - Make sure the `readme.md` and any other relevant documentation are kept up-to-date.
1313+## Viability
19142020-- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.
1515+When requesting or submitting new features, first consider whether it might be useful to others. Open source projects are used by many developers, who may have entirely different needs to your own. Think about whether or not your feature is likely to be used by other users of the project.
1616+1717+## Procedure
1818+1919+### Before Filing an Issue
2020+2121+- Search existing issues to avoid duplicates
2222+- Check the [documentation](README.md) to ensure it's not a usage question
2323+- Provide a clear title and description
2424+- Include steps to reproduce the issue
2525+- Specify your environment (PHP version, Laravel version, Schema version)
2626+- Include relevant code samples and full error messages
2727+2828+### Before Submitting a Pull Request
2929+3030+- **Discuss non-trivial changes first** by opening an issue
3131+- **Fork the repository** and create a feature branch from `main`
3232+- **Follow all requirements** listed below
3333+- **Write tests** for your changes
3434+- **Update documentation** if behavior changes
3535+- **Run code style checks** with `vendor/bin/php-cs-fixer fix`
3636+- **Ensure all tests pass** with `vendor/bin/phpunit`
3737+- **Write clear commit messages** that explain what and why
3838+3939+## Requirements
4040+4141+- **[PSR-12 Coding Standard](https://www.php-fig.org/psr/psr-12/)** - Run `vendor/bin/php-cs-fixer fix` to automatically fix code style issues.
4242+4343+- **Add tests** - Your patch won't be accepted if it doesn't have tests. All tests must use [PHPUnit](https://phpunit.de/) with [Pest](https://pestphp.com/).
4444+4545+- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
4646+4747+- **Consider our release cycle** - We follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
21482249- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
23502424-- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
5151+- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
5252+5353+## Running Tests
25545555+```bash
5656+vendor/bin/phpunit
5757+```
5858+5959+Run specific test suites:
6060+6161+```bash
6262+# Unit tests only
6363+vendor/bin/phpunit --testsuite=unit
6464+6565+# Integration tests only
6666+vendor/bin/phpunit --testsuite=integration
6767+```
6868+6969+## Code Style
7070+7171+Schema follows PSR-12 coding standard. Run PHP CS Fixer before submitting:
7272+7373+```bash
7474+vendor/bin/php-cs-fixer fix
7575+```
26762777**Happy coding**!
+381-29
README.md
···11-# Schema
11+[](https://github.com/socialdept/atp-signals)
22+33+<h3 align="center">
44+ Parse, validate, and transform AT Protocol Lexicon schemas in Laravel.
55+</h3>
66+77+<p align="center">
88+ <br>
99+ <a href="https://packagist.org/packages/socialdept/atp-schema" title="Latest Version on Packagist"><img src="https://img.shields.io/packagist/v/socialdept/atp-schema.svg?style=flat-square"></a>
1010+ <a href="https://packagist.org/packages/socialdept/atp-schema" title="Total Downloads"><img src="https://img.shields.io/packagist/dt/socialdept/atp-schema.svg?style=flat-square"></a>
1111+ <a href="LICENSE" title="Software License"><img src="https://img.shields.io/github/license/socialdept/atp-schema?style=flat-square"></a>
1212+</p>
1313+1414+---
1515+1616+## What is Schema?
1717+1818+**Schema** is a Laravel package for working with AT Protocol Lexicon schemas. It provides comprehensive tools for parsing schema definitions, validating data against those schemas, handling file uploads (blobs), and transforming between raw data and domain models.
1919+2020+Think of it as your complete toolkit for building AT Protocol applications that need strict data validation and schema compliance.
2121+2222+## Why use Schema?
2323+2424+- **Complete Lexicon support** - All types, formats, and constraints from the AT Protocol spec
2525+- **Multiple validation modes** - STRICT, OPTIMISTIC, and LENIENT for different use cases
2626+- **Laravel integration** - Works seamlessly with Laravel's validation and storage systems
2727+- **Blob handling** - Built-in file upload validation and storage
2828+- **Model transformation** - Convert between arrays and domain objects
2929+- **Union types** - Full support for discriminated unions with `$type` fields
3030+- **Extensible** - Macros and hooks let you customize behavior
3131+- **Production ready** - 818 passing tests with comprehensive coverage
3232+3333+## Quick Example
3434+3535+```php
3636+use SocialDept\Schema\Data\LexiconDocument;
3737+use SocialDept\Schema\Validation\Validator;
3838+use SocialDept\Schema\Parser\SchemaLoader;
3939+4040+// Load a schema
4141+$schema = LexiconDocument::fromArray([
4242+ 'lexicon' => 1,
4343+ 'id' => 'app.bsky.feed.post',
4444+ 'defs' => [
4545+ 'main' => [
4646+ 'type' => 'record',
4747+ 'record' => [
4848+ 'type' => 'object',
4949+ 'required' => ['text', 'createdAt'],
5050+ 'properties' => [
5151+ 'text' => ['type' => 'string', 'maxLength' => 300],
5252+ 'createdAt' => ['type' => 'string', 'format' => 'datetime'],
5353+ ],
5454+ ],
5555+ ],
5656+ ],
5757+]);
25833-[![Latest Version on Packagist][ico-version]][link-packagist]
44-[![Total Downloads][ico-downloads]][link-downloads]
55-[![Build Status][ico-travis]][link-travis]
66-[![StyleCI][ico-styleci]][link-styleci]
5959+// Validate data
6060+$validator = new Validator(new SchemaLoader([]));
76188-This is where your description should go. Take a look at [contributing.md](CONTRIBUTING.md) to see a to do list.
6262+$data = [
6363+ 'text' => 'Hello, AT Protocol!',
6464+ 'createdAt' => '2024-01-01T12:00:00Z',
6565+];
6666+6767+if ($validator->validate($data, $schema)) {
6868+ // Data is valid!
6969+}
7070+7171+// Get Laravel-formatted errors
7272+$errors = $validator->validateWithErrors($invalidData, $schema);
7373+// ['text' => ['The text field exceeds maximum length.']]
7474+```
9751076## Installation
11771212-Via Composer
7878+```bash
7979+composer require socialdept/atp-schema
8080+```
8181+8282+The package will auto-register with Laravel. Optionally publish the config:
13831484```bash
1515-composer require social-dept/schema
8585+php artisan vendor:publish --tag=schema-config
8686+```
8787+8888+## Basic Usage
8989+9090+### Validation Modes
9191+9292+Choose the validation strictness that fits your use case:
9393+9494+```php
9595+use SocialDept\Schema\Validation\Validator;
9696+9797+// STRICT - Rejects unknown fields
9898+$validator->setMode(Validator::MODE_STRICT);
9999+100100+// OPTIMISTIC - Allows unknown fields (default)
101101+$validator->setMode(Validator::MODE_OPTIMISTIC);
102102+103103+// LENIENT - Skips constraint validation
104104+$validator->setMode(Validator::MODE_LENIENT);
16105```
171061818-## Usage
107107+### Handling Blobs
108108+109109+Upload and validate files with built-in constraints:
110110+111111+```php
112112+use SocialDept\Schema\Services\BlobHandler;
113113+114114+$blobHandler = new BlobHandler('local');
115115+116116+$blob = $blobHandler->store(request()->file('image'), [
117117+ 'accept' => ['image/*'],
118118+ 'maxSize' => 1024 * 1024 * 5, // 5MB
119119+]);
120120+121121+// Use in validated data
122122+$data = [
123123+ 'image' => $blob->toArray(),
124124+];
125125+```
126126+127127+### Model Transformation
128128+129129+Transform between raw arrays and domain objects:
130130+131131+```php
132132+use SocialDept\Schema\Services\ModelMapper;
133133+use SocialDept\Schema\Contracts\Transformer;
134134+135135+class Post
136136+{
137137+ public function __construct(
138138+ public string $text,
139139+ public string $createdAt
140140+ ) {}
141141+}
191422020-## Change log
143143+class PostTransformer implements Transformer
144144+{
145145+ public function fromArray(array $data): Post
146146+ {
147147+ return new Post(
148148+ text: $data['text'],
149149+ createdAt: $data['createdAt']
150150+ );
151151+ }
211522222-Please see the [changelog](changelog.md) for more information on what has changed recently.
153153+ public function toArray(mixed $model): array
154154+ {
155155+ return [
156156+ 'text' => $model->text,
157157+ 'createdAt' => $model->createdAt,
158158+ ];
159159+ }
160160+161161+ public function supports(string $type): bool
162162+ {
163163+ return $type === 'app.bsky.feed.post';
164164+ }
165165+}
166166+167167+// Register and use
168168+$mapper = new ModelMapper();
169169+$mapper->register('app.bsky.feed.post', new PostTransformer());
170170+171171+$post = $mapper->fromArray('app.bsky.feed.post', $data);
172172+$array = $mapper->toArray('app.bsky.feed.post', $post);
173173+```
174174+175175+### Union Types
176176+177177+Work with discriminated unions using the `$type` field:
178178+179179+```php
180180+use SocialDept\Schema\Services\UnionResolver;
181181+182182+$resolver = new UnionResolver();
183183+184184+$data = [
185185+ '$type' => 'app.bsky.embed.images',
186186+ 'images' => [/* ... */],
187187+];
188188+189189+$type = $resolver->extractType($data);
190190+// "app.bsky.embed.images"
191191+192192+$isValid = $resolver->validate($data, $unionDef);
193193+```
194194+195195+## Complete Workflow Example
196196+197197+Here's how to validate a post with an image upload:
198198+199199+```php
200200+use SocialDept\Schema\Data\LexiconDocument;
201201+use SocialDept\Schema\Validation\Validator;
202202+use SocialDept\Schema\Services\BlobHandler;
203203+204204+// Load schema
205205+$schema = LexiconDocument::fromArray([/* ... */]);
206206+207207+// Handle image upload
208208+$blobHandler = new BlobHandler('local');
209209+$blob = $blobHandler->store(request()->file('image'), [
210210+ 'accept' => ['image/*'],
211211+ 'maxSize' => 1024 * 1024 * 5,
212212+]);
213213+214214+// Create post data
215215+$postData = [
216216+ 'text' => 'Check out this photo!',
217217+ 'createdAt' => now()->toIso8601String(),
218218+ 'embed' => [
219219+ '$type' => 'app.bsky.embed.images',
220220+ 'images' => [
221221+ [
222222+ 'image' => $blob->toArray(),
223223+ 'alt' => 'A beautiful sunset',
224224+ ],
225225+ ],
226226+ ],
227227+];
228228+229229+// Validate
230230+$validator = new Validator(new SchemaLoader([]));
231231+232232+if ($validator->validate($postData, $schema)) {
233233+ // Store post...
234234+} else {
235235+ $errors = $validator->validateWithErrors($postData, $schema);
236236+ // Handle errors...
237237+}
238238+```
239239+240240+## Supported Types
241241+242242+Schema supports all AT Protocol Lexicon types:
243243+244244+- **Primitives** - `string`, `integer`, `boolean`, `bytes`
245245+- **Objects** - Nested objects with properties
246246+- **Arrays** - Sequential lists with item validation
247247+- **Blobs** - File uploads with mime type and size constraints
248248+- **Unions** - Discriminated unions with `$type` field
249249+- **Unknown** - Accept any value
250250+251251+## Supported Formats
252252+253253+Built-in validators for AT Protocol formats:
254254+255255+- `datetime` - ISO 8601 timestamps
256256+- `uri` - Valid URIs
257257+- `at-uri` - AT Protocol URIs
258258+- `did` - Decentralized identifiers
259259+- `nsid` - Namespaced identifiers
260260+- `cid` - Content identifiers
261261+262262+## Advanced Features
263263+264264+### Extension Hooks
265265+266266+Add custom logic at key points in the validation lifecycle:
267267+268268+```php
269269+use SocialDept\Schema\Support\ExtensionManager;
270270+271271+$extensions = new ExtensionManager();
272272+273273+$extensions->hook('before:validate', function ($data) {
274274+ $data['text'] = trim($data['text']);
275275+ return $data;
276276+});
277277+278278+$transformed = $extensions->filter('before:validate', $data);
279279+```
280280+281281+### Macros
282282+283283+Extend core services with custom methods:
284284+285285+```php
286286+use SocialDept\Schema\Services\ModelMapper;
287287+288288+ModelMapper::macro('validateAndTransform', function ($type, $data, $schema) {
289289+ if (!$this->validator->validate($data, $schema)) {
290290+ return null;
291291+ }
292292+ return $this->fromArray($type, $data);
293293+});
294294+295295+$mapper = new ModelMapper();
296296+$result = $mapper->validateAndTransform('app.bsky.feed.post', $data, $schema);
297297+```
298298+299299+## API Reference
300300+301301+### Core Classes
302302+303303+**LexiconDocument**
304304+```php
305305+LexiconDocument::fromArray(array $data): self
306306+LexiconDocument::fromJson(string $json): self
307307+$document->getNsid(): string
308308+$document->getVersion(): int
309309+$document->getDefinition(string $name = 'main'): array
310310+```
311311+312312+**Validator**
313313+```php
314314+$validator->validate(array $data, LexiconDocument $schema): bool
315315+$validator->validateWithErrors(array $data, LexiconDocument $schema): array
316316+$validator->setMode(string $mode): self
317317+```
318318+319319+**BlobHandler**
320320+```php
321321+$handler->store(UploadedFile $file, array $constraints = []): BlobReference
322322+$handler->storeFromString(string $content, string $mimeType): BlobReference
323323+$handler->get(string $ref): ?string
324324+$handler->delete(string $ref): bool
325325+$handler->exists(string $ref): bool
326326+```
327327+328328+**ModelMapper**
329329+```php
330330+$mapper->register(string $type, Transformer $transformer): self
331331+$mapper->fromArray(string $type, array $data): mixed
332332+$mapper->toArray(string $type, mixed $model): array
333333+$mapper->fromArrayMany(string $type, array $items): array
334334+```
335335+336336+**UnionResolver**
337337+```php
338338+$resolver->extractType(array $data): ?string
339339+$resolver->validate(array $data, array $definition): bool
340340+$resolver->getTypeDefinition(array $data, array $definition): ?LexiconDocument
341341+```
2334224343## Testing
25344345345+Run the test suite:
346346+26347```bash
2727-composer test
348348+vendor/bin/phpunit
28349```
293503030-## Contributing
351351+Run specific test categories:
352352+353353+```bash
354354+# Unit tests only
355355+vendor/bin/phpunit --testsuite=unit
313563232-Please see [contributing.md](CONTRIBUTING.md) for details and a todolist.
357357+# Integration tests only
358358+vendor/bin/phpunit --testsuite=integration
359359+```
333603434-## Security
361361+## Configuration
353623636-If you discover any security related issues, please email author@email.com instead of using the issue tracker.
363363+Customize behavior in `config/schema.php`:
364364+365365+```php
366366+return [
367367+ 'storage' => [
368368+ 'disk' => env('SCHEMA_STORAGE_DISK', 'local'),
369369+ ],
370370+371371+ 'validation' => [
372372+ 'mode' => env('SCHEMA_VALIDATION_MODE', 'optimistic'),
373373+ ],
374374+375375+ 'blob' => [
376376+ 'max_size' => env('SCHEMA_BLOB_MAX_SIZE', 1024 * 1024 * 10), // 10MB
377377+ ],
378378+];
379379+```
380380+381381+## Requirements
382382+383383+- PHP 8.2+
384384+- Laravel 11+
385385+386386+## Resources
387387+388388+- [AT Protocol Documentation](https://atproto.com/)
389389+- [Lexicon Specification](https://atproto.com/specs/lexicon)
390390+- [Bluesky API Docs](https://docs.bsky.app/)
391391+392392+## Support & Contributing
393393+394394+Found a bug or have a feature request? [Open an issue](https://github.com/socialdept/atp-schema/issues).
395395+396396+Want to contribute? We'd love your help! Check out the [contribution guidelines](CONTRIBUTING.md).
3739738398## Credits
393994040-- [Author Name][link-author]
4141-- [All Contributors][link-contributors]
400400+- [Miguel Batres](https://batres.co) - founder & lead maintainer
401401+- [All contributors](https://github.com/socialdept/atp-schema/graphs/contributors)
4240243403## License
444044545-MIT. Please see the [license file](LICENSE) for more information.
405405+Schema is open-source software licensed under the [MIT license](LICENSE).
464064747-[ico-version]: https://img.shields.io/packagist/v/social-dept/schema.svg?style=flat-square
4848-[ico-downloads]: https://img.shields.io/packagist/dt/social-dept/schema.svg?style=flat-square
4949-[ico-travis]: https://img.shields.io/travis/social-dept/schema/master.svg?style=flat-square
5050-[ico-styleci]: https://styleci.io/repos/12345678/shield
407407+---
514085252-[link-packagist]: https://packagist.org/packages/social-dept/schema
5353-[link-downloads]: https://packagist.org/packages/social-dept/schema
5454-[link-travis]: https://travis-ci.org/social-dept/schema
5555-[link-styleci]: https://styleci.io/repos/12345678
5656-[link-author]: https://github.com/social-dept
5757-[link-contributors]: ../../contributors
409409+**Built for the Federation** • By Social Dept.