Creates the model

@return \MUtil_Model_ModelAbstract
16858
protected function createModel()
    {
        if (! $this->model instanceof EpisodeOfCareModel) {
            $this->model = $this->loader->getModels()->createEpisodeOfCareModel();

            $this->model->applyBrowseSettings();
        }

        if ($this->calSearchFilter instanceof AppointmentFilterInterface) {
            $this->model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr'), 'order', 3);

            \Gems_Model_RespondentModel::addNameToModel($this->model, $this->_('Name'));

            $this->model->set('name', 'order', 6);
        }

        // \MUtil_Model::$verbose = true;
        return $this->model;
    }
1003290
protected function createModel()
    {
        $groupby['period_1'] = new \Zend_Db_Expr("YEAR($this->dateFrom)");

        $date = new \MUtil_Date();

        switch ($this->dateType) {
            case 'D':
                $keyCount = 1;
                $groupby['period_1'] = new \Zend_Db_Expr("CONVERT($this->dateFrom, DATE)");

                $date->setTime(0);
                $date->addDay($this->dateFactor - $this->dateRange);

                $start = $date->getIso();
                for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) {
                    if (0 == $i) {
                        $this->dateCurrentStart = clone $date;
                        $this->dateCurrentEnd   = clone $date;
                        $this->dateCurrentEnd->setTimeToDayEnd();
                    }

                    $values = array();
                    $values['period_1'] = $date->get('yyyy-MM-dd');
                    $values['range']    = $i;
                    $requiredRows[$i]   = $values;
                    $date->addDay(1);
                }
                $date->subSecond(1);
                $end = $date->getIso();
                break;

            case 'W':
                $keyCount = 2;

                // Use MONDAY as start of week
                $groupby['period_1'] = new \Zend_Db_Expr("substr(YEARWEEK(gto_valid_from, 3),1,4)");
                //$groupby['period_1'] = new \Zend_Db_Expr("YEAR($this->dateFrom) - CASE WHEN WEEK($this->dateFrom, 1) = 0 THEN 1 ELSE 0 END");
                $groupby['period_2'] = new \Zend_Db_Expr("WEEK($this->dateFrom, 3)");

                $date->setWeekday(1);
                $date->setTime(0);
                $date->addWeek($this->dateFactor - $this->dateRange);

                $start = $date->getIso();
                for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) {
                    if (0 == $i) {
                        $this->dateCurrentStart = clone $date;
                        $this->dateCurrentEnd   = clone $date;
                        $this->dateCurrentEnd->addWeek(1)->subSecond(1);
                    }

                    $values = array();
                    $values['period_1'] = $date->get(\Zend_Date::YEAR);
                    $values['period_2'] = (int) $date->get(\Zend_Date::WEEK);   // Use constant but drop leading zero
                    // When monday is in the previous year, add one to the year
                    if ($date->get(\Zend_Date::DAY_OF_YEAR)>14 && $date->get(\Zend_Date::WEEK) == 1) {
                        $values['period_1'] =  $values['period_1'] + 1;
                    }
                    $values['range']    = $i;
                    $requiredRows[$i]   = $values;
                    $date->addWeek(1);
                }
                $date->subSecond(1);
                $end = $date->getIso();
                break;

            case 'M':
                $keyCount = 2;
                $groupby['period_2'] = new \Zend_Db_Expr("MONTH($this->dateFrom)");

                $date->setDay(1);
                $date->setTime(0);
                $date->addMonth($this->dateFactor - $this->dateRange);

                $start = $date->getIso();
                for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) {
                    if (0 == $i) {
                        $this->dateCurrentStart = clone $date;
                        $this->dateCurrentEnd   = clone $date;
                        $this->dateCurrentEnd->addMonth(1)->subSecond(1);
                    }

                    $values = array();
                    $values['period_1'] = $date->get(\Zend_Date::YEAR);
                    $values['period_2'] = $date->get(\Zend_Date::MONTH);
                    $values['range']    = $i;
                    $requiredRows[$i]   = $values;
                    $date->addMonth(1);
                }
                $date->subSecond(1);
                $end = $date->getIso();
                break;

            case 'Y':
                $keyCount = 1;
                $date->setDay(1);
                $date->setMonth(1);
                $date->setTime(0);
                $date->addYear($this->dateFactor - $this->dateRange);
                $start = $date->getIso();
                for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) {
                    if (0 == $i) {
                        $this->dateCurrentStart = clone $date;
                        $this->dateCurrentEnd   = clone $date;
                        $this->dateCurrentEnd->addYear(1)->subSecond(1);
                    }

                    $values = array();
                    $values['period_1'] = $date->get(\Zend_Date::YEAR);
                    $values['range']    = $i;
                    $requiredRows[$i]   = $values;
                    $date->addYear(1);
                }
                $date->subSecond(1);
                $end = $date->getIso();
                break;

            default:
                throw new \Gems_Exception_Coding('Incorrect date_type value: ' . $this->dateType);
        }
        $where = "$this->dateFrom BETWEEN '$start' AND '$end'";

        for ($i = -$this->dateRange; $i <= $this->dateRange; $i++) {
            $requiredRows[$i]['date_factor'] = $this->dateFactor + $i;
            $requiredRows[$i]['df_link']     = null;
            $requiredRows[$i]['df_label']    = null;
        }
        if ($this->dateRange > 0) {
            $requiredRows[-$this->dateRange]['df_link']  = $this->dateFactor - ($this->dateRange * 2);
            $requiredRows[-$this->dateRange]['df_label'] = $this->_('<<');
            $requiredRows[ $this->dateRange]['df_link']  = $this->dateFactor + ($this->dateRange * 2);
            $requiredRows[ $this->dateRange]['df_label'] = $this->_('>>');
            if ($this->dateRange > 1) {
                $i = intval($this->dateRange / 2);
                $requiredRows[-$i]['df_link']  = $this->dateFactor - 1;
                $requiredRows[-$i]['df_label'] = $this->_('<');
                $requiredRows[ $i]['df_link']  = $this->dateFactor + 1;
                $requiredRows[ $i]['df_label'] = $this->_('>');
            }
            $requiredRows[ 0]['df_link']  = $this->dateFactor ? '0' : null;
            $requiredRows[ 0]['df_label'] = $this->_('Now!');
        }

        if ($this->dateFactor) {
            $today = new \MUtil_Date();
            $this->dateFactorChanges['D'] = $this->dateCurrentStart->diffDays($today);
            $this->dateFactorChanges['W'] = $this->dateCurrentStart->diffWeeks($today);
            $this->dateFactorChanges['M'] = $this->dateCurrentStart->diffMonths($today);
            $this->dateFactorChanges['Y'] = $this->dateCurrentStart->diffYears($today);
        } else {
            $this->dateFactorChanges = array_fill_keys(array('D', 'W', 'M', 'Y'), 0);
        }
        // \MUtil_Echo::track($requiredRows);
        // \MUtil_Echo::rs($start, $end, $where);

        $select = new \Zend_Db_Select($this->db);
        $select->from($this->dataTableName, $groupby + $this->getDbFields());
        $select->where($where);
        $select->group($groupby);

        $this->processSelect($select);

        // \MUtil_Echo::r((string) $select);

        $model = new \MUtil_Model_SelectModel($select, $this->dataTableName);

        // Display by column cannot use formatFunction as it is a simple repeater
        // $model->set('duration_avg', 'formatFunction', $this->util->getLocalized()->formatNumber);

        $transformer = new \MUtil_Model_Transform_RequiredRowsTransformer();
        $transformer->setDefaultRow($this->getDefaultRow());
        $transformer->setRequiredRows($requiredRows);
        $transformer->setKeyItemCount($keyCount);
        $model->addTransformer($transformer);

        return $model;
    }
1172955
public function actionCreate()
    {
        Yii::$app->getResponse()->format = 'json';
        $routes = Yii::$app->getRequest()->post('route', '');
        $routes = preg_split('/\s*,\s*/', trim($routes), -1, PREG_SPLIT_NO_EMPTY);
        $model = new Route();
        $model->addNew($routes);
        return $model->getRoutes();
    }
756478
private function createModel(): self
    {
        $oInput      = $this->oInput;
        $oOutput     = $this->oOutput;
        $bSkipDb     = $oInput->getOption('skip-db');
        $bSkipSeeder = $oInput->getOption('skip-seeder');
        $bAutoDetect = $oInput->getOption('auto-detect');
        $bLocalised  = $oInput->getOption('localised');
        $bAdmin      = Components::exists('nails/module-admin') && $oInput->getOption('admin');

        //  If auto-detecting models using the database then skip cresting database tables
        if ($bAutoDetect) {
            $bSkipDb = true;
        }

        try {

            if (!$bAutoDetect) {

                $aFields    = $this->getArguments();
                $aModels    = explode(',', $aFields['MODEL_NAME']);
                $aModelData = [];
                sort($aModels);
                foreach ($aModels as $sModelName) {
                    $oModel = $this->prepareModelName($sModelName);

                    /**
                     * Test whether the model exists already
                     *
                     * Alter our behaviour slightly depending if we're localising or not. An existing model, which
                     * is not-localised is OK as we'll convert it to be localised (assuming the --localised flag
                     * is passed).
                     */

                    if ($this->modelExists($oModel)) {
                        if ($bLocalised && classUses($oModel->class_path, Localised::class)) {
                            throw new NailsException(
                                'A localised model by that path already exists "' . $oModel->path . $oModel->filename . '"'
                            );
                        } elseif (!$bLocalised) {
                            throw new NailsException(
                                'A model by that path already exists "' . $oModel->path . $oModel->filename . '"'
                            );
                        }
                    }

                    if (!$bSkipDb && $this->tableExists($oModel)) {
                        if ($bLocalised && classUses($oModel->class_path, Localised::class)) {
                            throw new NailsException(
                                'Localised table "' . $oModel->table_with_prefix . '" already exists. Use option --skip-db to skip database check.'
                            );
                        } elseif (!$bLocalised) {
                            throw new NailsException(
                                'Table "' . $oModel->table_with_prefix . '" already exists. Use option --skip-db to skip database check.'
                            );
                        }
                    }

                    $aModelData[] = $oModel;
                }

            } else {

                $oDb        = Factory::service('PDODatabase');
                $sAppPrefix = defined('APP_DB_PREFIX') ? APP_DB_PREFIX : '';
                $oTables    = $oDb->query('SHOW TABLES LIKE "' . $sAppPrefix . '%";');
                $aTables    = $oTables->fetchAll(\PDO::FETCH_NUM);

                //  If APP_DB_PREFIX is empty then the query above will have all the Nails table's too,
                //  filter them out.
                if (empty($sAppPrefix)) {
                    $aTables = array_filter(
                        $aTables,
                        function ($aTable) {
                            return !preg_match('/^' . NAILS_DB_PREFIX . '/', $aTable[0]);
                        }
                    );
                    $aTables = array_values($aTables);
                }

                $aModelData = array_map(
                    function ($aTable) use ($sAppPrefix) {
                        $sTable = $aTable[0];
                        $sTable = preg_replace('/^' . $sAppPrefix . '/', '', $sTable);
                        $sTable = str_replace('_', ' ', $sTable);
                        $sTable = ucwords($sTable);
                        $sTable = str_replace(' ', '/', $sTable);

                        $oModel = $this->prepareModelName($sTable);

                        return $this->modelExists($oModel) ? null : $oModel;
                    },
                    $aTables
                );
                $aModelData = array_filter($aModelData);
            }

            arraySortMulti($aModelData, 'class_path');

            //  Report to the user and get confirmation
            $oOutput->writeln('The following model(s) will be created:');
            $oOutput->writeln('');
            foreach ($aModelData as $oModel) {
                $oOutput->writeln('Model Class:    <info>\\' . $oModel->class_path . '</info>');
                $oOutput->writeln('Model Path:     <info>' . $oModel->path . $oModel->filename . '</info>');
                if ($bLocalised && $this->modelExists($oModel)) {
                    $oOutput->writeln('Localised:      <info>Model will be converted</info>');
                } else {
                    $oOutput->writeln('Resource Class: <info>\\' . $oModel->resource_class_path . '</info>');
                    $oOutput->writeln('Resource Path:  <info>' . $oModel->resource_path . $oModel->resource_filename . '</info>');
                    if (!$bSkipDb) {
                        $oOutput->writeln('Table:          <info>' . $oModel->table_with_prefix . '</info>');
                    }
                    if ($bAdmin) {
                        $oOutput->writeln('Admin:          <info>Controller will be created</info>');
                    }
                    if (!$bSkipSeeder) {
                        $oOutput->writeln('Seeder:         <info>Seeder will be created</info>');
                    }
                }
                $oOutput->writeln('');
            }

            if ($this->confirm('Continue?', true)) {

                $aServiceModelDefinitions    = [];
                $aServiceResourceDefinitions = [];

                foreach ($aModelData as $oModel) {
                    $oOutput->writeln('');
                    if ($bLocalised && $this->modelExists($oModel)) {
                        $this->convertExistingModelToLocalised(
                            $oModel,
                            $bSkipDb,
                            $bAdmin,
                            $bSkipSeeder
                        );
                    } elseif ($bLocalised && !$this->modelExists($oModel)) {
                        list($sServiceDefinition, $sResourceDefinition) = $this->createLocalisedModel(
                            $oModel,
                            $bSkipDb,
                            $bAdmin,
                            $bSkipSeeder
                        );
                    } else {
                        list($sServiceDefinition, $sResourceDefinition) = $this->createNormalModel(
                            $oModel,
                            $bSkipDb,
                            $bAdmin,
                            $bSkipSeeder
                        );
                    }

                    if (!empty($sServiceDefinition)) {
                        $aServiceModelDefinitions[] = $sServiceDefinition;
                    }

                    if (!empty($sResourceDefinition)) {
                        $aServiceResourceDefinitions[] = $sResourceDefinition;
                    }
                }

                // --------------------------------------------------------------------------

                //  Add models to the app's services array
                if (!empty($aServiceModelDefinitions)) {
                    $this->oOutput->writeln('');
                    $this->oOutput->write('Adding model(s) to app services...');
                    $this->writeServiceFile($aServiceModelDefinitions);
                    $this->oOutput->writeln('<info>done!</info>');
                }

                //  Add resources to app's service array
                if (!empty($aServiceResourceDefinitions)) {
                    $this->oOutput->write('Adding resource(s) to app services...');
                    //  Reset the token detials so we write to the correct part of the file
                    $this->validateServiceFile(static::SERVICE_RESOURCE_TOKEN);
                    $this->writeServiceFile($aServiceResourceDefinitions);
                    $this->oOutput->writeln('<info>done!</info>');
                }
            }

        } catch (\Exception $e) {
            if (!empty($aModelData)) {
                foreach ($aModelData as $oModel) {
                    @unlink($oModel->path . '/' . $oModel->filename);
                }
            }
            throw new NailsException(
                $e->getMessage(),
                is_numeric($e->getCode()) ? $e->getCode() : null
            );
        }

        return $this;
    }
1317602
public function create()
    {
        $loaders = array();

        if (count($this->xmlMappings) > 1) {
            $loaders[] = new XmlFilesLoader($this->xmlMappings, $this->constraintNamespaces);
        } elseif (1 === count($this->xmlMappings)) {
            $loaders[] = new XmlFileLoader($this->xmlMappings[0], $this->constraintNamespaces);
        }

        if (count($this->yamlMappings) > 1) {
            $loaders[] = new YamlFilesLoader($this->yamlMappings, $this->constraintNamespaces);
        } elseif (1 === count($this->yamlMappings)) {
            $loaders[] = new YamlFileLoader($this->yamlMappings[0], $this->constraintNamespaces);
        }

        foreach ($this->methodMappings as $methodName) {
            $loaders[] = new StaticMethodLoader($methodName);
        }

        if ($this->annotationReader) {
            $loaders[] = new AnnotationLoader($this->annotationReader);
        }

        $loader = null;

        if (count($loaders) > 1) {
            $loader = new LoaderChain($loaders);
        } elseif (1 === count($loaders)) {
            $loader = $loaders[0];
        }

        return new LazyLoadingMetadataFactory($loader, $this->metadataCache);
    }
3761
public function create()
    {
        $instance = self::createDiscountPromotion($this);
        $this->setId($instance->getId());
        return $instance;
    }
81431
protected function buildModel()
    {
        $config = $this->getGeneratorConfig();
        $con = $this->getConnection();

        $this->log('Reading database structure...');

        $database = new Database($this->getDatabaseName());
        $database->setPlatform($config->getConfiguredPlatform($con));
        $database->setDefaultIdMethod(IDMethod::NATIVE);
        $parser = $config->getConfiguredSchemaParser($con);
        $nbTables = $parser->parse($database, $this);

        $this->log(sprintf('Successfully reverse engineered %d tables', $nbTables));

        return $database;
    }
63824
public function create()
	{
		$class = ($this->classClr) ? 'w50 clr' : 'w50';
		$class .= ($this->multiSelect) ? ' autoheight' : '';

		// Generate options
		$strGroup = 'default';
		foreach (StringUtil::deserialize($this->options) as $arrOption)
		{
			if ($arrOption['group'])
			{
				$strGroup = $arrOption['label'];
				continue;
			}	
			
			if ($arrOption['default'])
			{
				$default = 'v'.$arrOption['value']; // Add a alphabetic character to allow numeric values
			}	
			
			$arrOptions[$strGroup]['v'.$arrOption['value']] = $arrOption['label'];
		}
		
		// No groups 
		if (count($arrOptions) < 2)
		{
			$arrOptions = array_values($arrOptions)[0];
		}

		// Generate a select field
		$this->generateDCA(($this->multiSelect) ? 'multiSelectField' : 'singleSelectField', array
		(
			'inputType' 	=>	'select',
			'label'			=>	array($this->label, $this->description),
			'default'		=>	$default,
			'options'		=>	$arrOptions,
			'eval'			=>	array
			(
				'mandatory'				=> ($this->mandatory) ? true : false, 
				'includeBlankOption'	=> ($this->blankOption) ? true : false,
				'multiple'				=> ($this->multiSelect) ? true : false,
				'chosen'				=> true,
				'tl_class'				=> $class,
			),
		));
	}
976899
protected function createModel($data) {
		$modelClass = $this->getModel();
			
		$model = $modelClass::factory($data);

		if ($this->hasDatagate()) {
			$model->setDatagate($this->getDatagate());
		}
		
		if ($this->hasLocator()) {
			$model->setLocator($this->getLocator());
		}
		
		return $model;
	}
496969
protected function createModel()
    {
        if ($this->model instanceof \Gems_Tracker_Model_StandardTokenModel) {
            $model = $this->model;
        } else {
            $model = $this->loader->getTracker()->getTokenModel();
        }
        $model->addColumn(
            'CASE WHEN gto_completion_time IS NULL THEN gto_valid_from ELSE gto_completion_time END',
            'calc_used_date',
            'gto_valid_from');
        $model->addColumn(
            'CASE WHEN gto_completion_time IS NULL THEN gto_valid_from ELSE NULL END',
            'calc_valid_from',
            'gto_valid_from');
        $model->addColumn(
            'CASE WHEN gto_completion_time IS NULL AND grc_success = 1 AND gto_valid_from <= CURRENT_TIMESTAMP AND gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP) THEN gto_id_token ELSE NULL END',
            'calc_id_token',
            'gto_id_token');
        $model->addColumn(
            'CASE WHEN gto_completion_time IS NULL AND grc_success = 1 AND gto_valid_from <= CURRENT_TIMESTAMP AND gto_completion_time IS NULL AND gto_valid_until < CURRENT_TIMESTAMP THEN 1 ELSE 0 END',
            'was_missed');
        return $model;
    }
621498
public function create(): Model
	{
		$model_class = $this->getModelClass();
		$instance = new $model_class;
		$this->fill($instance);

		return $instance;
	}
1137424
protected function createModel()
    {
        if ($this->model instanceof \Gems_Model_StaffModel) {
            $model = $this->model;
        } else {
            $model = $this->loader->getModels()->getStaffModel();
            $model->applyBrowseSettings();
        }

        return $model;
    }
348167
protected function createModel()
    {
        $tracker = $this->loader->getTracker();
        $model   = $tracker->getRespondentTrackModel();

        if (! $this->trackEngine instanceof \Gems_Tracker_Engine_TrackEngineInterface) {
            if (! $this->respondentTrack) {
                $this->respondentTrack = $tracker->getRespondentTrack($this->respondentTrackId);
            }
            $this->trackEngine = $this->respondentTrack->getTrackEngine();
        }
        $model->applyEditSettings($this->trackEngine);

        return $model;
    }
795710
public function asModels()
    {
        $this->hydrate();

        return new ModelCollection(array_map(function ($element, $key) {

            // Add the key as an attribute
            return new $this->model(array_merge($element, ['key' => $key]));
        }, $this->all(), array_keys($this->items)));
    }
106374
public function makeModel()
    {
        $model = $this->app->make($this->model());

        if (!$model instanceof Model) {
            throw new RepositoryException("Class {$this->model()} must be an instance of Illuminate\\Database\\Eloquent\\Model");
        }

        $this->model = $model->with($this->withRelationShips());

        return $model;
    }
801384
public function create()
    {
        $instance = self::createCustomerGroup($this);
        $this->setId($instance->getId());
        return $instance;
    }
113786
protected function createModel()
    {
        if (! $this->model instanceof \Gems_Model_StaffModel) {
            $this->model = $this->loader->getModels()->getStaffModel(false);
            $this->model->applyOwnAccountEdit();
        }

        return $this->model;
    }