Skip to content

Data Handler

matteosister edited this page Dec 6, 2014 · 10 revisions

Next (Data Handler for doctrine) ►

The Data Handler is used simply to change the value of a property

PATCH /books/1

[
  {"op": "data", "property": "title", "value": "1984"},
  {"op": "data", "property": "author.first_name", "value": "George"},
  {"op": "data", "property": "author.last_name", "value": "Orwell"}
]

The DataHandler uses the property access symfony component to change the value of a property.

By default the component uses setters and direct property access to do its job. It also traverse an object graph. So for example you can pass "profile.firstName" on a user object to change the value of the firstName property of the related profile object. Or you can even traverse collections by passing something like "children[0].firstName"

You can configure the handler to also try magic methods by calling useMagicCall(true) on the data handler

See the data handler example for reference

use PatchManager\Request\Operations;
use PatchManager\OperationMatcher;
use PatchManager\Handler\DataHandler;
use PatchManager\PatchManager;

// Test subject
class Subject implements \PatchManager\Patchable
{
    private $a = 1;

    public function setA($a)
    {
        $this->a = $a;
    }

    public function getA()
    {
        return $this->a;
    }
}

// Here we create a patch manager instance
$operations = new Operations();
$operations->setRequestBody(
  '{"op": "data", "property": "a", "value": 2}'
);
$operationMatcher = new OperationMatcher($operations);
$dataHandler = new DataHandler();
$dataHandler->useMagicCall(false);
$operationMatcher->addHandler($dataHandler);
$pm = new PatchManager($operationMatcher);

// and we do the test
$subject = new Subject();
echo sprintf("value of 'a' property: %s\n", $subject->getA());
echo "Patch manager operation\n";
$pm->handle($subject);
echo sprintf("value of 'a' property: %s\n", $subject->getA());

The output is:

value of 'a' property: 1
Patch manager operation
value of 'a' property: 2

Next (Data Handler for doctrine) ►