Converts existing non-localised model tables to a localised version

@param \stdClass $oModel The model being converted

@return $this
975684
private function convertTablesToLocalised(\stdClass $oModel): self
    {
        /** @var Database $oDb */
        $oDb = Factory::service('Database');
        /** @var \Nails\Common\Service\Locale $locale */
        $oLocale = Factory::service('Locale');

        $aQueries = [
            //  Disable foreign key checks so we can shift the tables about
            'SET FOREIGN_KEY_CHECKS = 0;',

            //  Rename the existing table (and data)
            'RENAME TABLE `' . $oModel->table_with_prefix . '` TO `' . $oModel->table_with_prefix . '_localised`;',

            //  Drop the AUTO_INCREMENT key
            'ALTER TABLE `' . $oModel->table_with_prefix . '_localised` CHANGE `id` `id` INT(11) UNSIGNED NOT NULL;',

            //  Change the primary key
            'ALTER TABLE  `' . $oModel->table_with_prefix . '_localised` DROP PRIMARY KEY, ADD PRIMARY KEY (`id`, `language`, `region`)',

            //  Create the new top-level table
            'CREATE TABLE `' . $oModel->table_with_prefix . '` (id INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT) DEFAULT CHARACTER SET `utf8`;',

            //  Add a foreign key to the localised table
            'ALTER TABLE `' . $oModel->table_with_prefix . '_localised` ADD FOREIGN KEY (`id`) REFERENCES `' . $oModel->table_with_prefix . '` (`id`) ON DELETE CASCADE;',

            //  Add the locale columns
            'ALTER TABLE `' . $oModel->table_with_prefix . '_localised` ADD `language` VARCHAR(5) NULL DEFAULT NULL AFTER `id`;',
            'ALTER TABLE `' . $oModel->table_with_prefix . '_localised` ADD `region` VARCHAR(5) NULL DEFAULT NULL AFTER `language`;',

            //  Populate the top-level table
            'INSERT INTO ' . $oModel->table_with_prefix . ' SELECT id FROM ' . $oModel->table_with_prefix . '_localised;',

            //  Update the columns with the default language
            'UPDATE `' . $oModel->table_with_prefix . '_localised` SET `language` = "' . $oLocale->get()->getLanguage() . '"',
            'UPDATE `' . $oModel->table_with_prefix . '_localised` SET `region` = "' . $oLocale->get()->getRegion() . '"',

            //  Re-enable foreign key checks
            'SET FOREIGN_KEY_CHECKS = 1;',
        ];

        array_walk($aQueries, function ($sQuery) use ($oDb) {
            $oDb->query($sQuery);
        });

        $this->warning(array_merge(['Remember to add migrations!', ''], $aQueries));

        return $this;
    }
419110
public function convertToModel()
    {
        $unit = new \Liip\TranslationBundle\Model\Unit(
            $this->getDomain(),
            $this->getKey(),
            $this->getMetadata()
        );
        foreach ($this->getTranslations() as $translation) {
            $unit->setTranslation($translation->getLocale(), $translation->getValue());
        }

        return $unit;
    }
387040
public function withLocale($locale, $callback)
    {
        if (! $locale) {
            return $callback();
        }

        $app = Container::getInstance();

        $original = $app->getLocale();

        try {
            $app->setLocale($locale);

            return $callback();
        } finally {
            $app->setLocale($original);
        }
    }
1264592
protected static function _getModuleInstaller(oxModuleCache $oModuleCache)
    {
        if (self::$_oModuleInstaller === null) {
            self::$_oModuleInstaller = oxNew('oxModuleInstaller', $oModuleCache);
        }

        return self::$_oModuleInstaller;
    }
1351149
protected static function _getModuleCache(oxModule $oModule)
    {
        if (self::$_oModuleCache === null) {
            self::$_oModuleCache = oxNew('oxModuleCache', $oModule);
        }

        return self::$_oModuleCache;
    }
707096
public function setEndOfThrottle($endOfThrottle)
    {
        if (is_int($endOfThrottle)) {
            $endOfThrottle = Carbon::createFromTimestamp($endOfThrottle);
        }

        $this->endOfThrottle = $endOfThrottle;

        return $this;
    }
963357
protected function addAppointmentsToModel()
    {
        $model = new \MUtil_Model_TableModel('gems__track_appointments');
        \Gems_Model::setChangeFieldsByPrefix($model, 'gtap');

        $map = $model->getItemsOrdered();
        $map = array_combine($map, str_replace('gtap_', 'gtf_', $map));
        $map['gtap_id_app_field'] = 'gtf_id_field';

        $this->addUnionModel($model, $map, self::APPOINTMENTS_NAME);

        $model->addColumn(new \Zend_Db_Expr("'appointment'"), 'gtf_field_type');
        $model->addColumn(new \Zend_Db_Expr("NULL"), 'gtf_field_values');
        $model->addColumn(new \Zend_Db_Expr("NULL"), 'gtf_field_default');
        $model->addColumn(new \Zend_Db_Expr("NULL"), 'gtf_calculate_using');
    }
751362
public void setPomModel( PomModel pomModel ) {
        this.pomModel = pomModel;
        if ( srcMfs.isAvailable( "pom.xml" ) ) {
            this.pomXml = srcMfs.getBytes( "pom.xml" );
        }
    }
496217
public function setLocale($locale)
    {
        if ($this->isRoot) {
            $this->translator->setLocale($locale);

            return $this;
        }

        $this->locale = $locale;

        return $this;
    }
689065
public function update($sModule = null, $oOutput = null)
    {
        if (!$this->bCanWriteRoutes) {
            $this->setError($this->sCantWriteReason);
            return false;
        }

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

        //  Look for modules who wish to write to the routes file
        $aModules = Components::modules();

        //  Append the app
        $aModules['app'] = (object) [
            'slug'      => 'app',
            'name'      => 'APP',
            'namespace' => 'App\\',
        ];

        foreach ($aModules as $oModule) {

            if (!empty($sModule) && $sModule !== $oModule->slug) {
                continue;
            }

            $sClass = $oModule->namespace . 'Routes';
            if (class_exists($sClass)) {

                if (!is_null($oOutput)) {
                    $oOutput->write('Generating routes for <info>' . $oModule->slug . '</info>... ');
                }

                $sInterface = 'Nails\\Common\\Interfaces\\RouteGenerator';
                if (!classImplements($sClass, $sInterface)) {
                    throw new NailsException(
                        'Routes generator ' . $sClass . ' does not implement ' . $sInterface
                    );
                }

                $this->aRoutes = array_merge(
                    $this->aRoutes,
                    ['// BEGIN ' . $oModule->name => ''],
                    $sClass::generate(),
                    ['// END ' . $oModule->name => '']
                );

                if (!is_null($oOutput)) {
                    $oOutput->writeln('<info>done!</info>');
                }
            }
        }

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

        //  Write the file
        if (!is_null($oOutput)) {
            $oOutput->write('Writing routes to file... ');
        }

        if ($this->writeFile()) {

            if (!is_null($oOutput)) {
                $oOutput->writeln('<info>done!</info>');
            }
            return true;

        } else {

            if (!is_null($oOutput)) {
                $oOutput->writeln('<error>failed!</error>');
            }
            return false;
        }
    }
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;
    }
1148647
public function setEntityManager(ObjectManager $om)
    {
        $this->objectManager     = $om;
        $this->ticketRepository  = $om->getRepository($this->ticketClass);
        $this->messageRepository = $om->getRepository($this->ticketMessageClass);

        return $this;
    }
284661
public function joinFallbackTranslation(callable $callable = null)
    {
        if ($this->translatableLang->langId() == 'en') {
            return $this;
        }

        $selects = [];
        $translaTable = $this->getTable() . $this->translatableTableSuffix;
        $fields = $this->getRepository()->getCache()->getTableFields($translaTable);
        $translatableKey = '`' . $translaTable . '`.`id`';
        foreach ($fields as $field) {
            if (in_array($field, ['id', $this->translatableLanguageField])) {
                continue;
            }

            $translatableField = '`' . $translaTable . '`.`' . $field . '`';
            $fallbackField = '`' . $translaTable . '_f`.`' . $field . '`';
            $selects[] = 'IF(' . $translatableKey . ', ' . $translatableField . ', ' . $fallbackField . ') AS `' .
                $field . '`';
        }

        $relation = $this->join($this->translationsFallback($callable));

        $relation->getQuery()->addSelect($selects);

        return $relation;
    }
430627
public static function removeModelFromCollection(\Model $objModel, \Model\Collection $objCollection = null)
    {
        $arrRegistered = [];

        if ($objCollection !== null)
        {
            while ($objCollection->next())
            {
                if ($objCollection->getTable() !== $objModel->getTable)
                {
                    return $objCollection;
                }

                $intId = $objCollection->{$objModel::getPk()};

                if ($objModel->{$objModel::getPk()} == $intId)
                {
                    continue;
                }

                $arrRegistered[$intId] = $objCollection->current();
            }
        }

        return static::createCollection(array_filter(array_values($arrRegistered)), $objModel->getTable());
    }
1173061
public function makeModel()
    {
        if (!($this->model = $this->app->make($this->takeModel())) instanceof Eloquent) {
            throw new InvalidRepositoryModel(get_class($this->model), Eloquent::class);
        }

        return $this->model;
    }
34094
function(oData) {
			if (this._oModel) {
				this._oModel.destroy();
				delete this._oModel;
			}
			if (oData) {
				this._oModel = new JSONModel(oData);
				this._getTable().setModel(this._oModel);
			} else {
				this._getTable().setModel(null);
			}
			this.setProperty("data", oData);
		}
372662
public function orAdd()
    {
        $args = func_get_args();
        $value = array_shift($args);
        
        $params = [];
        while ($args) {
            $param = array_shift($args);
            if (is_array($param)) {
                $params = array_merge($params, $param);
            } else {
                $params[] = $param;
            }
        }

        $value = new WhereConditionValue($this, $value, $params);
        $value->chain_by = WhereCondition::CHAIN_BY_OR;
        $this->add($value);

        return $this;
    }