StackFormation\Preprocessor::injectFilecontent PHP Method

injectFilecontent() protected method

protected injectFilecontent ( $jsonString, $basePath )
    protected function injectFilecontent($jsonString, $basePath)
    {
        $jsonString = preg_replace_callback('/(\\s*)(.*){\\s*"Fn::FileContent(Unpretty|TrimLines|Minify)?"\\s*:\\s*"(.+?)"\\s*}/', function (array $matches) use($basePath) {
            $file = $basePath . '/' . end($matches);
            if (!is_file($file)) {
                throw new FileNotFoundException("File '{$file}' not found");
            }
            $ext = pathinfo($file, PATHINFO_EXTENSION);
            if ($matches[3] == 'Minify' && $ext != 'js') {
                throw new \Exception('Fn::FileContentMinify is only supported for *.js files. (File: ' . $file . ')');
            }
            $fileContent = file_get_contents($file);
            $fileContent = $this->injectInclude($fileContent, dirname(realpath($file)));
            if ($ext === 'js') {
                if ($matches[3] == 'Minify') {
                    $fileContent = \JShrink\Minifier::minify($fileContent, ['flaggedComments' => false]);
                }
                $size = strlen($fileContent);
                if ($size > self::MAX_JS_FILE_INCLUDE_SIZE) {
                    // this is assuming you are uploading an inline JS file to AWS Lambda
                    throw new \Exception(sprintf("JS file is larger than %s bytes (actual size: %s bytes)", self::MAX_JS_FILE_INCLUDE_SIZE, $size));
                }
            }
            // TODO: this isn't optimal. Why are we processing this here in between?
            $fileContent = $this->base64encodedJson($fileContent);
            $lines = explode("\n", $fileContent);
            foreach ($lines as $key => &$line) {
                if ($matches[3] == 'TrimLines') {
                    $line = trim($line);
                    if (empty($line)) {
                        unset($lines[$key]);
                    }
                }
                $line .= "\n";
            }
            if ($matches[3] == 'Unpretty') {
                $result = ' {"Fn::Join": ["", ' . json_encode(array_values($lines)) . ']}';
            } else {
                $result = ' {"Fn::Join": ["", ' . json_encode(array_values($lines), JSON_PRETTY_PRINT) . ']}';
            }
            $whitespace = trim($matches[1], "\n");
            $result = str_replace("\n", "\n" . $whitespace, $result);
            return $matches[1] . $matches[2] . $result;
        }, $jsonString);
        return $jsonString;
    }