AbstractPosition::bundleFile

@param string $filename
@param array  $sources

@return array
334265
protected function bundleFile($filename, array $sources)
    {
        $sourcesContent = [];
        foreach ($sources as $key => $source) {
            $content = file_get_contents($source);

            if ( ! empty($content)) {
                $sourcesContent[] = $content;
            } else {
                unset($sources[ $key ]);
            }
        }

        $fileContent = implode(PHP_EOL, $sourcesContent);
        $fileVersion = $this->getVersion($fileContent);

        $publicFilePath = PATH_PUBLIC . $filename;
        $filename = pathinfo($publicFilePath, PATHINFO_BASENAME);

        $publicFileDir = dirname($publicFilePath) . DIRECTORY_SEPARATOR . 'bundled' . DIRECTORY_SEPARATOR;
        $publicFilePath = $publicFileDir . $filename;

        $extension = pathinfo($publicFilePath, PATHINFO_EXTENSION);

        $publicMinifyFilePath = str_replace('.' . $extension, '.min.' . $extension, $publicFilePath);

        if ( ! empty($sourcesContent)) {
            if (is_file($mapFilePath = $publicFilePath . '.map')) {
                $mapMetadata = json_decode(file_get_contents($mapFilePath), true);
                // if the file version is changed delete it first
                if ( ! hash_equals($fileVersion, $mapMetadata[ 'version' ])) {
                    unlink($publicFilePath);
                    unlink($publicMinifyFilePath);
                    unlink($mapFilePath);
                }
            }

            if ( ! is_file($mapFilePath)) {
                if ( ! empty($fileContent)) {
                    $mapMetadata = [
                        'version'        => $fileVersion,
                        'sources'        => $sources,
                        'names'          => [],
                        'mappings'       => [],
                        'file'           => pathinfo($publicMinifyFilePath, PATHINFO_BASENAME),
                        'sourcesContent' => $sourcesContent,
                        'sourceRoot'     => '',
                    ];

                    if ( ! is_writable($publicFileDir)) {
                        @mkdir($publicFileDir, 0777, true);
                    }

                    if (is_writable($publicFileDir)) {
                        if ($fileStream = @fopen($publicFilePath, 'ab')) {
                            flock($fileStream, LOCK_EX);
                            fwrite($fileStream, $fileContent);
                            flock($fileStream, LOCK_UN);
                            fclose($fileStream);

                            // File Map
                            if ($fileStream = @fopen($mapFilePath, 'ab')) {
                                flock($fileStream, LOCK_EX);

                                fwrite($fileStream, json_encode($mapMetadata));

                                flock($fileStream, LOCK_UN);
                                fclose($fileStream);
                            }

                            switch ($extension) {
                                case 'min.css':
                                case 'css':
                                    $minifyStyleHandler = new CSS($publicFilePath);
                                    $minifyStyleHandler->minify($publicMinifyFilePath);
                                    break;

                                case 'min.js':
                                case 'js':
                                    $minifyJavascriptHandler = new JS($publicFilePath);
                                    $minifyJavascriptHandler->minify($publicMinifyFilePath);
                                    break;
                            }

                        }
                    }
                }
            }
        }

        return [
            'filePath' => $publicFilePath,
            'url'      => $this->getUrl($publicFilePath),
            'minify'   => [
                'filePath' => $publicMinifyFilePath,
                'url'      => $this->getUrl($publicMinifyFilePath),
            ],
            'version'  => $fileVersion,
        ];
    }
208636
protected function processFile($filename, $configArray=[], $parsedFiles=[]) {
    // avoid circular includes
    if (!in_array($filename, $parsedFiles)) {
      $parsedFiles[] = $filename;

      $content = $this->parseIniFile($filename);

      // process includes
      $includes = $this->getConfigIncludes($content);
      if ($includes) {
        $this->processValue($includes);
        foreach ($includes as $include) {
          $result = $this->processFile($this->configPath.$include, $configArray, $parsedFiles);
          $configArray = $this->configMerge($configArray, $result['config'], true);
          $parsedFiles = $result['files'];
        }
      }

      // process self
      $configArray = $this->configMerge($configArray, $content, true);
    }
    return ['config' => $configArray, 'files' => $parsedFiles];
  }
620657
private function copy(array $sources, $dest, $minify)
    {
        // create destination path if not exists

        $ext = pathinfo($dest, PATHINFO_EXTENSION);
        $dir = !empty($ext) ? dirname($dest) : $dest;
        if (!file_exists($dir)) {
            if (!make_dir($dir, 0775)) {
                throw new RuntimeException('Unable to create directory ' . $dir); // @codeCoverageIgnore
            }
        }

        // list all source files into a flat array

        $files = [];
        foreach ($sources as $source) {
            if (is_dir($source)) {
                if ($ext == 'js') {
                    $filter = ['js'];
                }
                else if ($ext == 'css') {
                    $filter = ['css', 'less', 'scss'];
                }
                else {
                    $filter = null;
                }
                list_files($files, $source, $filter);
            }
            else {
                $files[] = $source;
            }
        }

        // copy all files to the destination

        if (file_exists($dest) && !is_dir($dest)) {
            unlink($dest);
        } // @codeCoverageIgnore

        foreach ($files as $file) {
            // get content
            $content = file_get_contents($file);

            // compile
            $srcExt = pathinfo($file, PATHINFO_EXTENSION);
            switch ($srcExt) {
                case 'less':
//                    $content = (new LessCompiler)->compile($content);
                    $content = (new LessCompiler)->parse($content)->getCss();
                    break;
                case 'scss':
                    $content = (new SCSSCompiler)->compile($content);
                    break;
            }

            // minimize
            if ($minify) {
                switch ($srcExt) {
                    case 'js':
                        $content = JSMin::minify($content);
                        break;
                    case 'css':
                    case 'less':
                    case 'scss':
                        $content = CssMin::minify($content);
                        break;
                }
            }

            // save content
            if (is_dir($dest)) {
                $success = file_put_contents($dest . DIRECTORY_SEPARATOR . basename($file), $content, LOCK_EX);
                //@chmod($dest . DIRECTORY_SEPARATOR . basename($file), 0664);
            }
            else {
                // concatenate the files to a single file
                if (file_exists($dest)) {
                    $success = file_put_contents($dest, PHP_EOL . $content, FILE_APPEND | LOCK_EX);
                }
                else {
                    $success = file_put_contents($dest, $content, LOCK_EX);
                    //@chmod($dest, 0664);
                }
            }
            if ($success === false) {
                throw new RuntimeException(sprintf('Asset Manager was not able to copy "%s" to "%s"', $file, $dest)); // @codeCoverageIgnore
            }
        }
    }
829259
private function findSourceFilesFromList(array $filenames): void
  {
    foreach ($filenames as $filename)
    {
      if (!file_exists($filename))
      {
        $this->io->error(sprintf("File not exists: '%s'", $filename));
        $this->errorFilenames[] = $filename;
      }
      else
      {
        $routineName     = pathinfo($filename, PATHINFO_FILENAME);
        $this->sources[] = ['path_name'    => $filename,
                            'routine_name' => $routineName,
                            'method_name'  => $this->methodName($routineName)];
      }
    }
  }
446647
public function createBundle($options = null)
    {
        if (!is_array($options)) {
            if (null !== $options) {
                $options = array('name' => $options);
            } else {
                $options = array();
            }
        }

        $options = array_merge($this->options, $options);

        if (isset($options['css_filter']) && is_string($options['css_filter'])) {
            $options['css_filter'] = $this->getFilter($options['css_filter']);
        }

        if (isset($options['js_filter']) && is_string($options['js_filter'])) {
            $options['js_filter'] = $this->getFilter($options['js_filter']);
        }

        return new Bundle($options);
    }
1307377
static function saveIncludedFiles($filename, $fromFile) {
        if (file_exists($filename)) {
            $all_included_files = json_decode(file_get_contents($filename), JSON_OBJECT_AS_ARRAY);
        } else {
            $all_included_files = array();
        }
        foreach (get_included_files() as $includedFile) {
            if (!isset($all_included_files[$includedFile])) {
                $all_included_files[$includedFile] = array();
            }
            if (!in_array($fromFile, $all_included_files[$includedFile])) {
                array_push($all_included_files[$includedFile], $fromFile);
            }
        }
        file_put_contents($filename, json_encode($all_included_files));
    }
571062
private function moveFile($sourceFolder, $destFolder, $filename)
    {
        // generate the full file paths
        $sourceFilepath = $sourceFolder . DIRECTORY_SEPARATOR . $filename;
        $destFilepath = $destFolder . DIRECTORY_SEPARATOR . $filename;

        // rename the file
        rename($sourceFilepath, $destFilepath);
    }
1237560
static function Modules($bundleName, ModuleLocation $location)
    {
        $result = array();
        $modulesFolder = Path::Combine(self::BundleFolder($bundleName), 'Modules');
        $folder = Path::Combine($modulesFolder, (string)$location);
        if (!Folder::Exists($folder)) {
            return $result;
        }
        $files = Folder::GetFiles($folder);
        foreach ($files as $file)
        {
            $result[] = Path::RemoveExtension($file);
        }
        return $result;
    }
564951
public function
	ShouldWriteToDisk($filename,$source) {
	/*//
	//*/

		if(!file_exists($filename))
		return true;

		$old = md5(static::StripScriptHeader(file_get_contents($filename)));
		$new = md5(static::StripScriptHeader($source));

		if($old !== $new) return true;
		else return false;
	}
156500
public function locateFileInFolder($filename, array $folders)
    {
        $list = [];
        foreach ($folders as $folder) {
            $list += $this->detectInFolder($folder, $filename);
        }
        return $list;
    }
877663
private function loadFile(string $filename) : array
    {
        Assertion::file($filename, 'File "' . $filename . '" does not exist.');
        Assertion::readable($filename, 'File "' . $filename . '" is not readable.');

        /** @var string $fileContent */
        $fileContent = file_get_contents($filename);

        Assertion::string($fileContent);

        if (preg_match('/[^ -~\s]/', $fileContent)) {
            throw new \RuntimeException('File "' . $filename . '" contains Non-ASCII-Characters.');
        }

        $jsonParser = new JsonParser();

        try {
            return $jsonParser->parse($fileContent, JsonParser::DETECT_KEY_CONFLICTS | JsonParser::PARSE_TO_ASSOC);
        } catch (ParsingException $e) {
            throw new \RuntimeException(
                'File "' . $filename . '" had invalid JSON.',
                0,
                $e
            );
        }
    }
1019495
public function generateAllAssets ($files, $sitePath, $siteName, $isFromVendor)
    {
        $cssMinifier = new Minify\CSS();
        $jsMinifier = new Minify\JS();

        if($isFromVendor){
            $bundleDir = $sitePath.'/public/';
            /**
             * we need to remove the site name on the path
             * since the site name is already included
             * in the file name inside the assets.config
             */
            $sitePath = dirname($sitePath);
        }else{
            $bundleDir = $sitePath.'/'.$siteName.'/public/';
        }

        $messages = array();

        //check if the directory for the bundle is exist
        if($this->checkDir($bundleDir)) {
            //check if bundle is writable
            if (is_writable($bundleDir)) {

                if (!empty($files)) {
                    foreach ($files as $key => $file) {
                        //create a bundle for js
                        $key = strtolower($key);
                        if ($key == 'js') {
                            $messages['error'] = $this->createBundleFile($jsMinifier, 'bundle.js', $file, $sitePath, $bundleDir);
                        }
                        //create a bundle for css
                        if ($key == 'css') {
                            $messages['error'] = $this->createBundleFile($cssMinifier, 'bundle.css', $file, $sitePath, $bundleDir, false);
                        }
                    }
                }
            }else {
                $messages['error'] = array('message' => $bundleDir . ' is not writable.', 'success' => false);
            }
        }else{
            $messages['error'] = array('message' => $bundleDir . ' does not exist.', 'success' => false);
        }
        return $messages;
    }
210941
public static function getFileContents(string $fileName): string
    {
        if (is_file($fileName)) {
            $fileContent = @file_get_contents($fileName);

            if ($fileContent === false) {
                throw new BunqException(vsprintf(self::ERROR_COULD_NOT_GET_FILE_CONTENT, [$fileName]));
            } else {
                return $fileContent;
            }
        } else {
            throw new BunqException(vsprintf(self::ERROR_FILE_DOES_NOT_EXIST, [$fileName]));
        }
    }
503272
private static function buildComponentFiles($bundleDir, $applicationName, Filesystem $filesystem)
    {
        $filesystem->setParameters(array(
            'namespace' => $applicationName,
            'applicationName' => $applicationName,
        ));

        $filesystem->mirror(__DIR__.'/../Resources/skeleton/avoo-component', $bundleDir, null, array('override' => true));
    }
763652
public function createInputStream($source, array $options = []): InputStream
    {
        if (isset($options['filemode'])) {
            return new FileInputStream($source, $options['filemode']);
        }

        return new FileInputStream($source);
    }
455824
private function createBundleFile ($minifier, $fileName, $files, $sitePath, $bundleDir, $cleanCode = true)
    {
        $translator = $this->getServiceLocator()->get('translator');
        $message = '';
        $success = false;
        if (!empty($files)) {
            try {
                foreach ($files as $key => $file) {
                    //remove comments
                    if($cleanCode) {
                        $codeToAdd = $this->removeComments($sitePath . $file);
                    }else{
                        $codeToAdd = $sitePath . $file;
                    }
                    //add the file to minify later
                    $minifier->add($codeToAdd);
//                 $minifier = $this->getFileContentsViaCurl($minifier, $file);
                }
                //minify all the files
                $minifier->minify($bundleDir . $fileName);
                $message = $translator->translate('tr_front_minify_assets_compiled_successfully');
                $success = true;
            } catch (\Exception $ex) {
                /**
                 * this will occur only if the bundle.css or bundle.js
                 * is not writable or no permission or other errors
                 */
                  $message = wordwrap($ex->getMessage(), 20, "\n", true);
            }
        }else{
            $success = true;
        }

        return array(
            'message' => $message,
            'success' => $success
        );
    }
157982
public function loadBundle($bundleName)
	{
		if (!preg_match('#^[A-Z][A-Za-z0-9]+$#D', $bundleName))
		{
			throw new InvalidArgumentException("Invalid bundle name '" . $bundleName . "'");
		}

		$className = __CLASS__ . '\\Bundles\\' . $bundleName;

		$bundle = new $className;
		$bundle->configure($this);
	}