@param null|array|object $model   (optional)
@param array             $options (optional)

@throws \RuntimeException When manager is closed
172524
public function flush($model = null, array $options = array())
    {
        $this->errorIfClosed();
        $this->unitOfWork->commit($model, $options);
    }
133625
public function persist($model)
    {
        $class    = $this->manager->getClassMetadata(get_class($model));
        $managers = $class->getFieldManagerNames();
        $pool     = $this->manager->getPool();

        $managerName = $class->getManagerReferenceGenerator();
        $referenceModel = call_user_func(array($model, 'get' . ucfirst($managerName)));

        $pool->getManager($managerName)->persist($referenceModel);

        unset($managers[array_search($managerName, $managers)]);

        $this->models->attach($model, $managers);
    }
606182
function beforeSave( Model $Model, $options = array() ){
	  	if ( !array_key_exists('Media', $Model->belongsTo) ) {
		  	$Model->bindModel(
		        array('belongsTo' => array(
		                'Media' => array(
		                    'className' => 'Risto.Media'
		                )
		            )
		        )
		    );
	  	}

	    if( isset($Model->data[$Model->alias][$this->_form_field_name]) 
	    	&& isset( $Model->data[$Model->alias][$this->_form_field_name]['error'] )
	    	&& $Model->data[$Model->alias][$this->_form_field_name]['error'] == 0
	    	){
	      $data = array('Media' => $Model->data[$Model->alias][$this->_form_field_name]);
	      $data['Media']['file'] = file_get_contents($Model->data[$Model->alias][$this->_form_field_name]['tmp_name']);
	      $data['Media']['model'] = $Model->name;
	      $Model->Media->create();
	      if ( !$Model->Media->save($data)) {
	      		// error
	      		$Model->validationErrors[$this->_form_field_name] = $Model->Media->validationErrors;
	      		return false;
	      }
      	  $Model->data[$Model->alias][$this->_form_fk] = $Model->Media->id;
      	  
	    }

	    return true;
	  }
364157
public function setModel(\atk4\data\Model $model, $method = null, $args = [])
    {
        $this->runMethod($model, $method, $args);

        return $model;
    }
463260
protected function saveModel(Model $model, array $options = []) {
		if ($model->isInsertForced()) {
			unset($model->_id);
			$model->unforceInsert();
		}
		
		// Update
		if (isset($model->_id)) {
			$data = $model->getDataForUpdate();
			unset($data['_id']);

			$id = $this->normalizeId($model->_id);
			
			return $this->getAdapter()->update(
				$this->getTableName(),
				['_id'  => $id],
				['$set' => $data],
				$options
			);
		}
		
		// Insert
		return $this->getAdapter()->insert(
			$this->getTableName(),
			$model->getDataForInsert(),
			$options
		);
	}
1013009
public function execute($method, array $options = [], array $arguments = []) {
        $params = [];

        if (count($options) > 0) {
            $params['options'] = $options;
        }

        if (count($arguments) > 0) {
            $params['arguments'] = $arguments;
        }

        $result = $this->api->request(
            $method,
            $params
        );

        if (!array_key_exists('success', $result)) {
            throw new RuntimeException('Missing success status');
        }

        if (!is_bool($result['success']) || $result['success'] === false) {
            throw new RuntimeException('Command failed');
        }

        if (!array_key_exists('output', $result)) {
            throw new RuntimeException('Missing output');
        }

        if (!is_array($result['output'])) {
            throw new RuntimeException('Invalid output');
        }

        return $result['output'];
    }
850627
public function save(Domain $model): void
    {
        if (!$model->save()) {
            throw new \RuntimeException($this->i18n->t('setrun/sys', 'Saving error'));
        }
    }
1146008
public function setExtraModelValues(array $fields, &$model)
    {
        //make sure the relationships are loaded
        foreach ($fields as $name => $field) {
            if ($field->getOption('relationship')) {
                $this->setModelRelationship($model, $field);
            }

            //if this is a setter field, unset it
            if ($field->getOption('setter')) {
                $model->__unset($name);
            }
        }
    }
1257821
public function remove(DatagateAwareInterface $model, array $options = []) {
		if ($model->isEmpty()) {
			throw new Exceptions\OperationError('Model has no data');
		}
		
		if ($model instanceof Model) {
			return $this->removeModel($model, $options);
		}
		
		
		if ($model instanceof Collection) {
			return $this->removeCollection($model, $options);
		}
		
		throw new Exceptions\OperationError('Unknown instance of the "DatagateAwareInterface" was given: "' . get_class($model) . '"');
	}
510621
public function processForm($model)
	{
		try {
			$configManager = $this->container->get('asf_website.config.manager');
			
			// Check configuration alias (internal use)
			$isExists = $configManager->getRepository()->findOneBy(array('alias' => $model->getAlias()));
			if ( $isExists !== null ) {
				throw new \Exception($this->container->get('asf_layout.flash_message')->danger($this->container->get('translator')->trans('A website configuration already exists with alias "%name%".', array('%name%' => $model->getAlias()), 'asf_website')));
			}
			
			// Check default configuration
			$defaultExists = $configManager->getRepository()->findOneBy(array('isDefault' => true));
			if ( $defaultExists === null ) {
				$model->setIsDefault(true);
			} elseif ($model->getIsDefault() == true && $model->getId() != $defaultExists->getId() ) {
				throw new \Exception($this->container->get('asf_layout.flash_message')->danger($this->container->get('translator')->trans('A default website configuration already exists ("%name%").', array('%name%' => $defaultExists->getName()), 'asf_website')));
			}
			
			$model instanceof Config;
			foreach($model->getParameters() as $parameter ) {
				$parameter->setConfig($model);
			}
			
			$db_parameters = $this->container->get('asf_website.parameter.manager')->getRepository()->findBy(array('config' => $model));
			foreach($db_parameters as $db_parameter) {
				if ( !$model->getParameters()->contains($db_parameter) ) {
					$model->removeParameter($db_parameter);
					$this->container->get('asf_website.parameter.manager')->getEntityManager()->remove($db_parameter);
				}
			}
			
			return true;
			
		} catch (\Exception $e) {
			throw new \Exception(sprintf('An error occured : %s', $e->getMessage()));
		}
		
		return false;
	}
43543
public function revertModel($model)
    {
        if (!$model->is_destroy) {
            $model->destroy();
        }
        $this->pool[$model->core_name]->push($model);
    }
309276
public function bootstrapModel($model)
    {
        if (! property_exists($model, 'rules')) {
            throw new ModelSanityException('Missing rules property for model '.get_class($model));
        }

        if (! $model instanceof AdminModel) {
            throw new ModelSanityException('Model '.get_class($model).' must be instanceof '.AdminModel::class);
        }

        $imageFields = $model->getImageFields();

        if (! is_array($imageFields)) {
            throw new ModelSanityException('No Image fields defined in config for model '.get_class($model));
        }

        // Check for fields collisions
        foreach ($imageFields as $imageFieldName => $imageField) {
            $imageMetaFields = $model->getImageMetaFields($imageFieldName);
            foreach ($imageMetaFields as $metaFieldName => $options) {
            }
        }

        $model->setRetinaFactor(config('ignicms.images.retina_factor'));

        foreach ($imageFields as $fieldName => $field) {
            $model->prepareImageRules($model, 'rules', $fieldName, $field);
        }
    }
1172779
protected function resolvePendingOps($model)
    {
        $name = $model->getMeta()->getNSModelName();
        if (isset($this->_pendingOps[$name])) {
            $todoActions = $this->_pendingOps[$name];
            foreach ($todoActions as $todoAction) {
                list($callback, $kwargs) = $todoAction;
                $kwargs['relatedModel'] = $model;
                $callback($kwargs);
            }
            unset($this->_pendingOps[$name]);
        }
    }
49245
public function validate($model, $fields = [])
    {
        $context = $this->_context;

        $context->messages = [];

        if (!$rules = $model->rules()) {
            return;
        }

        $context->model = $model;

        if (is_string($fields)) {
            $fields = (array)preg_split('#[\s,]+#', $fields, -1, PREG_SPLIT_NO_EMPTY);
        }

        $templates = null;
        foreach ($fields ?: $model->getChangedFields() as $field) {
            if (!isset($rules[$field])) {
                continue;
            }
            $context->field = $field;

            foreach ((array)$rules[$field] as $k => $v) {
                if (is_int($k)) {
                    $name = $v;
                    $parameters = null;
                } else {
                    $name = $k;
                    $parameters = $v;
                }

                $value = $this->_validate($model->$field, $name, $parameters);
                if ($value === null) {
                    $templates = $this->_templates ?: $this->_loadTemplates();
                    $template = isset($templates[$name]) ? $templates[$name] : $templates['default'];
                    $this->appendMessage(new Message($template, $context->model, $context->field, $parameters));
                } else {
                    $model->$field = $value;
                }
            }
        }

        if ($context->messages) {
            throw new ValidateFailedException('validate failed: ' . json_encode($context->messages));
        }
    }
922990
public function onSave($model)
    {
        $apiRoles          = ApiRoles::firstOrNew(['role_id' => $model->id]);
        $apiRoles->enabled = (int) Input::get('enabled');
        try {
            $apiRoles->save();
        } catch (Exception $ex) {
            Log::emergency($ex);
            throw new Exception('Unable to save role.');
        }
    }
34990
public function insert($model, array $options = [])
    {
        $values = $this->convertValues->convertToMongoValues(get_values($model), []);

        $result = $this->collection->insertOne($values, $options);
        if (false == $result->isAcknowledged()) {
            throw new \LogicException('Operation is not acknowledged');
        }

        set_object_id($model, new ObjectID((string) $result->getInsertedId()));
        $this->changesCollector->register($model, $values);

        return $result;
    }
1041551
protected function checkCreatable($model)
    {
        $environment = $this->getEnvironment();
        $definition  = $this->getDataDefinition();

        // Check if table is closed but we are adding a new item.
        if (!($model->getId() || $definition->getBasicDefinition()->isCreatable())) {
            $message = 'DataContainer ' . $definition->getName() . ' is closed';
            $environment->getEventDispatcher()->dispatch(
                ContaoEvents::SYSTEM_LOG,
                new LogEvent($message, TL_ERROR, 'DC_General - edit()')
            );
            throw new DcGeneralRuntimeException($message);
        }
    }