xttribute/xttribute

XML to DTO, nicely!

1.1.1 2023-10-22 15:07 UTC

This package is auto-updated.

Last update: 2024-04-22 16:09:41 UTC


README

Tests & PHP CodeSniffer GitHub tag

xttribute will make dealing with XML a breeze! DOMDocuments can now be cast to classes with PHP 8.1 attributes!

Getting started

Requirements

  • PHP 8.1

Installation

Use composer to install

composer require xttribute/xttribute

Usage

Given the following XML

<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

We can translate this easily to the following class with some attributes!

use Xttribute\Xttribute\Castables\Str;

class Note 
{
    public function __construct(
        #[Str('/note/to')]
        public readonly string $to,
        #[Str('/note/from')]
        public readonly string $from,
        #[Str('/note/heading')]
        public readonly string $heading,
        #[Str('/note/body')]
        public readonly string $body,
    ) {
    }
}

Then we can run it through our DomDocumentCaster and get our hydrated object!

use Xttribute\Xttribute\DOMDocumentCaster;

// populate $source here with however you're receiving your XML

$doc = new DOMDocument();
$doc->loadXML($source);

$caster = new DOMDocumentCaster();
$note = $caster->cast($doc, Note::class);

// Work with $note hydrated DTO...

Other ways of using this package can be found in our examples.

Contributing

Pull requests are welcome! For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

Testing

composer test

License

MIT