XeroPHP\Application::save PHP Method

save() public method

public save ( Object $object, boolean $replace_data = false ) : Response | null
$object XeroPHP\Remote\Object
$replace_data boolean
return XeroPHP\Remote\Response | null
    public function save(Remote\Object $object, $replace_data = false)
    {
        //Saves any properties that don't want to be included in the normal loop
        //(special saving endpoints)
        $this->savePropertiesDirectly($object);
        if (!$object->isDirty()) {
            return null;
        }
        $object->validate();
        //In this case it's new
        if ($object->hasGUID()) {
            $method = $object::supportsMethod(Request::METHOD_POST) ? Request::METHOD_POST : Request::METHOD_PUT;
            $uri = sprintf('%s/%s', $object::getResourceURI(), $object->getGUID());
        } else {
            $method = $object::supportsMethod(Request::METHOD_PUT) ? Request::METHOD_PUT : Request::METHOD_POST;
            $uri = $object::getResourceURI();
            //@todo, bump version so you must create objects with app context.
            $object->setApplication($this);
        }
        if (!$object::supportsMethod($method)) {
            throw new Exception(sprintf('%s doesn\'t support [%s] via the API', get_class($object), $method));
        }
        //Put in an array with the first level containing only the 'root node'.
        $data = [$object::getRootNodeName() => $object->toStringArray()];
        $url = new URL($this, $uri);
        $request = new Request($this, $url, $method);
        $request->setBody(Helpers::arrayToXML($data))->send();
        $response = $request->getResponse();
        if (false !== ($element = current($response->getElements()))) {
            $object->fromStringArray($element, $replace_data);
        }
        //Mark the object as clean since no exception was thrown
        $object->setClean();
        return $response;
    }

Usage Example

示例#1
0
 /**
  * Shorthand save an object if it is instantiated with app context.
  *
  * @return Response|null
  * @throws Exception
  */
 public function save()
 {
     if ($this->_application === null) {
         throw new Exception('->save() is only available on objects that have an injected application context.');
     }
     return $this->_application->save($this);
 }