1<?php
2
3namespace Illuminate\Support;
4
5use Illuminate\Filesystem\Filesystem;
6use Symfony\Component\Process\Process;
7use Symfony\Component\Process\PhpExecutableFinder;
8
9class Composer
10{
11    /**
12     * The filesystem instance.
13     *
14     * @var \Illuminate\Filesystem\Filesystem
15     */
16    protected $files;
17
18    /**
19     * The working path to regenerate from.
20     *
21     * @var string|null
22     */
23    protected $workingPath;
24
25    /**
26     * Create a new Composer manager instance.
27     *
28     * @param  \Illuminate\Filesystem\Filesystem  $files
29     * @param  string|null  $workingPath
30     * @return void
31     */
32    public function __construct(Filesystem $files, $workingPath = null)
33    {
34        $this->files = $files;
35        $this->workingPath = $workingPath;
36    }
37
38    /**
39     * Regenerate the Composer autoloader files.
40     *
41     * @param  string|array  $extra
42     * @return void
43     */
44    public function dumpAutoloads($extra = '')
45    {
46        $extra = $extra ? (array) $extra : [];
47
48        $command = array_merge($this->findComposer(), ['dump-autoload'], $extra);
49
50        $this->getProcess($command)->run();
51    }
52
53    /**
54     * Regenerate the optimized Composer autoloader files.
55     *
56     * @return void
57     */
58    public function dumpOptimized()
59    {
60        $this->dumpAutoloads('--optimize');
61    }
62
63    /**
64     * Get the composer command for the environment.
65     *
66     * @return array
67     */
68    protected function findComposer()
69    {
70        if ($this->files->exists($this->workingPath.'/composer.phar')) {
71            return [$this->phpBinary(), 'composer.phar'];
72        }
73
74        return ['composer'];
75    }
76
77    /**
78     * Get the PHP binary.
79     *
80     * @return string
81     */
82    protected function phpBinary()
83    {
84        return ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false));
85    }
86
87    /**
88     * Get a new Symfony process instance.
89     *
90     * @param  array  $command
91     * @return \Symfony\Component\Process\Process
92     */
93    protected function getProcess(array $command)
94    {
95        return (new Process($command, $this->workingPath))->setTimeout(null);
96    }
97
98    /**
99     * Set the working path used by the class.
100     *
101     * @param  string  $path
102     * @return $this
103     */
104    public function setWorkingPath($path)
105    {
106        $this->workingPath = realpath($path);
107
108        return $this;
109    }
110}
111