Files
CloudObjects-PHP-SDK/CloudObjects/SDK/CloudObject.php

111 lines
3.2 KiB
PHP

<?php
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
namespace CloudObjects\SDK;
use ML\IRI\IRI;
use ML\JsonLD\Node;
use CloudObjects\SDK\NodeReader;
use Webmozart\Assert\Assert;
/**
* A CloudObject encapsulates an object node for an object stored in CloudObjects Core
* with convenience methods to access properties.
*/
class CloudObject {
private $coid;
private $node;
private $reader;
public function __construct(IRI $coid, Node $node) {
Assert::eq((string)$coid, $node->getId(), "COID and Node ID must match.");
$this->coid = $coid;
$this->node = $node;
}
/**
* Specify a custom NodeReader to use for this CloudObject.
* If not set, a default NodeReader will be used.
*/
public function setReader(NodeReader $reader) : self {
$this->reader = $reader;
return $this;
}
private function getReader() : NodeReader {
if (!$this->reader) {
$this->reader = new NodeReader;
}
return $this->reader;
}
/**
* Get the COID of this object.
*/
public function getCOID() : IRI {
return $this->coid;
}
/**
* Get the raw object node.
*/
public function getObjectNode() : Node {
return $this->node;
}
/**
* Get the value of a property as a string.
* If the property has multiple values, only the first is returned.
*/
public function getString($property, string $default = null) : ?string {
return $this->getReader()->getFirstValueString($this->node, $property, $default);
}
/**
* Get the value of a property as an integer.
* If the property has multiple values, only the first is returned.
*/
public function getInt($property, int $default = null) : ?int {
return $this->getReader()->getFirstValueInt($this->node, $property, $default);
}
/**
* Get the value of a property as a float.
* If the property has multiple values, only the first is returned.
*/
public function getFloat($property, float $default = null) : ?float {
return $this->getReader()->getFirstValueFloat($this->node, $property, $default);
}
/**
* Get the value of a property as a boolean.
* If the property has multiple values, only the first is returned.
*/
public function getBool($property, bool $default = null) : ?bool {
return $this->getReader()->getFirstValueBool($this->node, $property, $default);
}
/**
* Get the value of a property as an IRI.
* If the property has multiple values, only the first is returned.
*/
public function getIRI($property, IRI $default = null) : ?IRI {
return $this->getReader()->getFirstValueIRI($this->node, $property, $default);
}
/**
* Get the value of a property as a Node.
* If the property has multiple values, only the first is returned.
*/
public function getNode($property, Node $default = null) : ?Node {
return $this->getReader()->getFirstValueNode($this->node, $property, $default);
}
}