Exemple #1
0
 /**
  * Saves an object with the given parameters.
  * If the param['id'] field is filled out, then that object is loaded
  * and updated, otherwise a new object of $type is created
  *
  * @param array $object
  * @param string $type
  * @return The created object
  */
 public function saveObject($params, $type = '')
 {
     $oldObject = null;
     if (is_array($params)) {
         $this->typeManager->includeType(ucfirst($type));
         if (isset($params['id'])) {
             $object = $this->getById((int) $params['id'], $type);
         } else {
             $object = new $type();
             za()->inject($object);
         }
         /* @var $object MappedObject */
         if ($object instanceof MappedObject) {
             $object->bind($params);
         } else {
             throw new InvalidModelException(array("Class " . get_class($object) . " must subclass MappedObject to use saveObject"));
         }
         // Validate
         $modelValidator = new ModelValidator();
         if (!$modelValidator->isValid($object)) {
             throw new InvalidModelException($modelValidator->getMessages());
         }
     } else {
         $object = $params;
     }
     if ($object == null) {
         throw new Exception("Cannot save null object");
     }
     $refObj = new ReflectionObject($object);
     if ($refObj->hasProperty('updated')) {
         $object->updated = date('Y-m-d H:i:s', time());
     }
     if ($refObj->hasProperty('modifier')) {
         $object->modifier = za()->getUser()->getUsername();
     }
     if (get_class($object) == 'stdClass') {
         throw new Exception("Cannot save stdClass");
     }
     $success = false;
     $this->triggerObjectEvent($object, 'beforeSave');
     if ($object->id) {
         $success = $this->updateObject($object);
     } else {
         $success = $this->createObject($object);
     }
     $this->triggerObjectEvent($object, 'saved');
     if ($success) {
         if ($this->searchService != null) {
             $this->searchService->index($object);
         }
         return $object;
     }
     return null;
 }