<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

use Yii;
use yii\base\BaseObject;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

/**
 * AssetBundle represents a collection of asset files, such as CSS, JS, images.
 *
 * Each asset bundle has a unique name that globally identifies it among all asset bundles used in an application.
 * The name is the [fully qualified class name](https://secure.php.net/manual/en/language.namespaces.rules.php)
 * of the class representing it.
 *
 * An asset bundle can depend on other asset bundles. When registering an asset bundle
 * with a view, all its dependent asset bundles will be automatically registered.
 *
 * For more details and usage information on AssetBundle, see the [guide article on assets](guide:structure-assets).
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AssetBundle extends BaseObject
{
    /**
     * @var string the directory that contains the source asset files for this asset bundle.
     * A source asset file is a file that is part of your source code repository of your Web application.
     *
     * You must set this property if the directory containing the source asset files is not Web accessible.
     * By setting this property, [[AssetManager]] will publish the source asset files
     * to a Web-accessible directory automatically when the asset bundle is registered on a page.
     *
     * If you do not set this property, it means the source asset files are located under [[basePath]].
     *
     * You can use either a directory or an alias of the directory.
     * @see $publishOptions
     */
    public $sourcePath;
    /**
     * @var string the Web-accessible directory that contains the asset files in this bundle.
     *
     * If [[sourcePath]] is set, this property will be *overwritten* by [[AssetManager]]
     * when it publishes the asset files from [[sourcePath]].
     *
     * You can use either a directory or an alias of the directory.
     */
    public $basePath;
    /**
     * @var string the base URL for the relative asset files listed in [[js]] and [[css]].
     *
     * If [[sourcePath]] is set, this property will be *overwritten* by [[AssetManager]]
     * when it publishes the asset files from [[sourcePath]].
     *
     * You can use either a URL or an alias of the URL.
     */
    public $baseUrl;
    /**
     * @var array list of bundle class names that this bundle depends on.
     *
     * For example:
     *
     * ```php
     * public $depends = [
     *    'yii\web\YiiAsset',
     *    'yii\bootstrap\BootstrapAsset',
     * ];
     * ```
     */
    public $depends = [];
    /**
     * @var array list of JavaScript files that this bundle contains. Each JavaScript file can be
     * specified in one of the following formats:
     *
     * - an absolute URL representing an external asset. For example,
     *   `http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js` or
     *   `//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js`.
     * - a relative path representing a local asset (e.g. `js/main.js`). The actual file path of a local
     *   asset can be determined by prefixing [[basePath]] to the relative path, and the actual URL
     *   of the asset can be determined by prefixing [[baseUrl]] to the relative path.
     * - an array, with the first entry being the URL or relative path as described before, and a list of key => value pairs
     *   that will be used to overwrite [[jsOptions]] settings for this entry.
     *   This functionality is available since version 2.0.7.
     *
     * Note that only a forward slash "/" should be used as directory separator.
     */
    public $js = [];
    /**
     * @var array list of CSS files that this bundle contains. Each CSS file can be specified
     * in one of the three formats as explained in [[js]].
     *
     * Note that only a forward slash "/" should be used as directory separator.
     */
    public $css = [];
    /**
     * @var array the options that will be passed to [[View::registerJsFile()]]
     * when registering the JS files in this bundle.
     */
    public $jsOptions = [];
    /**
     * @var array the options that will be passed to [[View::registerCssFile()]]
     * when registering the CSS files in this bundle.
     */
    public $cssOptions = [];
    /**
     * @var array the options to be passed to [[AssetManager::publish()]] when the asset bundle
     * is being published. This property is used only when [[sourcePath]] is set.
     */
    public $publishOptions = [];

    /**
     * Registers this asset bundle with a view.
     * @param View $view the view to be registered with
     * @return static the registered asset bundle instance
     */
    public static function register($view)
    {
        return $view->registerAssetBundle(get_called_class());
    }

    /**
     * Initializes the bundle.
     * If you override this method, make sure you call the parent implementation in the last.
     */
    public function init()
    {
        if ($this->sourcePath !== null) {
            $this->sourcePath = rtrim(Yii::getAlias($this->sourcePath), '/\\');
        }
        if ($this->basePath !== null) {
            $this->basePath = rtrim(Yii::getAlias($this->basePath), '/\\');
        }
        if ($this->baseUrl !== null) {
            $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
        }
    }

    /**
     * Registers the CSS and JS files with the given view.
     * @param \yii\web\View $view the view that the asset files are to be registered with.
     */
    public function registerAssetFiles($view)
    {
        $manager = $view->getAssetManager();
        foreach ($this->js as $js) {
            if (is_array($js)) {
                $file = array_shift($js);
                $options = ArrayHelper::merge($this->jsOptions, $js);
                $view->registerJsFile($manager->getAssetUrl($this, $file), $options);
            } else {
                if ($js !== null) {
                    $view->registerJsFile($manager->getAssetUrl($this, $js), $this->jsOptions);
                }
            }
        }
        foreach ($this->css as $css) {
            if (is_array($css)) {
                $file = array_shift($css);
                $options = ArrayHelper::merge($this->cssOptions, $css);
                $view->registerCssFile($manager->getAssetUrl($this, $file), $options);
            } else {
                if ($css !== null) {
                    $view->registerCssFile($manager->getAssetUrl($this, $css), $this->cssOptions);
                }
            }
        }
    }

    /**
     * Publishes the asset bundle if its source code is not under Web-accessible directory.
     * It will also try to convert non-CSS or JS files (e.g. LESS, Sass) into the corresponding
     * CSS or JS files using [[AssetManager::converter|asset converter]].
     * @param AssetManager $am the asset manager to perform the asset publishing
     */
    public function publish($am)
    {
        if ($this->sourcePath !== null && !isset($this->basePath, $this->baseUrl)) {
            list($this->basePath, $this->baseUrl) = $am->publish($this->sourcePath, $this->publishOptions);
        }

        if (isset($this->basePath, $this->baseUrl) && ($converter = $am->getConverter()) !== null) {
            foreach ($this->js as $i => $js) {
                if (is_array($js)) {
                    $file = array_shift($js);
                    if (Url::isRelative($file)) {
                        $js = ArrayHelper::merge($this->jsOptions, $js);
                        array_unshift($js, $converter->convert($file, $this->basePath));
                        $this->js[$i] = $js;
                    }
                } elseif (Url::isRelative($js)) {
                    $this->js[$i] = $converter->convert($js, $this->basePath);
                }
            }
            foreach ($this->css as $i => $css) {
                if (is_array($css)) {
                    $file = array_shift($css);
                    if (Url::isRelative($file)) {
                        $css = ArrayHelper::merge($this->cssOptions, $css);
                        array_unshift($css, $converter->convert($file, $this->basePath));
                        $this->css[$i] = $css;
                    }
                } elseif (Url::isRelative($css)) {
                    $this->css[$i] = $converter->convert($css, $this->basePath);
                }
            }
        }
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\build\controllers;

use Yii;
use yii\base\Exception;
use yii\console\Controller;
use yii\helpers\ArrayHelper;
use yii\helpers\Console;
use yii\helpers\FileHelper;

/**
 * ReleaseController is there to help preparing releases.
 *
 * Get a version overview:
 *
 *     ./build release/info
 *
 * run it with `--update` to fetch tags for all repos:
 *
 *     ./build release/info --update
 *
 * Make a framework release (apps are always in line with framework):
 *
 *     ./build release framework
 *     ./build release app-basic
 *     ./build release app-advanced
 *
 * Make an extension release (e.g. for redis):
 *
 *     ./build release redis
 *
 * Be sure to check the help info for individual sub-commands:
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
class ReleaseController extends Controller
{
    public $defaultAction = 'release';

    /**
     * @var string base path to use for releases.
     */
    public $basePath;
    /**
     * @var bool whether to make actual changes. If true, it will run without changing or pushing anything.
     */
    public $dryRun = false;
    /**
     * @var bool whether to fetch latest tags.
     */
    public $update = false;
    /**
     * @var string override the default version. e.g. for major or patch releases.
     */
    public $version;

    public function options($actionID)
    {
        $options = ['basePath'];
        if ($actionID === 'release') {
            $options[] = 'dryRun';
            $options[] = 'version';
        } elseif ($actionID === 'sort-changelog') {
            $options[] = 'version';
        } elseif ($actionID === 'info') {
            $options[] = 'update';
        }

        return array_merge(parent::options($actionID), $options);
    }

    public function beforeAction($action)
    {
        if (!$this->interactive) {
            throw new Exception('Sorry, but releases should be run interactively to ensure you actually verify what you are doing ;)');
        }
        if ($this->basePath === null) {
            $this->basePath = \dirname(\dirname(__DIR__));
        }
        $this->basePath = rtrim($this->basePath, '\\/');
        return parent::beforeAction($action);
    }

    /**
     * Shows information about current framework and extension versions.
     */
    public function actionInfo()
    {
        $items = [
            'framework',
            'app-basic',
            'app-advanced',
        ];
        $extensionPath = "{$this->basePath}/extensions";
        foreach (scandir($extensionPath) as $extension) {
            if (ctype_alpha($extension) && is_dir($extensionPath . '/' . $extension)) {
                $items[] = $extension;
            }
        }

        if ($this->update) {
            foreach ($items as $item) {
                $this->stdout("fetching tags for $item...");
                if ($item === 'framework') {
                    $this->gitFetchTags((string)$this->basePath);
                } elseif (strncmp('app-', $item, 4) === 0) {
                    $this->gitFetchTags("{$this->basePath}/apps/" . substr($item, 4));
                } else {
                    $this->gitFetchTags("{$this->basePath}/extensions/$item");
                }
                $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);
            }
        } else {
            $this->stdout("\nInformation may be outdated, re-run with `--update` to fetch latest tags.\n\n");
        }

        $versions = $this->getCurrentVersions($items);
        $nextVersions = $this->getNextVersions($versions, self::PATCH);

        // print version table
        $w = $this->minWidth(array_keys($versions));
        $this->stdout(str_repeat(' ', $w + 2) . "Current Version  Next Version\n", Console::BOLD);
        foreach ($versions as $ext => $version) {
            $this->stdout($ext . str_repeat(' ', $w + 3 - mb_strlen($ext)) . $version . '');
            $this->stdout(str_repeat(' ', 17 - mb_strlen($version)) . $nextVersions[$ext] . "\n");
        }
    }

    private function minWidth($a)
    {
        $w = 1;
        foreach ($a as $s) {
            if (($l = mb_strlen($s)) > $w) {
                $w = $l;
            }
        }

        return $w;
    }

    /**
     * Automation tool for making Yii framework and official extension releases.
     *
     * Usage:
     *
     * To make a release, make sure your git is clean (no uncommitted changes) and run the following command in
     * the yii dev repo root:
     *
     * ```
     * ./build/build release framework
     * ```
     *
     * or
     *
     * ```
     * ./build/build release redis,bootstrap,apidoc
     * ```
     *
     * You may use the `--dryRun` switch to test the command without changing or pushing anything:
     *
     * ```
     * ./build/build release redis --dryRun
     * ```
     *
     * The command will guide you through the complete release process including changing of files,
     * committing and pushing them. Each git command must be confirmed and can be skipped individually.
     * You may adjust changes in a separate shell or your IDE while the command is waiting for confirmation.
     *
     * @param array $what what do you want to release? this can either be:
     *
     * - an extension name such as `redis` or `bootstrap`,
     * - an application indicated by prefix `app-`, e.g. `app-basic`,
     * - or `framework` if you want to release a new version of the framework itself.
     *
     * @return int
     */
    public function actionRelease(array $what)
    {
        if (\count($what) > 1) {
            $this->stdout("Currently only one simultaneous release is supported.\n");
            return 1;
        }

        $this->stdout("This is the Yii release manager\n\n", Console::BOLD);

        if ($this->dryRun) {
            $this->stdout("Running in \"dry-run\" mode, nothing will actually be changed.\n\n", Console::BOLD, Console::FG_GREEN);
        }

        $this->validateWhat($what);
        $versions = $this->getCurrentVersions($what);

        if ($this->version !== null) {
            // if a version is explicitly given
            $newVersions = [];
            foreach ($versions as $k => $v) {
                $newVersions[$k] = $this->version;
            }
        } else {
            // otherwise get next patch or minor
            $newVersions = $this->getNextVersions($versions, self::PATCH);
        }

        $this->stdout("You are about to prepare a new release for the following things:\n\n");
        $this->printWhat($what, $newVersions, $versions);
        $this->stdout("\n");

        $this->stdout("Before you make a release briefly go over the changes and check if you spot obvious mistakes:\n\n", Console::BOLD);
        $gitDir = reset($what) === 'framework' ? 'framework/' : '';
        $gitVersion = $versions[reset($what)];
        if (strncmp('app-', reset($what), 4) !== 0) {
            $this->stdout("- no accidentally added CHANGELOG lines for other versions than this one?\n\n    git diff $gitVersion.. ${gitDir}CHANGELOG.md\n\n");
            $this->stdout("- are all new `@since` tags for this release version?\n");
        }
        $this->stdout("- other issues with code changes?\n\n    git diff -w $gitVersion.. ${gitDir}\n\n");
        $travisUrl = reset($what) === 'framework' ? '' : '-' . reset($what);
        $this->stdout("- are unit tests passing on travis? https://travis-ci.org/yiisoft/yii2$travisUrl/builds\n");
        $this->stdout("- also make sure the milestone on github is complete and no issues or PRs are left open.\n\n");
        $this->printWhatUrls($what, $versions);
        $this->stdout("\n");

        if (!$this->confirm('When you continue, this tool will run cleanup jobs and update the changelog as well as other files (locally). Continue?', false)) {
            $this->stdout("Canceled.\n");
            return 1;
        }

        foreach ($what as $ext) {
            if ($ext === 'framework') {
                $this->releaseFramework("{$this->basePath}/framework", $newVersions['framework']);
            } elseif (strncmp('app-', $ext, 4) === 0) {
                $this->releaseApplication(substr($ext, 4), "{$this->basePath}/apps/" . substr($ext, 4), $newVersions[$ext]);
            } else {
                $this->releaseExtension($ext, "{$this->basePath}/extensions/$ext", $newVersions[$ext]);
            }
        }

        return 0;
    }

    /**
     * This will generate application packages for download page.
     *
     * Usage:
     *
     * ```
     * ./build/build release/package app-basic
     * ```
     *
     * @param array $what what do you want to package? this can either be:
     *
     * - an application indicated by prefix `app-`, e.g. `app-basic`,
     *
     * @return int
     */
    public function actionPackage(array $what)
    {
        $this->validateWhat($what, ['app']);
        $versions = $this->getCurrentVersions($what);

        $this->stdout("You are about to generate packages for the following things:\n\n");
        foreach ($what as $ext) {
            if (strncmp('app-', $ext, 4) === 0) {
                $this->stdout(' - ');
                $this->stdout(substr($ext, 4), Console::FG_RED);
                $this->stdout(' application version ');
            } elseif ($ext === 'framework') {
                $this->stdout(' - Yii Framework version ');
            } else {
                $this->stdout(' - ');
                $this->stdout($ext, Console::FG_RED);
                $this->stdout(' extension version ');
            }
            $this->stdout($versions[$ext], Console::BOLD);
            $this->stdout("\n");
        }
        $this->stdout("\n");

        $packagePath = "{$this->basePath}/packages";
        $this->stdout("Packages will be stored in $packagePath\n\n");

        if (!$this->confirm('Continue?', false)) {
            $this->stdout("Canceled.\n");
            return 1;
        }

        foreach ($what as $ext) {
            if ($ext === 'framework') {
                throw new Exception('Can not package framework.');
            } elseif (strncmp('app-', $ext, 4) === 0) {
                $this->packageApplication(substr($ext, 4), $versions[$ext], $packagePath);
            } else {
                throw new Exception('Can not package extension.');
            }
        }

        $this->stdout("\ndone. verify the versions composer installed above and push it to github!\n\n");

        return 0;
    }

    /**
     * Sorts CHANGELOG for framework or extension.
     *
     * @param array $what what do you want to resort changelog for? this can either be:
     *
     * - an extension name such as `redis` or `bootstrap`,
     * - or `framework` if you want to release a new version of the framework itself.
     */
    public function actionSortChangelog(array $what)
    {
        if (\count($what) > 1) {
            $this->stdout("Currently only one simultaneous release is supported.\n");
            return 1;
        }
        $this->validateWhat($what, ['framework', 'ext'], false);

        $version = $this->version ?: array_values($this->getNextVersions($this->getCurrentVersions($what), self::PATCH))[0];
        $this->stdout('sorting CHANGELOG of ');
        $this->stdout(reset($what), Console::BOLD);
        $this->stdout(' for version ');
        $this->stdout($version, Console::BOLD);
        $this->stdout('...');

        $this->resortChangelogs($what, $version);

        $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN);
    }

    protected function printWhat(array $what, $newVersions, $versions)
    {
        foreach ($what as $ext) {
            if (strncmp('app-', $ext, 4) === 0) {
                $this->stdout(' - ');
                $this->stdout(substr($ext, 4), Console::FG_RED);
                $this->stdout(' application version ');
            } elseif ($ext === 'framework') {
                $this->stdout(' - Yii Framework version ');
            } else {
                $this->stdout(' - ');
                $this->stdout($ext, Console::FG_RED);
                $this->stdout(' extension version ');
            }
            $this->stdout($newVersions[$ext], Console::BOLD);
            $this->stdout(", last release was {$versions[$ext]}\n");
        }
    }

    protected function printWhatUrls(array $what, $oldVersions)
    {
        foreach ($what as $ext) {
            if ($ext === 'framework') {
                $this->stdout("framework:    https://github.com/yiisoft/yii2-framework/compare/{$oldVersions[$ext]}...master\n");
                $this->stdout("app-basic:    https://github.com/yiisoft/yii2-app-basic/compare/{$oldVersions[$ext]}...master\n");
                $this->stdout("app-advanced: https://github.com/yiisoft/yii2-app-advanced/compare/{$oldVersions[$ext]}...master\n");
            } else {
                $this->stdout($ext, Console::FG_RED);
                $this->stdout(": https://github.com/yiisoft/yii2-$ext/compare/{$oldVersions[$ext]}...master\n");
            }
        }
    }

    /**
     * @param array $what list of items
     * @param array $limit list of things to allow, or empty to allow any, can be `app`, `framework`, `extension`
     * @param bool $ensureGitClean
     * @throws \yii\base\Exception
     */
    protected function validateWhat(array $what, $limit = [], $ensureGitClean = true)
    {
        foreach ($what as $w) {
            if (strncmp('app-', $w, 4) === 0) {
                if (!empty($limit) && !\in_array('app', $limit)) {
                    throw new Exception('Only the following types are allowed: ' . implode(', ', $limit) . "\n");
                }
                if (!is_dir($appPath = "{$this->basePath}/apps/" . substr($w, 4))) {
                    throw new Exception("Application path does not exist: \"{$appPath}\"\n");
                }
                if ($ensureGitClean) {
                    $this->ensureGitClean($appPath);
                }
            } elseif ($w === 'framework') {
                if (!empty($limit) && !\in_array('framework', $limit)) {
                    throw new Exception('Only the following types are allowed: ' . implode(', ', $limit) . "\n");
                }
                if (!is_dir($fwPath = "{$this->basePath}/framework")) {
                    throw new Exception("Framework path does not exist: \"{$this->basePath}/framework\"\n");
                }
                if ($ensureGitClean) {
                    $this->ensureGitClean($fwPath);
                }
            } else {
                if (!empty($limit) && !\in_array('ext', $limit)) {
                    throw new Exception('Only the following types are allowed: ' . implode(', ', $limit) . "\n");
                }
                if (!is_dir($extPath = "{$this->basePath}/extensions/$w")) {
                    throw new Exception("Extension path for \"$w\" does not exist: \"{$this->basePath}/extensions/$w\"\n");
                }
                if ($ensureGitClean) {
                    $this->ensureGitClean($extPath);
                }
            }
        }
    }

    protected function releaseFramework($frameworkPath, $version)
    {
        $this->stdout("\n");
        $this->stdout($h = "Preparing framework release version $version", Console::BOLD);
        $this->stdout("\n" . str_repeat('-', \strlen($h)) . "\n\n", Console::BOLD);

        if (!$this->confirm('Make sure you are on the right branch for this release and that it tracks the correct remote branch! Continue?')) {
            exit(1);
        }
        $this->runGit('git pull', $frameworkPath);

        // checks

        $this->stdout('check if framework composer.json matches yii2-dev composer.json...');
        $this->checkComposer($frameworkPath);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        // adjustments

        $this->stdout('prepare classmap...', Console::BOLD);
        $this->dryRun || Yii::$app->runAction('classmap', [$frameworkPath]);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout('updating mimetype magic file and mime aliases...', Console::BOLD);
        $this->dryRun || Yii::$app->runAction('mime-type', ["$frameworkPath/helpers/mimeTypes.php"], ["$frameworkPath/helpers/mimeAliases.php"]);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("fixing various PHPDoc style issues...\n", Console::BOLD);
        $this->dryRun || Yii::$app->runAction('php-doc/fix', [$frameworkPath]);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("updating PHPDoc @property annotations...\n", Console::BOLD);
        $this->dryRun || Yii::$app->runAction('php-doc/property', [$frameworkPath]);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout('sorting changelogs...', Console::BOLD);
        $this->dryRun || $this->resortChangelogs(['framework'], $version);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout('closing changelogs...', Console::BOLD);
        $this->dryRun || $this->closeChangelogs(['framework'], $version);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout('updating Yii version...');
        $this->dryRun || $this->updateYiiVersion($frameworkPath, $version);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("\nIn the following you can check the above changes using git diff.\n\n");
        do {
            $this->runGit('git diff --color', $frameworkPath);
            $this->stdout("\n\n\nCheck whether the above diff is okay, if not you may change things as needed before continuing.\n");
            $this->stdout("You may abort the program with Ctrl + C and reset the changes by running `git checkout -- .` in the repo.\n\n");
        } while (!$this->confirm('Type `yes` to continue, `no` to view git diff again. Continue?'));

        $this->stdout("\n\n");
        $this->stdout("    ****          RELEASE TIME!         ****\n", Console::FG_YELLOW, Console::BOLD);
        $this->stdout("    ****    Commit, Tag and Push it!    ****\n", Console::FG_YELLOW, Console::BOLD);
        $this->stdout("\n\nHint: if you decide 'no' for any of the following, the command will not be executed. You may manually run them later if needed. E.g. try the release locally without pushing it.\n\n");

        $this->stdout("Make sure to have your git set up for GPG signing. The following tag and commit should be signed.\n\n");

        $this->runGit("git commit -S -a -m \"release version $version\"", $frameworkPath);
        $this->runGit("git tag -s $version -m \"version $version\"", $frameworkPath);
        $this->runGit('git push', $frameworkPath);
        $this->runGit('git push --tags', $frameworkPath);

        $this->stdout("\n\n");
        $this->stdout('CONGRATULATIONS! You have just released ', Console::FG_YELLOW, Console::BOLD);
        $this->stdout('framework', Console::FG_RED, Console::BOLD);
        $this->stdout(' version ', Console::FG_YELLOW, Console::BOLD);
        $this->stdout($version, Console::BOLD);
        $this->stdout("!\n\n", Console::FG_YELLOW, Console::BOLD);

        // TODO release applications
        // $this->composerSetStability($what, $version);

//        $this->resortChangelogs($what, $version);
  //        $this->closeChangelogs($what, $version);
  //        $this->composerSetStability($what, $version);
  //        if (in_array('framework', $what)) {
  //            $this->updateYiiVersion($version);
  //        }

        // if done:
        //     * ./build/build release/done framework 2.0.0-dev 2.0.0-rc
        //     * ./build/build release/done redis 2.0.0-dev 2.0.0-rc
//            $this->openChangelogs($what, $nextVersion);
//            $this->composerSetStability($what, 'dev');
//            if (in_array('framework', $what)) {
//                $this->updateYiiVersion($devVersion);
//            }

        // prepare next release

        $this->stdout("Time to prepare the next release...\n\n", Console::FG_YELLOW, Console::BOLD);

        $this->stdout('opening changelogs...', Console::BOLD);
        $nextVersion = $this->getNextVersions(['framework' => $version], self::PATCH); // TODO support other versions
        $this->dryRun || $this->openChangelogs(['framework'], $nextVersion['framework']);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout('updating Yii version...');
        $this->dryRun || $this->updateYiiVersion($frameworkPath, $nextVersion['framework'] . '-dev');
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("\n");
        $this->runGit('git diff --color', $frameworkPath);
        $this->stdout("\n\n");
        $this->runGit('git commit -a -m "prepare for next release"', $frameworkPath);
        $this->runGit('git push', $frameworkPath);

        $this->stdout("\n\nDONE!", Console::FG_YELLOW, Console::BOLD);

        $this->stdout("\n\nThe following steps are left for you to do manually:\n\n");
        $nextVersion2 = $this->getNextVersions($nextVersion, self::PATCH); // TODO support other versions
        $this->stdout("- wait for your changes to be propagated to the repo and create a tag $version on  https://github.com/yiisoft/yii2-framework\n\n");
        $this->stdout("    git clone git@github.com:yiisoft/yii2-framework.git\n");
        $this->stdout("    cd yii2-framework/\n");
        $this->stdout("    export RELEASECOMMIT=$(git log --oneline |grep $version |grep -Po \"^[0-9a-f]+\")\n");
        $this->stdout("    git tag -s $version -m \"version $version\" \$RELEASECOMMIT\n");
        $this->stdout("    git tag --verify $version\n");
        $this->stdout("    git push --tags\n\n");
        $this->stdout("- close the $version milestone on github and open new ones for {$nextVersion['framework']} and {$nextVersion2['framework']}: https://github.com/yiisoft/yii2/milestones\n");
        $this->stdout("- create a release on github.\n");
        $this->stdout("- release news and announcement.\n");
        $this->stdout("- update the website (will be automated soon and is only relevant for the new website).\n");
        $this->stdout("  https://github.com/yiisoft-contrib/yiiframework.com/blob/master/config/versions.php#L69\n");
        $this->stdout("\n");
        $this->stdout("- release applications: ./build/build release app-basic\n");
        $this->stdout("- release applications: ./build/build release app-advanced\n");

        $this->stdout("\n");
    }

    protected function releaseApplication($name, $path, $version)
    {
        $this->stdout("\n");
        $this->stdout($h = "Preparing release for application  $name  version $version", Console::BOLD);
        $this->stdout("\n" . str_repeat('-', \strlen($h)) . "\n\n", Console::BOLD);

        if (!$this->confirm('Make sure you are on the right branch for this release and that it tracks the correct remote branch! Continue?')) {
            exit(1);
        }
        $this->runGit('git pull', $path);

        // adjustments

        $this->stdout("fixing various PHPDoc style issues...\n", Console::BOLD);
        $this->setAppAliases($name, $path);
        $this->dryRun || Yii::$app->runAction('php-doc/fix', [$path, 'skipFrameworkRequirements' => true]);
        $this->resetAppAliases();
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("updating PHPDoc @property annotations...\n", Console::BOLD);
        $this->setAppAliases($name, $path);
        $this->dryRun || Yii::$app->runAction('php-doc/property', [$path, 'skipFrameworkRequirements' => true]);
        $this->resetAppAliases();
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("updating composer stability...\n", Console::BOLD);
        $this->dryRun || $this->composerSetStability(["app-$name"], $version);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("\nIn the following you can check the above changes using git diff.\n\n");
        do {
            $this->runGit('git diff --color', $path);
            $this->stdout("\n\n\nCheck whether the above diff is okay, if not you may change things as needed before continuing.\n");
            $this->stdout("You may abort the program with Ctrl + C and reset the changes by running `git checkout -- .` in the repo.\n\n");
        } while (!$this->confirm('Type `yes` to continue, `no` to view git diff again. Continue?'));

        $this->stdout("\n\n");
        $this->stdout("    ****          RELEASE TIME!         ****\n", Console::FG_YELLOW, Console::BOLD);
        $this->stdout("    ****    Commit, Tag and Push it!    ****\n", Console::FG_YELLOW, Console::BOLD);
        $this->stdout("\n\nHint: if you decide 'no' for any of the following, the command will not be executed. You may manually run them later if needed. E.g. try the release locally without pushing it.\n\n");

        $this->stdout("Make sure to have your git set up for GPG signing. The following tag and commit should be signed.\n\n");

        $this->runGit("git commit -S -a -m \"release version $version\"", $path);
        $this->runGit("git tag -s $version -m \"version $version\"", $path);
        $this->runGit('git push', $path);
        $this->runGit('git push --tags', $path);

        $this->stdout("\n\n");
        $this->stdout('CONGRATULATIONS! You have just released application ', Console::FG_YELLOW, Console::BOLD);
        $this->stdout($name, Console::FG_RED, Console::BOLD);
        $this->stdout(' version ', Console::FG_YELLOW, Console::BOLD);
        $this->stdout($version, Console::BOLD);
        $this->stdout("!\n\n", Console::FG_YELLOW, Console::BOLD);

        // prepare next release

        $this->stdout("Time to prepare the next release...\n\n", Console::FG_YELLOW, Console::BOLD);

        $this->stdout("updating composer stability...\n", Console::BOLD);
        $this->dryRun || $this->composerSetStability(["app-$name"], 'dev');
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $nextVersion = $this->getNextVersions(["app-$name" => $version], self::PATCH); // TODO support other versions

        $this->stdout("\n");
        $this->runGit('git diff --color', $path);
        $this->stdout("\n\n");
        $this->runGit('git commit -a -m "prepare for next release"', $path);
        $this->runGit('git push', $path);

        $this->stdout("\n\nDONE!", Console::FG_YELLOW, Console::BOLD);

        $this->stdout("\n\nThe following steps are left for you to do manually:\n\n");
        $nextVersion2 = $this->getNextVersions($nextVersion, self::PATCH); // TODO support other versions
        $this->stdout("- close the $version milestone on github and open new ones for {$nextVersion["app-$name"]} and {$nextVersion2["app-$name"]}: https://github.com/yiisoft/yii2-app-$name/milestones\n");
        $this->stdout("- Create Application packages and upload them to framework releast at github:  ./build release/package app-$name\n");

        $this->stdout("\n");
    }

    private $_oldAlias;

    protected function setAppAliases($app, $path)
    {
        $this->_oldAlias = Yii::getAlias('@app');
        switch ($app) {
            case 'basic':
                Yii::setAlias('@app', $path);
                break;
            case 'advanced':
                // setup @frontend, @backend etc...
                require "$path/common/config/bootstrap.php";
                break;
        }
    }

    protected function resetAppAliases()
    {
        Yii::setAlias('@app', $this->_oldAlias);
    }

    protected function packageApplication($name, $version, $packagePath)
    {
        FileHelper::createDirectory($packagePath);

        $this->runCommand("composer create-project yiisoft/yii2-app-$name $name $version", $packagePath);
        // clear cookie validation key in basic app
        if (is_file($configFile = "$packagePath/$name/config/web.php")) {
            $this->sed(
                "/'cookieValidationKey' => '.*?',/",
                "'cookieValidationKey' => '',",
                $configFile
            );
        }
        $this->runCommand("tar zcf yii-$name-app-$version.tgz $name", $packagePath);
    }

    protected function releaseExtension($name, $path, $version)
    {
        $this->stdout("\n");
        $this->stdout($h = "Preparing release for extension  $name  version $version", Console::BOLD);
        $this->stdout("\n" . str_repeat('-', \strlen($h)) . "\n\n", Console::BOLD);

        if (!$this->confirm('Make sure you are on the right branch for this release and that it tracks the correct remote branch! Continue?')) {
            exit(1);
        }
        $this->runGit('git pull', $path);

        // adjustments

        $this->stdout("fixing various PHPDoc style issues...\n", Console::BOLD);
        $this->dryRun || Yii::$app->runAction('php-doc/fix', [$path]);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("updating PHPDoc @property annotations...\n", Console::BOLD);
        $this->dryRun || Yii::$app->runAction('php-doc/property', [$path]);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout('sorting changelogs...', Console::BOLD);
        $this->dryRun || $this->resortChangelogs([$name], $version);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout('closing changelogs...', Console::BOLD);
        $this->dryRun || $this->closeChangelogs([$name], $version);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("\nIn the following you can check the above changes using git diff.\n\n");
        do {
            $this->runGit('git diff --color', $path);
            $this->stdout("\n\n\nCheck whether the above diff is okay, if not you may change things as needed before continuing.\n");
            $this->stdout("You may abort the program with Ctrl + C and reset the changes by running `git checkout -- .` in the repo.\n\n");
        } while (!$this->confirm('Type `yes` to continue, `no` to view git diff again. Continue?'));

        $this->stdout("\n\n");
        $this->stdout("    ****          RELEASE TIME!         ****\n", Console::FG_YELLOW, Console::BOLD);
        $this->stdout("    ****    Commit, Tag and Push it!    ****\n", Console::FG_YELLOW, Console::BOLD);
        $this->stdout("\n\nHint: if you decide 'no' for any of the following, the command will not be executed. You may manually run them later if needed. E.g. try the release locally without pushing it.\n\n");

        $this->stdout("Make sure to have your git set up for GPG signing. The following tag and commit should be signed.\n\n");

        $this->runGit("git commit -S -a -m \"release version $version\"", $path);
        $this->runGit("git tag -s $version -m \"version $version\"", $path);
        $this->runGit('git push', $path);
        $this->runGit('git push --tags', $path);

        $this->stdout("\n\n");
        $this->stdout('CONGRATULATIONS! You have just released extension ', Console::FG_YELLOW, Console::BOLD);
        $this->stdout($name, Console::FG_RED, Console::BOLD);
        $this->stdout(' version ', Console::FG_YELLOW, Console::BOLD);
        $this->stdout($version, Console::BOLD);
        $this->stdout("!\n\n", Console::FG_YELLOW, Console::BOLD);

        // prepare next release

        $this->stdout("Time to prepare the next release...\n\n", Console::FG_YELLOW, Console::BOLD);

        $this->stdout('opening changelogs...', Console::BOLD);
        $nextVersion = $this->getNextVersions([$name => $version], self::PATCH); // TODO support other versions
        $this->dryRun || $this->openChangelogs([$name], $nextVersion[$name]);
        $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD);

        $this->stdout("\n");
        $this->runGit('git diff --color', $path);
        $this->stdout("\n\n");
        $this->runGit('git commit -a -m "prepare for next release"', $path);
        $this->runGit('git push', $path);

        $this->stdout("\n\nDONE!", Console::FG_YELLOW, Console::BOLD);

        $this->stdout("\n\nThe following steps are left for you to do manually:\n\n");
        $nextVersion2 = $this->getNextVersions($nextVersion, self::PATCH); // TODO support other versions
        $this->stdout("- close the $version milestone on github and open new ones for {$nextVersion[$name]} and {$nextVersion2[$name]}: https://github.com/yiisoft/yii2-$name/milestones\n");
        $this->stdout("- release news and announcement.\n");
        $this->stdout("- update the website (will be automated soon and is only relevant for the new website).\n");

        $this->stdout("\n");
    }

    protected function runCommand($cmd, $path)
    {
        $this->stdout("running  $cmd  ...", Console::BOLD);
        if ($this->dryRun) {
            $this->stdout("dry run, command `$cmd` not executed.\n");
            return;
        }
        chdir($path);
        exec($cmd, $output, $ret);
        if ($ret != 0) {
            echo implode("\n", $output);
            throw new Exception("Command \"$cmd\" failed with code " . $ret);
        }
        $this->stdout("\ndone.\n", Console::BOLD, Console::FG_GREEN);
    }

    protected function runGit($cmd, $path)
    {
        if ($this->confirm("Run `$cmd`?", true)) {
            if ($this->dryRun) {
                $this->stdout("dry run, command `$cmd` not executed.\n");
                return;
            }
            chdir($path);
            exec($cmd, $output, $ret);
            echo implode("\n", $output);
            if ($ret != 0) {
                throw new Exception("Command \"$cmd\" failed with code " . $ret);
            }
            echo "\n";
        }
    }

    protected function ensureGitClean($path)
    {
        chdir($path);
        exec('git status --porcelain -uno', $changes, $ret);
        if ($ret != 0) {
            throw new Exception('Command "git status --porcelain -uno" failed with code ' . $ret);
        }
        if (!empty($changes)) {
            throw new Exception("You have uncommitted changes in $path: " . print_r($changes, true));
        }
    }

    protected function gitFetchTags($path)
    {
        try {
            chdir($path);
        } catch (\yii\base\ErrorException $e) {
            throw new Exception('Failed to getch git tags in ' . $path . ': ' . $e->getMessage());
        }
        exec('git fetch --tags', $output, $ret);
        if ($ret != 0) {
            throw new Exception('Command "git fetch --tags" failed with code ' . $ret);
        }
    }

    protected function checkComposer($fwPath)
    {
        if (!$this->confirm("\nNot yet automated: Please check if composer.json dependencies in framework dir match the one in repo root. Continue?", false)) {
            exit;
        }
    }

    protected function closeChangelogs($what, $version)
    {
        $v = str_replace('\\-', '[\\- ]', preg_quote($version, '/'));
        $headline = $version . ' ' . date('F d, Y');
        $this->sed(
            '/' . $v . ' under development\R(-+?)\R/',
            $headline . "\n" . str_repeat('-', \strlen($headline)) . "\n",
            $this->getChangelogs($what)
        );
    }

    protected function openChangelogs($what, $version)
    {
        $headline = "\n$version under development\n";
        $headline .= str_repeat('-', \strlen($headline) - 2) . "\n\n- no changes in this release.\n";
        foreach ($this->getChangelogs($what) as $file) {
            $lines = explode("\n", file_get_contents($file));
            $hl = [
                array_shift($lines),
                array_shift($lines),
            ];
            array_unshift($lines, $headline);

            file_put_contents($file, implode("\n", array_merge($hl, $lines)));
        }
    }

    protected function resortChangelogs($what, $version)
    {
        foreach ($this->getChangelogs($what) as $file) {
            // split the file into relevant parts
            list($start, $changelog, $end) = $this->splitChangelog($file, $version);
            $changelog = $this->resortChangelog($changelog);
            file_put_contents($file, implode("\n", array_merge($start, $changelog, $end)));
        }
    }

    /**
     * Extract changelog content for a specific version.
     * @param string $file
     * @param string $version
     * @return array
     */
    protected function splitChangelog($file, $version)
    {
        $lines = explode("\n", file_get_contents($file));

        // split the file into relevant parts
        $start = [];
        $changelog = [];
        $end = [];

        $state = 'start';
        foreach ($lines as $l => $line) {
            // starting from the changelogs headline
            if (isset($lines[$l - 2]) && strpos($lines[$l - 2], $version) !== false &&
                isset($lines[$l - 1]) && strncmp($lines[$l - 1], '---', 3) === 0) {
                $state = 'changelog';
            }
            if ($state === 'changelog' && isset($lines[$l + 1]) && strncmp($lines[$l + 1], '---', 3) === 0) {
                $state = 'end';
            }
            // add continued lines to the last item to keep them together
            if (!empty(${$state}) && trim($line) !== '' && strncmp($line, '- ', 2) !== 0) {
                end(${$state});
                ${$state}[key(${$state})] .= "\n" . $line;
            } else {
                ${$state}[] = $line;
            }
        }

        return [$start, $changelog, $end];
    }

    /**
     * Ensure sorting of the changelog lines.
     * @param string[] $changelog
     * @return string[]
     */
    protected function resortChangelog($changelog)
    {
        // cleanup whitespace
        foreach ($changelog as $i => $line) {
            $changelog[$i] = rtrim($line);
        }
        $changelog = array_filter($changelog);

        $i = 0;
        ArrayHelper::multisort($changelog, function ($line) use (&$i) {
            if (preg_match('/^- (Chg|Enh|Bug|New)( #\d+(, #\d+)*)?: .+/', $line, $m)) {
                $o = ['Bug' => 'C', 'Enh' => 'D', 'Chg' => 'E', 'New' => 'F'];
                return $o[$m[1]] . ' ' . (!empty($m[2]) ? $m[2] : 'AAAA' . $i++);
            }

            return 'B' . $i++;
        }, SORT_ASC, SORT_NATURAL);

        // re-add leading and trailing lines
        array_unshift($changelog, '');
        $changelog[] = '';
        $changelog[] = '';

        return $changelog;
    }

    protected function getChangelogs($what)
    {
        $changelogs = [];
        if (\in_array('framework', $what)) {
            $changelogs[] = $this->getFrameworkChangelog();
        }

        return array_merge($changelogs, $this->getExtensionChangelogs($what));
    }

    protected function getFrameworkChangelog()
    {
        return $this->basePath . '/framework/CHANGELOG.md';
    }

    protected function getExtensionChangelogs($what)
    {
        return array_filter(glob($this->basePath . '/extensions/*/CHANGELOG.md'), function ($elem) use ($what) {
            foreach ($what as $ext) {
                if (strpos($elem, "extensions/$ext/CHANGELOG.md") !== false) {
                    return true;
                }
            }

            return false;
        });
    }

    protected function composerSetStability($what, $version)
    {
        $apps = [];
        if (\in_array('app-advanced', $what)) {
            $apps[] = $this->basePath . '/apps/advanced/composer.json';
        }
        if (\in_array('app-basic', $what)) {
            $apps[] = $this->basePath . '/apps/basic/composer.json';
        }
        if (\in_array('app-benchmark', $what)) {
            $apps[] = $this->basePath . '/apps/benchmark/composer.json';
        }
        if (empty($apps)) {
            return;
        }

        $stability = 'stable';
        if (strpos($version, 'alpha') !== false) {
            $stability = 'alpha';
        } elseif (strpos($version, 'beta') !== false) {
            $stability = 'beta';
        } elseif (strpos($version, 'rc') !== false) {
            $stability = 'RC';
        } elseif (strpos($version, 'dev') !== false) {
            $stability = 'dev';
        }

        $this->sed(
            '/"minimum-stability": "(.+?)",/',
            '"minimum-stability": "' . $stability . '",',
            $apps
        );
    }

    protected function updateYiiVersion($frameworkPath, $version)
    {
        $this->sed(
            '/function getVersion\(\)\R    \{\R        return \'(.+?)\';/',
            "function getVersion()\n    {\n        return '$version';",
            $frameworkPath . '/BaseYii.php');
    }

    protected function sed($pattern, $replace, $files)
    {
        foreach ((array) $files as $file) {
            file_put_contents($file, preg_replace($pattern, $replace, file_get_contents($file)));
        }
    }

    protected function getCurrentVersions(array $what)
    {
        $versions = [];
        foreach ($what as $ext) {
            if ($ext === 'framework') {
                chdir("{$this->basePath}/framework");
            } elseif (strncmp('app-', $ext, 4) === 0) {
                chdir("{$this->basePath}/apps/" . substr($ext, 4));
            } else {
                chdir("{$this->basePath}/extensions/$ext");
            }
            $tags = [];
            exec('git tag', $tags, $ret);
            if ($ret != 0) {
                throw new Exception('Command "git tag" failed with code ' . $ret);
            }
            rsort($tags, SORT_NATURAL); // TODO this can not deal with alpha/beta/rc...

            // exclude 3.0.0-alpha1 tag
            if (($key = array_search('3.0.0-alpha1', $tags, true)) !== false)
            {
                unset($tags[$key]);
            }

            $versions[$ext] = reset($tags);
        }

        return $versions;
    }

    const MINOR = 'minor';
    const PATCH = 'patch';

    protected function getNextVersions(array $versions, $type)
    {
        foreach ($versions as $k => $v) {
            if (empty($v)) {
                $versions[$k] = '2.0.0';
                continue;
            }
            $parts = explode('.', $v);
            switch ($type) {
                case self::MINOR:
                    $parts[1]++;
                    $parts[2] = 0;
                    if (isset($parts[3])) {
                        unset($parts[3]);
                    }
                    break;
                case self::PATCH:
                    $parts[2]++;
                    if (isset($parts[3])) {
                        unset($parts[3]);
                    }
                    break;
                default:
                    throw new Exception('Unknown version type.');
            }
            $versions[$k] = implode('.', $parts);
        }

        return $versions;
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\build\controllers;

use Yii;
use yii\console\Controller;
use yii\helpers\Console;
use yii\helpers\FileHelper;
use yii\helpers\Json;

/**
 * PhpDocController is there to help maintaining PHPDoc annotation in class files.
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
class PhpDocController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public $defaultAction = 'property';
    /**
     * @var bool whether to update class docs directly. Setting this to false will just output docs
     * for copy and paste.
     */
    public $updateFiles = true;
    /**
     * @var bool whether to add copyright header to php files. This should be skipped in application code.
     */
    public $skipFrameworkRequirements = false;

    /**
     * Generates `@property` annotations in class files from getters and setters.
     *
     * Property description will be taken from getter or setter or from an `@property` annotation
     * in the getters docblock if there is one defined.
     *
     * See https://github.com/yiisoft/yii2/wiki/Core-framework-code-style#documentation for details.
     *
     * @param string $root the directory to parse files from. Defaults to YII2_PATH.
     */
    public function actionProperty($root = null)
    {
        $files = $this->findFiles($root);

        $nFilesTotal = 0;
        $nFilesUpdated = 0;
        foreach ($files as $file) {
            $result = $this->generateClassPropertyDocs($file);
            if ($result !== false) {
                list($className, $phpdoc) = $result;
                if ($this->updateFiles) {
                    if ($this->updateClassPropertyDocs($file, $className, $phpdoc)) {
                        $nFilesUpdated++;
                    }
                } elseif (!empty($phpdoc)) {
                    $this->stdout("\n[ " . $file . " ]\n\n", Console::BOLD);
                    $this->stdout($phpdoc);
                }
            }
            $nFilesTotal++;
        }

        $this->stdout("\nParsed $nFilesTotal files.\n");
        $this->stdout("Updated $nFilesUpdated files.\n");
    }

    /**
     * Fix some issues with PHPDoc in files.
     *
     * @param string $root the directory to parse files from. Defaults to YII2_PATH.
     */
    public function actionFix($root = null)
    {
        $files = $this->findFiles($root, false);

        $nFilesTotal = 0;
        $nFilesUpdated = 0;
        foreach ($files as $file) {
            $contents = file_get_contents($file);
            $hash = $this->hash($contents);

            // fix line endings
            $lines = preg_split('/(\r\n|\n|\r)/', $contents);

            if (!$this->skipFrameworkRequirements) {
                $this->fixFileDoc($lines);
            }
            $this->fixDocBlockIndentation($lines);
            $lines = array_values($this->fixLineSpacing($lines));

            $newContent = implode("\n", $lines);
            if ($hash !== $this->hash($newContent)) {
                file_put_contents($file, $newContent);
                $nFilesUpdated++;
            }
            $nFilesTotal++;
        }

        $this->stdout("\nParsed $nFilesTotal files.\n");
        $this->stdout("Updated $nFilesUpdated files.\n");
    }

    /**
     * {@inheritdoc}
     */
    public function options($actionID)
    {
        return array_merge(parent::options($actionID), ['updateFiles', 'skipFrameworkRequirements']);
    }

    /**
     * @param string $root
     * @param bool $needsInclude
     * @return array list of files.
     */
    protected function findFiles($root, $needsInclude = true)
    {
        $except = [];
        if ($needsInclude) {
            $extensionExcept = [
                'apidoc' => [
                    '/helpers/PrettyPrinter.php',
                    '/extensions/apidoc/helpers/ApiIndexer.php',
                    '/extensions/apidoc/helpers/ApiMarkdownLaTeX.php',
                ],
                'codeception' => [
                    '/TestCase.php',
                    '/DbTestCase.php',
                ],
                'gii' => [
                    '/components/DiffRendererHtmlInline.php',
                    '/generators/extension/default/AutoloadExample.php',
                ],
                'swiftmailer' => [
                    'src/Logger.php',
                ],
                'twig' => [
                    '/Extension.php',
                    '/Optimizer.php',
                    '/Template.php',
                    '/TwigSimpleFileLoader.php',
                    '/ViewRendererStaticClassProxy.php',
                ],
            ];
        } else {
            $extensionExcept = [];
        }

        if ($root === null) {
            $root = \dirname(YII2_PATH);
            $extensionPath = "$root/extensions";
            $this->setUpExtensionAliases($extensionPath);

            $except = [
                '/apps/',
                '/build/',
                '/docs/',
                '/extensions/composer/',
                '/framework/BaseYii.php',
                '/framework/Yii.php',
                'assets/',
                'tests/',
                'vendor/',
            ];
            foreach ($extensionExcept as $ext => $paths) {
                foreach ($paths as $path) {
                    $except[] = "/extensions/$ext$path";
                }
            }
        } elseif (preg_match('~extensions/([\w-]+)[\\\\/]?$~', $root, $matches)) {
            $extensionPath = \dirname(rtrim($root, '\\/'));
            $this->setUpExtensionAliases($extensionPath);

            list(, $extension) = $matches;
            Yii::setAlias("@yii/$extension", (string)$root);
            if (is_file($autoloadFile = Yii::getAlias("@yii/$extension/vendor/autoload.php"))) {
                include $autoloadFile;
            }

            if (isset($extensionExcept[$extension])) {
                foreach ($extensionExcept[$extension] as $path) {
                    $except[] = $path;
                }
            }
            $except[] = '/vendor/';
            $except[] = '/tests/';
            $except[] = '/docs/';

//            // composer extension does not contain yii code
//            if ($extension === 'composer') {
//                return [];
//            }
        } elseif (preg_match('~apps/([\w-]+)[\\\\/]?$~', $root, $matches)) {
            $extensionPath = \dirname(\dirname(rtrim($root, '\\/'))) . '/extensions';
            $this->setUpExtensionAliases($extensionPath);

            list(, $appName) = $matches;
            Yii::setAlias("@app-$appName", (string)$root);
            if (is_file($autoloadFile = Yii::getAlias("@app-$appName/vendor/autoload.php"))) {
                include $autoloadFile;
            }

            $except[] = '/runtime/';
            $except[] = '/vendor/';
            $except[] = '/tests/';
            $except[] = '/docs/';
        }
        $root = FileHelper::normalizePath($root);
        $options = [
            'filter' => function ($path) {
                if (is_file($path)) {
                    $file = basename($path);
                    if ($file[0] < 'A' || $file[0] > 'Z') {
                        return false;
                    }
                }

                return null;
            },
            'only' => ['*.php'],
            'except' => array_merge($except, [
                '.git/',
                'views/',
                'requirements/',
                'gii/generators/',
                'vendor/',
            ]),
        ];

        return FileHelper::findFiles($root, $options);
    }

    /**
     * @param string $extensionPath root path containing extension repositories.
     */
    private function setUpExtensionAliases($extensionPath)
    {
        foreach (scandir($extensionPath) as $extension) {
            if (ctype_alpha($extension) && is_dir($extensionPath . '/' . $extension)) {
                Yii::setAlias("@yii/$extension", "$extensionPath/$extension");

                $composerConfigFile = $extensionPath . '/' . $extension . '/composer.json';
                if (file_exists($composerConfigFile)) {
                    $composerConfig = Json::decode(file_get_contents($composerConfigFile));
                    if (isset($composerConfig['autoload']['psr-4'])) {
                        foreach ($composerConfig['autoload']['psr-4'] as $namespace => $subPath) {
                            $alias = '@' . str_replace('\\', '/', $namespace);
                            $path = rtrim("$extensionPath/$extension/$subPath", '/');
                            Yii::setAlias($alias, $path);
                        }
                    }
                }
            }
        }
    }

    /**
     * Fix file PHPDoc.
     */
    protected function fixFileDoc(&$lines)
    {
        // find namespace
        $namespace = false;
        $namespaceLine = '';
        $contentAfterNamespace = false;
        foreach ($lines as $i => $line) {
            $line = trim($line);
            if (!empty($line)) {
                if (strncmp($line, 'namespace', 9) === 0) {
                    $namespace = $i;
                    $namespaceLine = $line;
                } elseif ($namespace !== false) {
                    $contentAfterNamespace = $i;
                    break;
                }
            }
        }

        if ($namespace !== false && $contentAfterNamespace !== false) {
            while ($contentAfterNamespace > 0) {
                array_shift($lines);
                $contentAfterNamespace--;
            }
            $lines = array_merge([
                '<?php',
                '/**',
                ' * @link http://www.yiiframework.com/',
                ' * @copyright Copyright (c) 2008 Yii Software LLC',
                ' * @license http://www.yiiframework.com/license/',
                ' */',
                '',
                $namespaceLine,
                '',
            ], $lines);
        }
    }

    /**
     * Markdown aware fix of whitespace issues in doc comments.
     * @param array $lines
     */
    protected function fixDocBlockIndentation(&$lines)
    {
        $docBlock = false;
        $codeBlock = false;
        $listIndent = '';
        $tag = false;
        $indent = '';
        foreach ($lines as $i => $line) {
            if (preg_match('~^(\s*)/\*\*$~', $line, $matches)) {
                $docBlock = true;
                $indent = $matches[1];
            } elseif (preg_match('~^(\s*)\*+/~', $line)) {
                if ($docBlock) { // could be the end of normal comment
                    $lines[$i] = $indent . ' */';
                }
                $docBlock = false;
                $codeBlock = false;
                $listIndent = '';
                $tag = false;
            } elseif ($docBlock) {
                $line = ltrim($line);
                if (isset($line[0]) && $line[0] === '*') {
                    $line = substr($line, 1);
                }
                if (isset($line[0]) && $line[0] === ' ') {
                    $line = substr($line, 1);
                }
                $docLine = str_replace("\t", '    ', rtrim($line));
                if (empty($docLine)) {
                    $listIndent = '';
                } elseif ($docLine[0] === '@') {
                    $listIndent = '';
                    $codeBlock = false;
                    $tag = true;
                    $docLine = preg_replace('/\s+/', ' ', $docLine);
                    $docLine = $this->fixParamTypes($docLine);
                } elseif (preg_match('/^(~~~|```)/', $docLine)) {
                    $codeBlock = !$codeBlock;
                    $listIndent = '';
                } elseif (preg_match('/^(\s*)([0-9]+\.|-|\*|\+) /', $docLine, $matches)) {
                    $listIndent = str_repeat(' ', \strlen($matches[0]));
                    $tag = false;
                    $lines[$i] = $indent . ' * ' . $docLine;
                    continue;
                }
                if ($codeBlock) {
                    $lines[$i] = rtrim($indent . ' * ' . $docLine);
                } else {
                    $lines[$i] = rtrim($indent . ' * ' . (empty($listIndent) && !$tag ? $docLine : ($listIndent . ltrim($docLine))));
                }
            }
        }
    }

    /**
     * @param string $line
     * @return string
     */
    protected function fixParamTypes($line)
    {
        return preg_replace_callback('~@(param|return) ([\w\\|]+)~i', function ($matches) {
            $types = explode('|', $matches[2]);
            foreach ($types as $i => $type) {
                switch ($type) {
                    case 'integer': $types[$i] = 'int'; break;
                    case 'boolean': $types[$i] = 'bool'; break;
                }
            }

            return '@' . $matches[1] . ' ' . implode('|', $types);
        }, $line);
    }

    /**
     * Fixes line spacing code style for properties and constants.
     * @param string[] $lines
     * @return string[]
     */
    protected function fixLineSpacing($lines)
    {
        $propertiesOnly = false;
        // remove blank lines between properties
        $skip = true;
        $level = 0;
        foreach ($lines as $i => $line) {
            if (strpos($line, 'class ') !== false) {
                $skip = false;
            }
            if ($skip) {
                continue;
            }

            // keep spaces in multi line arrays
            if (strpos($line, '*') === false && strncmp(trim($line), "'SQLSTATE[", 10) !== 0) {
                $level += substr_count($line, '[') - substr_count($line, ']');
            }

            if (trim($line) === '') {
                if ($level == 0) {
                    unset($lines[$i]);
                }
            } elseif (ltrim($line)[0] !== '*' && strpos($line, 'function ') !== false) {
                break;
            } elseif (trim($line) === '}') {
                $propertiesOnly = true;
                break;
            }
        }
        $lines = array_values($lines);

        // add back some
        $endofUse = false;
        $endofConst = false;
        $endofPublic = false;
        $endofProtected = false;
        $endofPrivate = false;
        $skip = true;
        $level = 0; // track array properties
        $property = '';
        foreach ($lines as $i => $line) {
            if (strpos($line, 'class ') !== false) {
                $skip = false;
            }
            if ($skip) {
                continue;
            }

            // check for multi line array
            if ($level > 0) {
                ${'endof' . $property} = $i;
            }

            $line = trim($line);
            if (strncmp($line, 'public $', 8) === 0 || strncmp($line, 'public static $', 15) === 0) {
                $endofPublic = $i;
                $property = 'Public';
                $level = 0;
            } elseif (strncmp($line, 'protected $', 11) === 0 || strncmp($line, 'protected static $', 18) === 0) {
                $endofProtected = $i;
                $property = 'Protected';
                $level = 0;
            } elseif (strncmp($line, 'private $', 9) === 0 || strncmp($line, 'private static $', 16) === 0) {
                $endofPrivate = $i;
                $property = 'Private';
                $level = 0;
            } elseif (substr($line, 0, 6) === 'const ') {
                $endofConst = $i;
                $property = false;
            } elseif (substr($line, 0, 4) === 'use ') {
                $endofUse = $i;
                $property = false;
            } elseif (!empty($line) && $line[0] === '*') {
                $property = false;
            } elseif (!empty($line) && $line[0] !== '*' && strpos($line, 'function ') !== false || $line === '}') {
                break;
            }

            // check for multi line array
            if ($property !== false && strncmp($line, "'SQLSTATE[", 10) !== 0) {
                $level += substr_count($line, '[') - substr_count($line, ']');
            }
        }

        $endofAll = false;
        foreach (['Private', 'Protected', 'Public', 'Const', 'Use'] as $var) {
            if (${'endof' . $var} !== false) {
                $endofAll = ${'endof' . $var};
                break;
            }
        }

//        $this->checkPropertyOrder($lineInfo);
        $result = [];
        foreach ($lines as $i => $line) {
            $result[] = $line;
            if (!($propertiesOnly && $i === $endofAll)) {
                if ($i === $endofUse || $i === $endofConst || $i === $endofPublic ||
                    $i === $endofProtected || $i === $endofPrivate) {
                    $result[] = '';
                }
                if ($i === $endofAll) {
                    $result[] = '';
                }
            }
        }

        return $result;
    }

    protected function checkPropertyOrder($lineInfo)
    {
        // TODO
    }

    protected function updateClassPropertyDocs($file, $className, $propertyDoc)
    {
        try {
            $ref = new \ReflectionClass($className);
        } catch (\Exception $e) {
            $this->stderr("[ERR] Unable to create ReflectionClass for class '$className': " . $e->getMessage() . "\n", Console::FG_RED);
            return false;
        }
        if ($ref->getFileName() != $file) {
            $this->stderr("[ERR] Unable to create ReflectionClass for class: $className loaded class is not from file: $file\n", Console::FG_RED);
            return false;
        }

        if ($this->isBaseObject($className, $ref)) {
            $this->stderr("[INFO] Skipping class $className as it is not a subclass of yii\\base\\BaseObject.\n", Console::FG_BLUE, Console::BOLD);
            return false;
        }

        if ($ref->isSubclassOf('yii\db\BaseActiveRecord')) {
            $this->stderr("[INFO] Skipping class $className as it is an ActiveRecord class, property handling is not supported yet.\n", Console::FG_BLUE, Console::BOLD);
            return false;
        }

        $oldDoc = $ref->getDocComment();
        $newDoc = $this->cleanDocComment($this->updateDocComment($oldDoc, $propertyDoc));

        $seenSince = false;
        $seenAuthor = false;

        // TODO move these checks to different action
        $lines = explode("\n", $newDoc);
        $firstLine = trim($lines[1]);
        if ($firstLine === '*' || strncmp($firstLine, '* @', 3) === 0) {
            $this->stderr("[WARN] Class $className has no short description.\n", Console::FG_YELLOW, Console::BOLD);
        }
        foreach ($lines as $line) {
            $line = trim($line);
            if (strncmp($line, '* @since ', 9) === 0) {
                $seenSince = true;
            } elseif (strncmp($line, '* @author ', 10) === 0) {
                $seenAuthor = true;
            }
        }

        if (!$this->skipFrameworkRequirements) {
            if (!$seenSince) {
                $this->stderr("[ERR] No @since found in class doc in file: $file\n", Console::FG_RED);
            }
            if (!$seenAuthor) {
                $this->stderr("[ERR] No @author found in class doc in file: $file\n", Console::FG_RED);
            }
        }

        if (trim($oldDoc) != trim($newDoc)) {
            $fileContent = explode("\n", file_get_contents($file));
            $start = $ref->getStartLine() - 2;
            $docStart = $start - \count(explode("\n", $oldDoc)) + 1;

            $newFileContent = [];
            $n = \count($fileContent);
            for ($i = 0; $i < $n; $i++) {
                if ($i > $start || $i < $docStart) {
                    $newFileContent[] = $fileContent[$i];
                } else {
                    $newFileContent[] = trim($newDoc);
                    $i = $start;
                }
            }

            file_put_contents($file, implode("\n", $newFileContent));

            return true;
        }

        return false;
    }

    /**
     * remove multi empty lines and trim trailing whitespace.
     *
     * @param $doc
     * @return string
     */
    protected function cleanDocComment($doc)
    {
        $lines = explode("\n", $doc);
        $n = \count($lines);
        for ($i = 0; $i < $n; $i++) {
            $lines[$i] = rtrim($lines[$i]);
            if (trim($lines[$i]) == '*' && trim($lines[$i + 1]) == '*') {
                unset($lines[$i]);
            }
        }

        return implode("\n", $lines);
    }

    /**
     * Replace property annotations in doc comment.
     * @param $doc
     * @param $properties
     * @return string
     */
    protected function updateDocComment($doc, $properties)
    {
        $lines = explode("\n", $doc);
        $propertyPart = false;
        $propertyPosition = false;
        foreach ($lines as $i => $line) {
            $line = trim($line);
            if (strncmp($line, '* @property ', 12) === 0) {
                $propertyPart = true;
            } elseif ($propertyPart && $line == '*') {
                $propertyPosition = $i;
                $propertyPart = false;
            }
            if (strncmp($line, '* @author ', 10) === 0 && $propertyPosition === false) {
                $propertyPosition = $i - 1;
                $propertyPart = false;
            }
            if ($propertyPart) {
                unset($lines[$i]);
            }
        }

        // if no properties or other tags where present add properties at the end
        if ($propertyPosition === false) {
            $propertyPosition = \count($lines) - 2;
        }

        $finalDoc = '';
        foreach ($lines as $i => $line) {
            $finalDoc .= $line . "\n";
            if ($i == $propertyPosition) {
                $finalDoc .= $properties;
            }
        }

        return $finalDoc;
    }

    protected function generateClassPropertyDocs($fileName)
    {
        $phpdoc = '';
        $file = str_replace("\r", '', str_replace("\t", ' ', file_get_contents($fileName, true)));
        $ns = $this->match('#\nnamespace (?<name>[\w\\\\]+);\n#', $file);
        $namespace = reset($ns);
        $namespace = $namespace['name'];
        $classes = $this->match('#\n(?:abstract )(?:final )?class (?<name>\w+)( extends .+)?( implements .+)?\n\{(?<content>.*)\n\}(\n|$)#', $file);

        if (\count($classes) > 1) {
            $this->stderr("[ERR] There should be only one class in a file: $fileName\n", Console::FG_RED);

            return false;
        }
        if (\count($classes) < 1) {
            $interfaces = $this->match('#\ninterface (?<name>\w+)( extends .+)?\n\{(?<content>.*)\n\}(\n|$)#', $file);
            if (\count($interfaces) == 1) {
                return false;
            }

            if (\count($interfaces) > 1) {
                $this->stderr("[ERR] There should be only one interface in a file: $fileName\n", Console::FG_RED);
            } else {
                $traits = $this->match('#\ntrait (?<name>\w+)\n\{(?<content>.*)\n\}(\n|$)#', $file);
                if (\count($traits) == 1) {
                    return false;
                }

                if (\count($traits) > 1) {
                    $this->stderr("[ERR] There should be only one class/trait/interface in a file: $fileName\n", Console::FG_RED);
                } else {
                    $this->stderr("[ERR] No class in file: $fileName\n", Console::FG_RED);
                }
            }

            return false;
        }

        $className = null;
        foreach ($classes as &$class) {
            $className = $namespace . '\\' . $class['name'];

            $gets = $this->match(
                '#\* @return (?<type>[\w\\|\\\\\\[\\]]+)(?: (?<comment>(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' .
                '[\s\n]{2,}public function (?<kind>get)(?<name>\w+)\((?:,? ?\$\w+ ?= ?[^,]+)*\)#',
                $class['content'], true);
            $sets = $this->match(
                '#\* @param (?<type>[\w\\|\\\\\\[\\]]+) \$\w+(?: (?<comment>(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' .
                '[\s\n]{2,}public function (?<kind>set)(?<name>\w+)\(\$\w+(?:, ?\$\w+ ?= ?[^,]+)*\)#',
                $class['content'], true);
            // check for @property annotations in getter and setter
            $properties = $this->match(
                '#\* @(?<kind>property) (?<type>[\w\\|\\\\\\[\\]]+)(?: (?<comment>(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' .
                '[\s\n]{2,}public function [g|s]et(?<name>\w+)\(((?:,? ?\$\w+ ?= ?[^,]+)*|\$\w+(?:, ?\$\w+ ?= ?[^,]+)*)\)#',
                $class['content']);
            $acrs = array_merge($properties, $gets, $sets);

            $props = [];
            foreach ($acrs as &$acr) {
                $acr['name'] = lcfirst($acr['name']);
                $acr['comment'] = trim(preg_replace('#(^|\n)\s+\*\s?#', '$1 * ', $acr['comment']));
                $props[$acr['name']][$acr['kind']] = [
                    'type' => $acr['type'],
                    'comment' => $this->fixSentence($acr['comment']),
                ];
            }

            ksort($props);

            if (\count($props) > 0) {
                $phpdoc .= " *\n";
                foreach ($props as $propName => &$prop) {
                    $docline = ' * @';
                    $docline .= 'property'; // Do not use property-read and property-write as few IDEs support complex syntax.
                    $note = '';
                    if (isset($prop['get'], $prop['set'])) {
                        if ($prop['get']['type'] != $prop['set']['type']) {
                            $note = ' Note that the type of this property differs in getter and setter.'
                                  . ' See [[get' . ucfirst($propName) . '()]] and [[set' . ucfirst($propName) . '()]] for details.';
                        }
                    } elseif (isset($prop['get'])) {
                        if (!$this->hasSetterInParents($className, $propName)) {
                            $note = ' This property is read-only.';
                            //$docline .= '-read';
                        }
                    } elseif (isset($prop['set'])) {
                        if (!$this->hasGetterInParents($className, $propName)) {
                            $note = ' This property is write-only.';
                            //$docline .= '-write';
                        }
                    } else {
                        continue;
                    }
                    $docline .= ' ' . $this->getPropParam($prop, 'type') . " $$propName ";
                    $comment = explode("\n", $this->getPropParam($prop, 'comment') . $note);
                    foreach ($comment as &$cline) {
                        $cline = ltrim($cline, '* ');
                    }
                    $docline = wordwrap($docline . implode(' ', $comment), 110, "\n * ") . "\n";

                    $phpdoc .= $docline;
                }
                $phpdoc .= " *\n";
            }
        }

        return [$className, $phpdoc];
    }

    protected function match($pattern, $subject, $split = false)
    {
        $sets = [];
        // split subject by double newlines because regex sometimes has problems with matching
        // in the complete set of methods
        // example: yii\di\ServiceLocator setComponents() is not recognized in the whole but in
        // a part of the class.
        $parts = $split ? explode("\n\n", $subject) : [$subject];
        foreach ($parts as $part) {
            preg_match_all($pattern . 'suU', $part, $matches, PREG_SET_ORDER);
            foreach ($matches as &$set) {
                foreach ($set as $i => $match) {
                    if (is_numeric($i) /*&& $i != 0*/) {
                        unset($set[$i]);
                    }
                }

                $sets[] = $set;
            }
        }

        return $sets;
    }

    protected function fixSentence($str)
    {
        // TODO fix word wrap
        if ($str == '') {
            return '';
        }

        return strtoupper(substr($str, 0, 1)) . substr($str, 1) . ($str[\strlen($str) - 1] != '.' ? '.' : '');
    }

    protected function getPropParam($prop, $param)
    {
        return isset($prop['property']) ? $prop['property'][$param] : (isset($prop['get']) ? $prop['get'][$param] : $prop['set'][$param]);
    }

    /**
     * Generate a hash value (message digest)
     * @param string $string message to be hashed.
     * @return string calculated message digest.
     */
    private function hash($string)
    {
        if (!function_exists('hash')) {
            return sha1($string);
        }
        return hash('sha256', $string);
    }

    /**
     * @param string $className
     * @param string $propName
     * @return bool
     */
    protected function hasGetterInParents($className, $propName)
    {
        $class = $className;
        while ($parent = get_parent_class($class)) {
            if (method_exists($parent, 'get' . ucfirst($propName))) {
                return true;
            }
            $class = $parent;
        }
        return false;
    }

    /**
     * @param string $className
     * @param string $propName
     * @return bool
     */
    protected function hasSetterInParents($className, $propName)
    {
        $class = $className;
        while ($parent = get_parent_class($class)) {
            if (method_exists($parent, 'set' . ucfirst($propName))) {
                return true;
            }
            $class = $parent;
        }
        return false;
    }

    /**
     * @param string $className
     * @param \ReflectionClass $ref
     * @return bool
     */
    protected function isBaseObject($className, \ReflectionClass $ref)
    {
        $isDepreceatedObject = false;
        if (PHP_VERSION_ID <= 70100) {
            $isDepreceatedObject = $ref->isSubclassOf('yii\base\Object') || $className === 'yii\base\Object';
        }
        return !$isDepreceatedObject && !$ref->isSubclassOf('yii\base\BaseObject') && $className !== 'yii\base\BaseObject';
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\db\oci;

use yii\base\InvalidArgumentException;
use yii\db\Connection;
use yii\db\Constraint;
use yii\db\Exception;
use yii\db\Expression;
use yii\db\Query;
use yii\helpers\StringHelper;
use yii\db\ExpressionInterface;

/**
 * QueryBuilder is the query builder for Oracle databases.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class QueryBuilder extends \yii\db\QueryBuilder
{
    /**
     * @var array mapping from abstract column types (keys) to physical column types (values).
     */
    public $typeMap = [
        Schema::TYPE_PK => 'NUMBER(10) NOT NULL PRIMARY KEY',
        Schema::TYPE_UPK => 'NUMBER(10) UNSIGNED NOT NULL PRIMARY KEY',
        Schema::TYPE_BIGPK => 'NUMBER(20) NOT NULL PRIMARY KEY',
        Schema::TYPE_UBIGPK => 'NUMBER(20) UNSIGNED NOT NULL PRIMARY KEY',
        Schema::TYPE_CHAR => 'CHAR(1)',
        Schema::TYPE_STRING => 'VARCHAR2(255)',
        Schema::TYPE_TEXT => 'CLOB',
        Schema::TYPE_TINYINT => 'NUMBER(3)',
        Schema::TYPE_SMALLINT => 'NUMBER(5)',
        Schema::TYPE_INTEGER => 'NUMBER(10)',
        Schema::TYPE_BIGINT => 'NUMBER(20)',
        Schema::TYPE_FLOAT => 'NUMBER',
        Schema::TYPE_DOUBLE => 'NUMBER',
        Schema::TYPE_DECIMAL => 'NUMBER',
        Schema::TYPE_DATETIME => 'TIMESTAMP',
        Schema::TYPE_TIMESTAMP => 'TIMESTAMP',
        Schema::TYPE_TIME => 'TIMESTAMP',
        Schema::TYPE_DATE => 'DATE',
        Schema::TYPE_BINARY => 'BLOB',
        Schema::TYPE_BOOLEAN => 'NUMBER(1)',
        Schema::TYPE_MONEY => 'NUMBER(19,4)',
    ];

    /**
     * {@inheritdoc}
     */
    protected function defaultExpressionBuilders()
    {
        return array_merge(parent::defaultExpressionBuilders(), [
            'yii\db\conditions\InCondition' => 'yii\db\oci\conditions\InConditionBuilder',
            'yii\db\conditions\LikeCondition' => 'yii\db\oci\conditions\LikeConditionBuilder',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
    {
        $orderBy = $this->buildOrderBy($orderBy);
        if ($orderBy !== '') {
            $sql .= $this->separator . $orderBy;
        }

        $filters = [];
        if ($this->hasOffset($offset)) {
            $filters[] = 'rowNumId > ' . $offset;
        }
        if ($this->hasLimit($limit)) {
            $filters[] = 'rownum <= ' . $limit;
        }
        if (empty($filters)) {
            return $sql;
        }

        $filter = implode(' AND ', $filters);
        return <<<EOD
WITH USER_SQL AS ($sql),
    PAGINATION AS (SELECT USER_SQL.*, rownum as rowNumId FROM USER_SQL)
SELECT *
FROM PAGINATION
WHERE $filter
EOD;
    }

    /**
     * Builds a SQL statement for renaming a DB table.
     *
     * @param string $table the table to be renamed. The name will be properly quoted by the method.
     * @param string $newName the new table name. The name will be properly quoted by the method.
     * @return string the SQL statement for renaming a DB table.
     */
    public function renameTable($table, $newName)
    {
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' RENAME TO ' . $this->db->quoteTableName($newName);
    }

    /**
     * Builds a SQL statement for changing the definition of a column.
     *
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
     * @param string $type the new column type. The [[getColumnType]] method will be invoked to convert abstract column type (if any)
     * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
     * @return string the SQL statement for changing the definition of a column.
     */
    public function alterColumn($table, $column, $type)
    {
        $type = $this->getColumnType($type);

        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' MODIFY ' . $this->db->quoteColumnName($column) . ' ' . $this->getColumnType($type);
    }

    /**
     * Builds a SQL statement for dropping an index.
     *
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
     * @return string the SQL statement for dropping an index.
     */
    public function dropIndex($name, $table)
    {
        return 'DROP INDEX ' . $this->db->quoteTableName($name);
    }

    /**
     * {@inheritdoc}
     */
    public function executeResetSequence($table, $value = null)
    {
        $tableSchema = $this->db->getTableSchema($table);
        if ($tableSchema === null) {
            throw new InvalidArgumentException("Unknown table: $table");
        }
        if ($tableSchema->sequenceName === null) {
            throw new InvalidArgumentException("There is no sequence associated with table: $table");
        }

        if ($value !== null) {
            $value = (int) $value;
        } else {
            if (count($tableSchema->primaryKey)>1) {
                throw new InvalidArgumentException("Can't reset sequence for composite primary key in table: $table");
            }
            // use master connection to get the biggest PK value
            $value = $this->db->useMaster(function (Connection $db) use ($tableSchema) {
                return $db->createCommand(
                    'SELECT MAX("' . $tableSchema->primaryKey[0] . '") FROM "'. $tableSchema->name . '"'
                )->queryScalar();
            }) + 1;
        }

        //Oracle needs at least two queries to reset sequence (see adding transactions and/or use alter method to avoid grants' issue?)
        $this->db->createCommand('DROP SEQUENCE "' . $tableSchema->sequenceName . '"')->execute();
        $this->db->createCommand('CREATE SEQUENCE "' . $tableSchema->sequenceName . '" START WITH ' . $value
            . ' INCREMENT BY 1 NOMAXVALUE NOCACHE')->execute();
    }

    /**
     * {@inheritdoc}
     */
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
    {
        $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
            . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
            . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
            . ' REFERENCES ' . $this->db->quoteTableName($refTable)
            . ' (' . $this->buildColumns($refColumns) . ')';
        if ($delete !== null) {
            $sql .= ' ON DELETE ' . $delete;
        }
        if ($update !== null) {
            throw new Exception('Oracle does not support ON UPDATE clause.');
        }

        return $sql;
    }

    /**
     * {@inheritdoc}
     */
    protected function prepareInsertValues($table, $columns, $params = [])
    {
        list($names, $placeholders, $values, $params) = parent::prepareInsertValues($table, $columns, $params);
        if (!$columns instanceof Query && empty($names)) {
            $tableSchema = $this->db->getSchema()->getTableSchema($table);
            if ($tableSchema !== null) {
                $columns = !empty($tableSchema->primaryKey) ? $tableSchema->primaryKey : [reset($tableSchema->columns)->name];
                foreach ($columns as $name) {
                    $names[] = $this->db->quoteColumnName($name);
                    $placeholders[] = 'DEFAULT';
                }
            }
        }
        return [$names, $placeholders, $values, $params];
    }

    /**
     * {@inheritdoc}
     * @see https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606
     */
    public function upsert($table, $insertColumns, $updateColumns, &$params)
    {
        /** @var Constraint[] $constraints */
        list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
        if (empty($uniqueNames)) {
            return $this->insert($table, $insertColumns, $params);
        }

        $onCondition = ['or'];
        $quotedTableName = $this->db->quoteTableName($table);
        foreach ($constraints as $constraint) {
            $constraintCondition = ['and'];
            foreach ($constraint->columnNames as $name) {
                $quotedName = $this->db->quoteColumnName($name);
                $constraintCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
            }
            $onCondition[] = $constraintCondition;
        }
        $on = $this->buildCondition($onCondition, $params);
        list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
        if (!empty($placeholders)) {
            $usingSelectValues = [];
            foreach ($insertNames as $index => $name) {
                $usingSelectValues[$name] = new Expression($placeholders[$index]);
            }
            $usingSubQuery = (new Query())
                ->select($usingSelectValues)
                ->from('DUAL');
            list($usingValues, $params) = $this->build($usingSubQuery, $params);
        }
        $mergeSql = 'MERGE INTO ' . $this->db->quoteTableName($table) . ' '
            . 'USING (' . (isset($usingValues) ? $usingValues : ltrim($values, ' ')) . ') "EXCLUDED" '
            . "ON ($on)";
        $insertValues = [];
        foreach ($insertNames as $name) {
            $quotedName = $this->db->quoteColumnName($name);
            if (strrpos($quotedName, '.') === false) {
                $quotedName = '"EXCLUDED".' . $quotedName;
            }
            $insertValues[] = $quotedName;
        }
        $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')'
            . ' VALUES (' . implode(', ', $insertValues) . ')';
        if ($updateColumns === false) {
            return "$mergeSql WHEN NOT MATCHED THEN $insertSql";
        }

        if ($updateColumns === true) {
            $updateColumns = [];
            foreach ($updateNames as $name) {
                $quotedName = $this->db->quoteColumnName($name);
                if (strrpos($quotedName, '.') === false) {
                    $quotedName = '"EXCLUDED".' . $quotedName;
                }
                $updateColumns[$name] = new Expression($quotedName);
            }
        }
        list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
        $updateSql = 'UPDATE SET ' . implode(', ', $updates);
        return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql";
    }

    /**
     * Generates a batch INSERT SQL statement.
     *
     * For example,
     *
     * ```php
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
     *     ['Tom', 30],
     *     ['Jane', 20],
     *     ['Linda', 25],
     * ]);
     * ```
     *
     * Note that the values in each row must match the corresponding column names.
     *
     * @param string $table the table that new rows will be inserted into.
     * @param array $columns the column names
     * @param array|\Generator $rows the rows to be batch inserted into the table
     * @return string the batch INSERT SQL statement
     */
    public function batchInsert($table, $columns, $rows, &$params = [])
    {
        if (empty($rows)) {
            return '';
        }

        $schema = $this->db->getSchema();
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
            $columnSchemas = $tableSchema->columns;
        } else {
            $columnSchemas = [];
        }

        $values = [];
        foreach ($rows as $row) {
            $vs = [];
            foreach ($row as $i => $value) {
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
                }
                if (is_string($value)) {
                    $value = $schema->quoteValue($value);
                } elseif (is_float($value)) {
                    // ensure type cast always has . as decimal separator in all locales
                    $value = StringHelper::floatToString($value);
                } elseif ($value === false) {
                    $value = 0;
                } elseif ($value === null) {
                    $value = 'NULL';
                } elseif ($value instanceof ExpressionInterface) {
                    $value = $this->buildExpression($value, $params);
                }
                $vs[] = $value;
            }
            $values[] = '(' . implode(', ', $vs) . ')';
        }
        if (empty($values)) {
            return '';
        }

        foreach ($columns as $i => $name) {
            $columns[$i] = $schema->quoteColumnName($name);
        }

        $tableAndColumns = ' INTO ' . $schema->quoteTableName($table)
        . ' (' . implode(', ', $columns) . ') VALUES ';

        return 'INSERT ALL ' . $tableAndColumns . implode($tableAndColumns, $values) . ' SELECT 1 FROM SYS.DUAL';
    }

    /**
     * {@inheritdoc}
     * @since 2.0.8
     */
    public function selectExists($rawSql)
    {
        return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END FROM DUAL';
    }

    /**
     * {@inheritdoc}
     * @since 2.0.8
     */
    public function dropCommentFromColumn($table, $column)
    {
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . " IS ''";
    }

    /**
     * {@inheritdoc}
     * @since 2.0.8
     */
    public function dropCommentFromTable($table)
    {
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . " IS ''";
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\db\mysql;

use yii\db\ExpressionInterface;
use yii\db\JsonExpression;

/**
 * Class ColumnSchema for MySQL database
 *
 * @author Dmytro Naumenko <d.naumenko.a@gmail.com>
 * @since 2.0.14.1
 */
class ColumnSchema extends \yii\db\ColumnSchema
{
    /**
     * @var bool whether the column schema should OMIT using JSON support feature.
     * You can use this property to make upgrade to Yii 2.0.14 easier.
     * Default to `false`, meaning JSON support is enabled.
     *
     * @since 2.0.14.1
     * @deprecated Since 2.0.14.1 and will be removed in 2.1.
     */
    public $disableJsonSupport = false;

    /**
     * {@inheritdoc}
     */
    public function dbTypecast($value)
    {
        if ($value === null) {
            return $value;
        }

        if ($value instanceof ExpressionInterface) {
            return $value;
        }

        if (!$this->disableJsonSupport && $this->dbType === Schema::TYPE_JSON) {
            return new JsonExpression($value, $this->type);
        }

        return $this->typecast($value);
    }

    /**
     * {@inheritdoc}
     */
    public function phpTypecast($value)
    {
        if ($value === null) {
            return null;
        }

        if (!$this->disableJsonSupport && $this->type === Schema::TYPE_JSON) {
            return json_decode($value, true);
        }

        return parent::phpTypecast($value);
    }
}