Compiling custom Bootstrap css in yii2 from less

composer-php, less, twitter-bootstrap, yii2

Solution

Bootstrap configuration can be done by changing variables.less. The following BootstrapAsset is the replacement of original one, that uses bootstrap-variables.less in current directory instead of original variables.less.

namespace app\assets;

use yii\helpers\FileHelper;
use yii\web\AssetBundle;

class BootstrapAsset extends AssetBundle
{
    public $sourcePath = '@bower/bootstrap/dist';
    public $css = [
        'css/bootstrap.css',
    ];

    public function publish($am)
    {
        if ($this->sourcePath !== null && !isset($this->basePath, $this->baseUrl)) {
            list ($this->basePath, $this->baseUrl) = $am->publish($this->sourcePath, $this->publishOptions);
        }

        $src = \Yii::getAlias($this->sourcePath);

        FileHelper::copyDirectory("$src/../less", $this->basePath."/less");

        $vars = file_get_contents(__DIR__ . "/bootstrap-variables.less");
        $css = \Yii::$app->cache->get("bootstrap-css-".crc32($vars));
        if (!$css)
        {
            file_put_contents("$src/../less/variables.less", $vars);

            ini_set('xdebug.max_nesting_level', 200);

            $less = new \lessc();
            $less->setFormatter(YII_DEBUG ? "lessjs" : "compressed");
            unlink($this->basePath . "/css/bootstrap.css");
            $less->compileFile("$src/../less/bootstrap.less", $this->basePath . "/css/bootstrap.css");
            \Yii::$app->cache->set("bootstrap-css-".crc32($vars), file_get_contents($this->basePath . "/css/bootstrap.css"));
        }
        else
        {
            file_put_contents($this->basePath . "/css/bootstrap.css", $css);
        }
    }
}

Problem

I'm starting a new project in Yii2 and Composer (after a few projects with YII 1). I created a new "advanced project" with composer. Everything is okay but, I'm wondering what is the best way to customize the bootstrap theme? I think copying the whole bootstrap less to the backend and to the frontend and edit the two variables file and compile it isn't the right way. So: is it somehow possible to extend the less files downloaded by the composer and edit only the two variables file?

Original source