/**
  * Sets the value at the specified index
  * checks if the value is an object of specified class
  *
  * @see ArrayObject::offsetSet()
  * @throws InvalidArgumentException if the given model does not fit (wrong type or id)
  */
 function offsetSet($index, $newval)
 {
     if (!is_null($index)) {
         $index = (int) $index;
     }
     if (!is_a($newval, $this->getClassName())) {
         throw new InvalidArgumentException('This collection only accepts objects of type: ' . $this->getClassName(), self::WRONG_OBJECT_TYPE);
     }
     if ($this->related_record && $this->relation_options['type'] === 'has_many') {
         $foreign_key_value = call_user_func($this->relation_options['assoc_func_params_func'], $this->related_record);
         call_user_func($this->relation_options['assoc_foreign_key_setter'], $newval, $foreign_key_value);
     }
     if ($newval->id !== null) {
         $exists = $this->find($newval->id);
         if ($exists) {
             throw new InvalidArgumentException('Element could not be appended, element with id: ' . $exists->id . ' is in the way', self::OBJECT_EXISTS);
         }
     }
     return parent::offsetSet($index, $newval);
 }