1<?php
2
3/*
4 * This file is part of Component Installer.
5 *
6 * (c) Rob Loach (http://robloach.net)
7 *
8 * For the full copyright and license information, please view the LICENSE.md
9 * file that was distributed with this source code.
10 */
11
12namespace ComponentInstaller\Process;
13
14/**
15 * Builds all JavaScript Components into one require-built.js.
16 */
17class BuildJsProcess extends Process
18{
19    /**
20     * {@inheritdoc}
21     */
22    public function process()
23    {
24        return $this->compile($this->packages);
25    }
26
27    /**
28     * Copy file assets from the given packages to the component directory.
29     *
30     * @param array $packages
31     *   An array of packages.
32     * @return bool
33     */
34    public function compile($packages)
35    {
36        // Set up the initial require-build.js file.
37        $destination = $this->componentDir.DIRECTORY_SEPARATOR.'require-built.js';
38        $require = $this->componentDir.DIRECTORY_SEPARATOR.'require.js';
39        copy($require, $destination);
40
41        // Cycle through each package and add it to the built require.js file.
42        foreach ($packages as $package) {
43            // Retrieve some information about the package
44            $name = isset($package['name']) ? $package['name'] : '__component__';
45            $extra = isset($package['extra']) ? $package['extra'] : array();
46            $componentName = $this->getComponentName($name, $extra);
47
48            // Find where the source file is located.
49            $packageDir = $this->componentDir.DIRECTORY_SEPARATOR.$componentName;
50            $source = $packageDir.DIRECTORY_SEPARATOR.$componentName.'-built.js';
51
52            // Make sure the source script is available.
53            if (file_exists($source)) {
54                // Build the compiled script.
55                $content = file_get_contents($source);
56                $output = $this->definePrefix($componentName) . $content . $this->definePostfix();
57
58                // Append the module definition to the destination file.
59                file_put_contents($destination, $output, FILE_APPEND);
60            }
61        }
62
63        return true;
64    }
65
66    /**
67     * Provide the initial definition prefix.
68     *
69     * @param string $componentName
70     * @return string Begin the module definition.
71     */
72    protected function definePrefix($componentName)
73    {
74        // Define the module using the simplified CommonJS wrapper.
75        return "\ndefine('$componentName', function (require, exports, module) {\n";
76    }
77
78    /**
79     * Finish the module definition.
80     *
81     * @return string Close brackets to finish the module.
82     */
83    protected function definePostfix()
84    {
85        return "\n});\n";
86    }
87}
88