Create a new invalid model state.

@param ModelInterface  $model
@param string          $processName
@param string          $stepName
@param ViolationList   $violationList
@param null|ModelState $previous

@return ModelState
182660
public function newModelStateError(ModelInterface $model, $processName, $stepName, ViolationList $violationList, $previous = null)
    {
        $modelState = $this->createModelState($model, $processName, $stepName, $previous);
        $modelState->setSuccessful(false);
        $modelState->setErrors($violationList->toArray());

        $this->om->persist($modelState);
        $this->om->flush($modelState);

        return $modelState;
    }
1118071
public function creating(Model $model)
    {
        if (request()->hasFile('name')) {
            // delete prev image
            $file = $this->fileUploader->handle(request()->file('name'));
            $model->name = $file['filename'];
            $model->fill(Arr::except($file, 'filename'));
        } else {
            if ($model->type !== 'f') {
                return false;
            }
        }
    }
1195509
private function prepare(Model $model): Model
    {
        if ($model->usesTimestamps()) {
            $time = $model->freshTimestamp();

            $updatedAtColumn = $model->getUpdatedAtColumn();

            // If model has updated at column and not manually provided.
            if ($updatedAtColumn && null === $model->{$updatedAtColumn}) {
                $model->setUpdatedAt($time);
            }

            $createdAtColumn = $model->getCreatedAtColumn();

            // If model has created at column and not manually provided.
            if ($createdAtColumn && null === $model->{$createdAtColumn}) {
                $model->setCreatedAt($time);
            }
        }

        return $model;
    }
726203
public function updateRevisions(Model $Model, $idlist = array()) {
		if (!$Model->ShadowModel) {
			trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING);
			return;
		}
		foreach ($idlist as $id) {
			$Model->id = $id;
			$Model->createRevision();
		}
	}
1251021
public function createProcess(ProcessFactoryInterface $processFactory): Process
    {
        return $processFactory->createProcess($this->name, $this->arguments);
    }
581428
public function findAllModelStates(ModelInterface $model, $processName, $successOnly = true)
    {
        return $this->repository->findModelStates(
            $model->getWorkflowIdentifier(),
            $processName,
            $successOnly
        );
    }
739333
public function process(Model $model)
    {
        $hiddenOnModel = $model->getHidden();

        foreach ($this->unhidden as $unhidden) {

            if (($key = array_search($unhidden, $hiddenOnModel)) !== false) {

                unset($hiddenOnModel[ $key ]);
            }
        }

        $hiddenOnModel = array_merge($hiddenOnModel, $this->hidden);

        $model->setHidden($hiddenOnModel);

        return $model;
    }
226863
protected function applyPostProcessorsToModel(Model $model)
    {
        foreach ($this->postProcessors as $processorClass => $parameters) {

            // if a processor class was added as a value instead of a key, it
            // does not have parameters
            if (is_numeric($processorClass)) {
                $processorClass = $parameters;
                $parameters     = null;
            }

            $processor = $this->makePostProcessor($processorClass, $parameters);

            $model = $processor->process($model);
        }

        return $model;
    }
82048
public function makeModel($modelName = null)
  {
    $modelName = ucwords($_POST['command']);

    $this->$modelName = $modelName;

    if (file_exists("App/Models/{$this->$modelName}.php")) {
      $this->errors[] = "The model {$this->$modelName} already exists!";
    } elseif (strripos($this->$modelName, '_') == 0) {
      $this->$modelName = ucwords(str_replace('_', '', $this->$modelName));
    }

    if (!empty($this->errors)) {
      echo array_shift($this->errors);
    } else {
      $newModelTemplate = file_get_contents(__DIR__ . '/templates/makeModel.txt');
      $newModel = str_replace('ModelName', $this->$modelName, $newModelTemplate);
      file_put_contents("App/Models/{$this->$modelName}.php", $newModel);
    }

  }
857291
public function create(Model $model)
    {
        $metadata = $model->getMetadata();
        $insert = $this->createInsertObj($model);
        $this->getQuery()->executeInsert($metadata, $insert);
        return $model;
    }
371917
protected function insertModelBeforeElement(Model &$model, Model &$element)
    {
        if ($element->isNew())
            throw new Exception('Target model should be saved before insert');

        $element->refreshTreeColumns();

        /** @var \T4\Orm\Model $class */
        $class = get_class($model);
        $tableName = $class::getTableName();
        /** @var \T4\Dbal\Connection $connection */
        $connection = $class::getDbConnection();

        $this->expandTreeBeforeElement($element, $model->getTreeWidth());

        if (!$model->isNew()) {

            $model->refreshTreeColumns();
            $diff = $element->__lft - $model->__lft;
            $lvldiff = $element->__lvl - $model->__lvl;

            $query = (new Query())
                ->update()
                ->table($tableName)
                ->values([
                    '__lft' => '__lft + :diff',
                    '__rgt' => '__rgt + :diff',
                    '__lvl' => '__lvl + :lvldiff',
                    '__prt' => 'CASE WHEN __id=:id THEN :parentid ELSE __prt END',
                ])
                ->where('__lft>=:lft AND __rgt<=:rgt')
                ->params([':id' => $model->getPk(), 'parentid'=>$element->__prt, ':lft' => $model->__lft, ':rgt' => $model->__rgt, ':diff' => $diff, ':lvldiff' => $lvldiff]);
            $connection->execute($query);

            $this->removeFromTreeByElement($model);

        } else {
            // TODO: этот вариант тоже рассмотреть
            throw new Exception('Save this model before move');
        }

        // TODO: рассчитывать
        $model->refreshTreeColumns();
        $element->refreshTreeColumns();

    }
1109186
protected function reachStep(ModelInterface $model, Step $step, ModelState $currentModelState = null)
    {
        try {
            $this->checkCredentials($model, $step);
        } catch (AccessDeniedException $e) {
            $violations = new ViolationList();
            $violations->add(new Violation($e->getMessage()));

            $modelState = $this->storage->newModelStateError($model, $this->process->getName(), $step->getName(), $violations, $currentModelState);

            $eventName = sprintf('%s.%s.bad_credentials', $this->process->getName(), $step->getName());
            $this->dispatcher->dispatch($eventName, new StepEvent($step, $model, $modelState));

            if ($step->getOnInvalid()) {
                $step = $this->getProcessStep($step->getOnInvalid());
                $modelState = $this->reachStep($model, $step);
            }

            return $modelState;
        }

        $event = new ValidateStepEvent($step, $model, new ViolationList());
        $eventName = sprintf('%s.%s.validate', $this->process->getName(), $step->getName());
        $this->dispatcher->dispatch($eventName, $event);

        if (0 === count($event->getViolationList())) {
            $modelState = $this->storage->newModelStateSuccess($model, $this->process->getName(), $step->getName(), $currentModelState);

            // update model status
            if ($step->hasModelStatus()) {
                list($method, $constant) = $step->getModelStatus();
                $model->$method(constant($constant));
            }

            $eventName = sprintf('%s.%s.reached', $this->process->getName(), $step->getName());
            $this->dispatcher->dispatch($eventName, new StepEvent($step, $model, $modelState));
        } else {
            $modelState = $this->storage->newModelStateError($model, $this->process->getName(), $step->getName(), $event->getViolationList(), $currentModelState);

            $eventName = sprintf('%s.%s.validation_fail', $this->process->getName(), $step->getName());
            $this->dispatcher->dispatch($eventName, new StepEvent($step, $model, $modelState));

            if ($step->getOnInvalid()) {
                $step = $this->getProcessStep($step->getOnInvalid());
                $modelState = $this->reachStep($model, $step);
            }
        }

        return $modelState;
    }
641891
public function beforeValidationOnUpdate(Event $event, Model $model)
    {
        if($model instanceof ITimestampable) {
            $now = $this->getNow();
            $model->setUpdatedAt($now);
        }
    }
230120
protected function assertStepExists($stepName)
    {
        if (!$this->hasStepNamed($stepName)) {
            throw new NoStepWithNameFoundException(
                sprintf('Could not find step named %s in scenario %s', $stepName, get_class($this->scenario))
            );
        }
    }
464222
public function create(ModelInterface $model)
    {
        $comment = $this->container->make(CommentSingularity::class);

        $comment
            ->setModel($model)
            ->boot();

        return $comment;
    }
873985
protected function addStepElementsForStep2(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model) {
        $element = $bridge->getForm()->createElement('html', 'table');
        $bridge->addElement($element);

        $table = $element->table(['class' => 'browser table']);

        $headers = [
            $this->_('Question code'),
            $this->_('Source Survey'),
            $this->_('Target Survey'),
        ];

        $tableHeader = $table->thead();

        $headerRow = $tableHeader->tr();
        foreach ($headers as $label) {
            $headerRow->th($label);
        }

        $headerRow = $tableHeader->tr();
        $headerRow->th();
        $headerRow->th($this->surveys[$this->sourceSurveyId]);
        $headerRow->th($this->surveys[$this->targetSurveyId]);

        $tableBody = $table->tbody();

        $row = $tableBody->tr();
        $row->td($this->_('Usage'));
        $row->td($this->getSurveyStatistics($this->sourceSurveyId));
        $row->td($this->getSurveyStatistics($this->targetSurveyId));

        $this->addSurveyCompareForm($tableBody, $this->formData);
    }
797181
protected function reindexModel(Model $model)
    {
        $mapping = $this->option('mapping') ? json_decode(File::get($this->option('mapping')), true) : null;

        $this->info('---> Reindexing ' . get_class($model));

        $model->reindex(
            $this->option('relations'),
            $this->option('batch'),
            $mapping,
            function ($batch)
            {
                $this->info("* Batch ${batch}");
            }
        );
    }