Generate Migration file

@param $version
@param string $contentUp
@param string $contentDown
@return mixed|string
971129
protected function _generateMigrationFile($version, $contentUp = "", $contentDown = "")
    {
        $classVersion = preg_replace('/[^0-9A-Za-z]/', '', $version);
        $className = 'Migration_' . $classVersion;
        $classData = "<?php

use Phalcon\Migrations\MigrationScript as Migration;

class " . $className . " extends Migration\n" .
            "{\n\n" .
            "\tpublic function up()\n" .
            "\t{\n" . $contentUp .
            "\n\t}" .
            "\n\n" .
            "\tpublic function down()\n" .
            "\t{\n" . $contentDown .
            "\n\t}" .
            "\n}\n";
        $classData = str_replace("\t", "    ", $classData);

        file_put_contents($this->migrationsDir . '/' . $version . '.php', $classData);

        return $classData;
    }
587157
public function createLocationsFromNodeAssignments($contentId, $versionNo)
    {
        // select all node assignments with OP_CODE_CREATE (3) for this content
        $query = $this->handler->createSelectQuery();
        $query
            ->select('*')
            ->from($this->handler->quoteTable('eznode_assignment'))
            ->where(
                $query->expr->lAnd(
                    $query->expr->eq(
                        $this->handler->quoteColumn('contentobject_id'),
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
                    ),
                    $query->expr->eq(
                        $this->handler->quoteColumn('contentobject_version'),
                        $query->bindValue($versionNo, null, \PDO::PARAM_INT)
                    ),
                    $query->expr->eq(
                        $this->handler->quoteColumn('op_code'),
                        $query->bindValue(self::NODE_ASSIGNMENT_OP_CODE_CREATE, null, \PDO::PARAM_INT)
                    )
                )
            )->orderBy('id');
        $statement = $query->prepare();
        $statement->execute();

        // convert all these assignments to nodes

        while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) {
            if ((bool)$row['is_main'] === true) {
                $mainLocationId = true;
            } else {
                $mainLocationId = $this->getMainNodeId($contentId);
            }

            $parentLocationData = $this->getBasicNodeData($row['parent_node']);
            $isInvisible = $row['is_hidden'] || $parentLocationData['is_hidden'] || $parentLocationData['is_invisible'];
            $this->create(
                new CreateStruct(
                    array(
                        'contentId' => $row['contentobject_id'],
                        'contentVersion' => $row['contentobject_version'],
                        'mainLocationId' => $mainLocationId,
                        'remoteId' => $row['parent_remote_id'],
                        'sortField' => $row['sort_field'],
                        'sortOrder' => $row['sort_order'],
                        'priority' => $row['priority'],
                        'hidden' => $row['is_hidden'],
                        'invisible' => $isInvisible,
                    )
                ),
                $parentLocationData
            );

            $this->updateNodeAssignment(
                $row['contentobject_id'],
                $row['parent_node'],
                $row['parent_node'],
                self::NODE_ASSIGNMENT_OP_CODE_CREATE_NOP
            );
        }
    }
821474
public function getDocumentation($version = null)
    {
        return $this->routesMethodService->getDocumentation(
            $this->context->getRouteId(),
            $version,
            $this->context->getPath()
        );
    }
1033629
public function newVersionContent(ContentInterface $originalContent, $versionName = '')
    {
        $newContent = $this->cloneContent($originalContent);
        $newContent->setVersionName($versionName);
        if (empty($versionName)) {
            $newContent = $this->setVersionName($newContent);
        }

        return $newContent;
    }
198729
function deleteStoredObjectAttribute( $contentObjectAttribute, $version = null )
    {
        $db = eZDB::instance();
        $userID = $contentObjectAttribute->attribute( "contentobject_id" );

        $res = $db->arrayQuery( "SELECT COUNT(*) AS version_count FROM ezcontentobject_version WHERE contentobject_id = $userID" );
        $versionCount = $res[0]['version_count'];

        if ( ( $version == null || $versionCount <= 1 )
                && eZUser::fetch( $userID ) !== null )
        {
            eZUser::removeUser( $userID );
            $db->query( "DELETE FROM ezuser_role WHERE contentobject_id = '$userID'" );
        }
    }
1304343
public function getMigrationSql($version, $increment)
    {
        // I could use the GLOB_BRACE but it is not supported on ALPINE distros.
        // So, I have to call multiple times to simulate the braces.

        if (intval($version) != $version) {
            throw new \InvalidArgumentException("Version '$version' should be a integer number");
        }
        $version = intval($version);

        $filePattern = $this->folder
            . "/migrations"
            . "/" . ($increment < 0 ? "down" : "up")
            . "/*.sql";

        $result = array_filter(glob($filePattern), function ($file) use ($version) {
            return preg_match("/^0*$version(-dev)?\.sql$/", basename($file));
        });

        // Valid values are 0 or 1
        if (count($result) > 1) {
            throw new InvalidMigrationFile("You have two files with the same version number '$version'");
        }

        foreach ($result as $file) {
            if (intval(basename($file)) === $version) {
                return $file;
            }
        }
        return null;
    }
202341
protected function _migrateFile($version, $filePath, $direction = 'up')
    {
        $classVersion = preg_replace('/[^0-9A-Za-z]/', '', $version);
        $className = 'Migration_' . $classVersion;
        if (file_exists($filePath)) {
            require_once $filePath;
            if (class_exists($className)) {
                $migration = new $className($this->config, $version);
                if ($direction === 'up') {
                    $migration->up();
                    if (method_exists($migration, 'afterUp')) {
                        $migration->afterUp();
                    }
                    print PHP_EOL . Color::success('Upgrade Version ' . $version . ' was successfully migrated') . PHP_EOL;
                } elseif ($direction === 'down') {
                    $migration->down();
                    if (method_exists($migration, 'afterDown')) {
                        $migration->afterDown();
                    }
                    print PHP_EOL . Color::info('Downgrade Version ' . $version . ' was successfully migrated') . PHP_EOL;
                }
            }
        } else {
            throw new CommandsException('Migration class cannot be found ' . $className . ' at ' . $filePath);
        }
    }
199256
public function run($version)
    {
        $versions = array();
        $iterator = new \DirectoryIterator($this->migrationsDir);
        foreach ($iterator as $fileinfo) {
            if (!$fileinfo->isDir()) {
                $versions[] = str_replace('.php', '', $fileinfo->getFilename());
            }
        }

        /** @var Mysql $connection */
        $connection = $this->getDI()->get($this->migrationAdapter);
        try {
            $lastMig = $connection->fetchOne('SELECT * FROM migration ORDER BY id DESC', \PDO::FETCH_ASSOC);
        } catch (\PDOException $ex) {
            if ($this->migrationAdapter === 'dbMysql') {
                $connection->query('CREATE TABLE migration (`id` INT NOT NULL AUTO_INCREMENT,`version` VARCHAR(45) NOT NULL,`run_at` DATETIME NOT NULL, PRIMARY KEY (`id`))');
            } else {
                $connection->query('CREATE TABLE "public"."migration" ("id" SERIAL NOT NULL,"version" CHARACTER VARYING(45),"run_at" TIMESTAMP,PRIMARY KEY ("id"));');
            }

        }

        if (isset($lastMig)) {
            $fromVersion = $lastMig['version'];
        } else {
            $fromVersion = '0';
        }

        $toZero = false;
        if (count($versions) == 0) {
            throw new CommandsException('Migrations were not found at ' . $this->migrationsDir);
        } else {
            if ($version === null) {
                $version = Version::maximum($versions);
            } else {
                if ($version == '0') {
                    $toZero = true;
                    $versionsSorted = Version::sortAsc($versions);
                    $version = $versionsSorted[0];

                } elseif ($version === 'up') {
                    $versionsSorted = Version::sortAsc($versions);
                    foreach ($versionsSorted as $k => $v) {
                        if ($v === $fromVersion) {
                            $currentK = $k;
                        }
                    }
                    $version = isset($versionsSorted[$currentK + 1]) ? $versionsSorted[$currentK + 1] : Version::maximum($versions);
                } elseif ($version === 'down') {
                    $versionsSorted = Version::sortAsc($versions);
                    foreach ($versionsSorted as $k => $v) {
                        if ($v === $fromVersion) {
                            $currentK = $k;
                        }
                    }
                    $version = isset($versionsSorted[$currentK - 1]) ? $versionsSorted[$currentK - 1] : $versionsSorted[0];
                }
                $migrationPath = $this->migrationsDir . '/' . $version . '.php';
                if (!file_exists($migrationPath)) {
                    throw new CommandsException('Migration class was not found ' . $migrationPath);
                }
            }
        }

        $versionsBetween = Version::between($fromVersion, $version, $versions);
        if ($toZero === true) {
            $theTwoFirstMigrations = [];
            $theTwoFirstMigrations[] = $versionsBetween[count($versionsBetween) - 1];
            $versionsBetween = $theTwoFirstMigrations;
        }


        try {
            $direction = 'up';
            foreach ($versionsBetween as $k => $v) {
                $migrationPath = $this->migrationsDir . '/' . $v['version'] . '.php';
                $this->_migrateFile((string)$v['version'], $migrationPath, $v['direction']);
                if ($v['direction'] === 'down' && $k === 0) {
                    $direction = $v['direction'];
                    continue;
                } else {
                    $connection->insert("migration", array((string)$v['version'], date('Y-m-d H:i:s')), array("version", "run_at"));
                }
                $direction = $v['direction'];

            }
            if (count($versionsBetween) > 0 && $direction === 'down') {
                $connection->insert("migration", array((string)$version, date('Y-m-d H:i:s')), array("version", "run_at"));
            } elseif (count($versionsBetween) === 0) {
                print Color::colorize('No migration to run' . PHP_EOL . PHP_EOL, Color::FG_GREEN);
            }
            exit(0);
        } catch (\Throwable $e){
            print PHP_EOL . Color::error($e->getMessage()) . PHP_EOL;
            exit(1);
        }

    }
1373144
private function mapContentDraft(VersionInfo $draft, ContentType $contentType): array
    {
        $contentInfo = $draft->getContentInfo();

        return [
            'id' => new VersionId(
                $contentInfo->id,
                $draft->versionNo
            ),
            'contentId' => $contentInfo->id,
            'name' => $draft->getName(),
            'type' => $contentType->getName(),
            'content_type' => $contentType,
            'language' => $draft->initialLanguageCode,
            'version' => $draft->versionNo,
            'modified' => $draft->modificationDate,
        ];
    }
206198
public static function form_policydoc_data(policy_version $version) {

        $data = $version->to_record();
        $summaryfieldoptions = static::policy_summary_field_options();
        $contentfieldoptions = static::policy_content_field_options();

        if (empty($data->id)) {
            // Adding a new version of a policy document.
            $data = file_prepare_standard_editor($data, 'summary', $summaryfieldoptions, $summaryfieldoptions['context']);
            $data = file_prepare_standard_editor($data, 'content', $contentfieldoptions, $contentfieldoptions['context']);

        } else {
            // Editing an existing policy document version.
            $data = file_prepare_standard_editor($data, 'summary', $summaryfieldoptions, $summaryfieldoptions['context'],
                'tool_policy', 'policydocumentsummary', $data->id);
            $data = file_prepare_standard_editor($data, 'content', $contentfieldoptions, $contentfieldoptions['context'],
                'tool_policy', 'policydocumentcontent', $data->id);
        }

        return $data;
    }
1373950
public function generate(
        Configuration $configuration,
        $create = false,
        $update = false,
        $up = null,
        $down = null
    ) {
        $stub = $this->getStub($create, $update);

        $contents = $this->locator->locate($stub)->get();

        $contents = $this->replacer->replace($contents, $this->variables, [
            $configuration->getMigrationsNamespace(),
            $configuration->getNamingStrategy()->getClassName(),
            $this->getTableName($create, $update),
            $up ? $this->tabbedNewLine($up) : null,
            $down ? $this->tabbedNewLine($down) : null
        ]);

        $filename = $configuration->getNamingStrategy()->getFilename();

        $this->writer->write(
            $contents,
            $filename,
            $configuration->getMigrationsDirectory()
        );

        return $filename;
    }
444967
public function getClientKey($uuid, $edition, $version)
    {
        $endPointUrl = $this->apiurl."/client/key/".$uuid."?edition=".$edition."&version=".$version;

        $response = $this->curlGet($endPointUrl);

        return $response;
    }
293620
private function getFileTemplate()
    {
        $content = FormatFileContent::createObject();
        $content->addItem('<?php');
        $content->addItem(
            sprintf(
                '/**Migration file generated at %s on %s by PowerOrm(%s)*/',
                date('h:m:i'),
                date('D, jS F Y'),
                POWERORM_VERSION
            ).PHP_EOL
        );

        $content->addItem('namespace %s;'.PHP_EOL);

        $content->addItem('use Eddmash\\PowerOrm\\Migration\\Migration;');
        $content->addItem('%s');

        $content->addItem('class %s extends Migration{'.PHP_EOL);

        $content->addIndent();
        $content->addItem('public function getDependency(){');

        $content->addIndent();
        $content->addItem('return [');

        $content->addItem('%s');

        $content->addItem('];');
        $content->reduceIndent();

        $content->addItem('}'.PHP_EOL);

        $content->addItem('public function getOperations(){');

        $content->addIndent();
        $content->addItem('return %s ;');
        $content->reduceIndent();

        $content->addItem('}'.PHP_EOL);
        $content->reduceIndent();

        $content->addItem('}');

        return $content;
    }
1147610
public function apply($contentId)
    {
        $versionNumbers = $this->contentGateway->listVersionNumbers($contentId);
        $fieldIdSet = array();

        $nameRows = $this->contentGateway->loadVersionedNameData(
            array_map(
                function ($versionNo) use ($contentId) {
                    return array('id' => $contentId, 'version' => $versionNo);
                },
                $versionNumbers
            )
        );

        foreach ($versionNumbers as $versionNo) {
            $contentRows = $this->contentGateway->load($contentId, $versionNo);
            $contentList = $this->contentMapper->extractContentFromRows($contentRows, $nameRows);
            $content = $contentList[0];
            $versionFieldIdSet = array();

            foreach ($content->fields as $field) {
                if ($field->fieldDefinitionId == $this->fieldDefinition->id) {
                    $fieldIdSet[$field->id] = true;
                    $versionFieldIdSet[$field->id] = true;
                }
            }

            // Delete from external storage with list of IDs per version
            $this->storageHandler->deleteFieldData(
                $this->fieldDefinition->fieldType,
                $content->versionInfo,
                array_keys($versionFieldIdSet)
            );
        }

        // Delete from internal storage -- field is always deleted from _all_ versions
        foreach (array_keys($fieldIdSet) as $fieldId) {
            $this->contentGateway->deleteField($fieldId);
        }
    }
994917
public function mapContent(Content $content)
    {
        $locations = $this->locationHandler->loadLocationsByContent($content->versionInfo->contentInfo->id);
        $section = $this->sectionHandler->load($content->versionInfo->contentInfo->sectionId);
        $mainLocation = null;
        $locationDocuments = array();
        foreach ($locations as $location) {
            $locationDocuments[] = $this->mapContentLocation($location, $content);
        }

        // UserGroups and Users are Content, but permissions cascade is achieved through
        // Locations hierarchy. We index all ancestor Location Content ids of all
        // Locations of an owner.
        $ancestorLocationsContentIds = $this->getAncestorLocationsContentIds(
            $content->versionInfo->contentInfo->ownerId
        );
        // Add owner user id as it can also be considered as user group.
        $ancestorLocationsContentIds[] = $content->versionInfo->contentInfo->ownerId;

        $fields = array(
            new Field(
                'id',
                $content->versionInfo->contentInfo->id,
                new FieldType\IdentifierField()
            ),
            new Field(
                'type',
                $content->versionInfo->contentInfo->contentTypeId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'version',
                $content->versionInfo->versionNo,
                new FieldType\IdentifierField()
            ),
            new Field(
                'status',
                $content->versionInfo->status,
                new FieldType\IdentifierField()
            ),
            new Field(
                'name',
                $content->versionInfo->contentInfo->name,
                new FieldType\StringField()
            ),
            new Field(
                'creator',
                $content->versionInfo->creatorId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'owner',
                $content->versionInfo->contentInfo->ownerId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'owner_user_group',
                $ancestorLocationsContentIds,
                new FieldType\MultipleIdentifierField()
            ),
            new Field(
                'section',
                $content->versionInfo->contentInfo->sectionId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'section_identifier',
                $section->identifier,
                new FieldType\IdentifierField()
            ),
            new Field(
                'section_name',
                $section->name,
                new FieldType\StringField()
            ),
            new Field(
                'remote_id',
                $content->versionInfo->contentInfo->remoteId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'modified',
                $content->versionInfo->contentInfo->modificationDate,
                new FieldType\DateField()
            ),
            new Field(
                'published',
                $content->versionInfo->contentInfo->publicationDate,
                new FieldType\DateField()
            ),
            new Field(
                'language_code',
                array_keys($content->versionInfo->names),
                new FieldType\MultipleStringField()
            ),
            new Field(
                'always_available',
                $content->versionInfo->contentInfo->alwaysAvailable,
                new FieldType\BooleanField()
            ),
            new Field(
                'locations',
                $locationDocuments,
                new FieldType\DocumentField()
            ),
        );

        $contentType = $this->contentTypeHandler->load($content->versionInfo->contentInfo->contentTypeId);
        $fields[] = new Field(
            'group',
            $contentType->groupIds,
            new FieldType\MultipleIdentifierField()
        );
        $fields[] = new Field(
            'fields',
            $this->mapFields($content, $contentType),
            new FieldType\DocumentField()
        );

        $fields[] = new Field(
            'object_state',
            $this->getObjectStateIds($content->versionInfo->contentInfo->id),
            new FieldType\MultipleIdentifierField()
        );

        $document = new Document(
            array(
                'id' => $content->versionInfo->contentInfo->id,
                'type' => 'content',
                'fields' => $fields,
            )
        );

        return $document;
    }
895636
public function updateVersion($contentId, $versionNo, UpdateStruct $struct)
    {
        $q = $this->dbHandler->createUpdateQuery();
        $q->update(
            $this->dbHandler->quoteTable('ezcontentobject_version')
        )->set(
            $this->dbHandler->quoteColumn('creator_id'),
            $q->bindValue($struct->creatorId, null, \PDO::PARAM_INT)
        )->set(
            $this->dbHandler->quoteColumn('modified'),
            $q->bindValue($struct->modificationDate, null, \PDO::PARAM_INT)
        )->set(
            $this->dbHandler->quoteColumn('initial_language_id'),
            $q->bindValue($struct->initialLanguageId, null, \PDO::PARAM_INT)
        )->set(
            $this->dbHandler->quoteColumn('language_mask'),
            $q->expr->bitOr(
                $this->dbHandler->quoteColumn('language_mask'),
                $q->bindValue(
                    $this->generateLanguageMask(
                        $struct->fields,
                        $this->languageHandler->load($struct->initialLanguageId)->languageCode,
                        false
                    ),
                    null,
                    \PDO::PARAM_INT
                )
            )
        )->where(
            $q->expr->lAnd(
                $q->expr->eq(
                    $this->dbHandler->quoteColumn('contentobject_id'),
                    $q->bindValue($contentId, null, \PDO::PARAM_INT)
                ),
                $q->expr->eq(
                    $this->dbHandler->quoteColumn('version'),
                    $q->bindValue($versionNo, null, \PDO::PARAM_INT)
                )
            )
        );
        $q->prepare()->execute();
    }
1024505
public function deleteTranslationFromVersion($contentId, $versionNo, $languageCode)
    {
        $language = $this->languageHandler->loadByLanguageCode($languageCode);

        $this->connection->beginTransaction();
        try {
            $this->deleteTranslationFromContentVersions($contentId, $language->id, $versionNo);
            $this->deleteTranslationFromContentNames($contentId, $languageCode, $versionNo);

            $this->connection->commit();
        } catch (DBALException $e) {
            $this->connection->rollBack();
            throw $e;
        }
    }