1<?php
2
3/*
4 * This file is part of Composer.
5 *
6 * (c) Nils Adermann <naderman@naderman.de>
7 *     Jordi Boggiano <j.boggiano@seld.be>
8 *
9 * For the full copyright and license information, please view the LICENSE
10 * file that was distributed with this source code.
11 */
12
13namespace Composer\DependencyResolver;
14
15/**
16 * Represents a problem detected while solving dependencies
17 *
18 * @author Nils Adermann <naderman@naderman.de>
19 */
20class Problem
21{
22    /**
23     * A map containing the id of each rule part of this problem as a key
24     * @var array
25     */
26    protected $reasonSeen;
27
28    /**
29     * A set of reasons for the problem, each is a rule or a job and a rule
30     * @var array
31     */
32    protected $reasons = array();
33
34    protected $section = 0;
35
36    protected $pool;
37
38    public function __construct(Pool $pool)
39    {
40        $this->pool = $pool;
41    }
42
43    /**
44     * Add a rule as a reason
45     *
46     * @param Rule $rule A rule which is a reason for this problem
47     */
48    public function addRule(Rule $rule)
49    {
50        $this->addReason(spl_object_hash($rule), array(
51            'rule' => $rule,
52            'job' => $rule->getJob(),
53        ));
54    }
55
56    /**
57     * Retrieve all reasons for this problem
58     *
59     * @return array The problem's reasons
60     */
61    public function getReasons()
62    {
63        return $this->reasons;
64    }
65
66    /**
67     * A human readable textual representation of the problem's reasons
68     *
69     * @param  array  $installedMap A map of all installed packages
70     * @return string
71     */
72    public function getPrettyString(array $installedMap = array())
73    {
74        $reasons = call_user_func_array('array_merge', array_reverse($this->reasons));
75
76        if (count($reasons) === 1) {
77            reset($reasons);
78            $reason = current($reasons);
79
80            $rule = $reason['rule'];
81            $job = $reason['job'];
82
83            if (isset($job['constraint'])) {
84                $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
85            } else {
86                $packages = array();
87            }
88
89            if ($job && $job['cmd'] === 'install' && empty($packages)) {
90
91                // handle php/hhvm
92                if ($job['packageName'] === 'php' || $job['packageName'] === 'php-64bit' || $job['packageName'] === 'hhvm') {
93                    $available = $this->pool->whatProvides($job['packageName']);
94                    $version = count($available) ? $available[0]->getPrettyVersion() : phpversion();
95
96                    $msg = "\n    - This package requires ".$job['packageName'].$this->constraintToText($job['constraint']).' but ';
97
98                    if (defined('HHVM_VERSION')) {
99                        return $msg . 'your HHVM version does not satisfy that requirement.';
100                    }
101
102                    if ($job['packageName'] === 'hhvm') {
103                        return $msg . 'you are running this with PHP and not HHVM.';
104                    }
105
106                    return $msg . 'your PHP version ('. $version .') does not satisfy that requirement.';
107                }
108
109                // handle php extensions
110                if (0 === stripos($job['packageName'], 'ext-')) {
111                    $ext = substr($job['packageName'], 4);
112                    $error = extension_loaded($ext) ? 'has the wrong version ('.(phpversion($ext) ?: '0').') installed' : 'is missing from your system';
113
114                    return "\n    - The requested PHP extension ".$job['packageName'].$this->constraintToText($job['constraint']).' '.$error.'. Install or enable PHP\'s '.$ext.' extension.';
115                }
116
117                // handle linked libs
118                if (0 === stripos($job['packageName'], 'lib-')) {
119                    if (strtolower($job['packageName']) === 'lib-icu') {
120                        $error = extension_loaded('intl') ? 'has the wrong version installed, try upgrading the intl extension.' : 'is missing from your system, make sure the intl extension is loaded.';
121
122                        return "\n    - The requested linked library ".$job['packageName'].$this->constraintToText($job['constraint']).' '.$error;
123                    }
124
125                    return "\n    - The requested linked library ".$job['packageName'].$this->constraintToText($job['constraint']).' has the wrong version installed or is missing from your system, make sure to load the extension providing it.';
126                }
127
128                if (!preg_match('{^[A-Za-z0-9_./-]+$}', $job['packageName'])) {
129                    $illegalChars = preg_replace('{[A-Za-z0-9_./-]+}', '', $job['packageName']);
130
131                    return "\n    - The requested package ".$job['packageName'].' could not be found, it looks like its name is invalid, "'.$illegalChars.'" is not allowed in package names.';
132                }
133
134                if ($providers = $this->pool->whatProvides($job['packageName'], $job['constraint'], true, true)) {
135                    return "\n    - The requested package ".$job['packageName'].$this->constraintToText($job['constraint']).' is satisfiable by '.$this->getPackageList($providers).' but these conflict with your requirements or minimum-stability.';
136                }
137
138                if ($providers = $this->pool->whatProvides($job['packageName'], null, true, true)) {
139                    return "\n    - The requested package ".$job['packageName'].$this->constraintToText($job['constraint']).' exists as '.$this->getPackageList($providers).' but these are rejected by your constraint.';
140                }
141
142                return "\n    - The requested package ".$job['packageName'].' could not be found in any version, there may be a typo in the package name.';
143            }
144        }
145
146        $messages = array();
147
148        foreach ($reasons as $reason) {
149            $rule = $reason['rule'];
150            $job = $reason['job'];
151
152            if ($job) {
153                $messages[] = $this->jobToText($job);
154            } elseif ($rule) {
155                if ($rule instanceof Rule) {
156                    $messages[] = $rule->getPrettyString($this->pool, $installedMap);
157                }
158            }
159        }
160
161        return "\n    - ".implode("\n    - ", $messages);
162    }
163
164    /**
165     * Store a reason descriptor but ignore duplicates
166     *
167     * @param string $id     A canonical identifier for the reason
168     * @param string $reason The reason descriptor
169     */
170    protected function addReason($id, $reason)
171    {
172        if (!isset($this->reasonSeen[$id])) {
173            $this->reasonSeen[$id] = true;
174            $this->reasons[$this->section][] = $reason;
175        }
176    }
177
178    public function nextSection()
179    {
180        $this->section++;
181    }
182
183    /**
184     * Turns a job into a human readable description
185     *
186     * @param  array  $job
187     * @return string
188     */
189    protected function jobToText($job)
190    {
191        switch ($job['cmd']) {
192            case 'install':
193                $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
194                if (!$packages) {
195                    return 'No package found to satisfy install request for '.$job['packageName'].$this->constraintToText($job['constraint']);
196                }
197
198                return 'Installation request for '.$job['packageName'].$this->constraintToText($job['constraint']).' -> satisfiable by '.$this->getPackageList($packages).'.';
199            case 'update':
200                return 'Update request for '.$job['packageName'].$this->constraintToText($job['constraint']).'.';
201            case 'remove':
202                return 'Removal request for '.$job['packageName'].$this->constraintToText($job['constraint']).'';
203        }
204
205        if (isset($job['constraint'])) {
206            $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
207        } else {
208            $packages = array();
209        }
210
211        return 'Job(cmd='.$job['cmd'].', target='.$job['packageName'].', packages=['.$this->getPackageList($packages).'])';
212    }
213
214    protected function getPackageList($packages)
215    {
216        $prepared = array();
217        foreach ($packages as $package) {
218            $prepared[$package->getName()]['name'] = $package->getPrettyName();
219            $prepared[$package->getName()]['versions'][$package->getVersion()] = $package->getPrettyVersion();
220        }
221        foreach ($prepared as $name => $package) {
222            $prepared[$name] = $package['name'].'['.implode(', ', $package['versions']).']';
223        }
224
225        return implode(', ', $prepared);
226    }
227
228    /**
229     * Turns a constraint into text usable in a sentence describing a job
230     *
231     * @param  \Composer\Semver\Constraint\ConstraintInterface $constraint
232     * @return string
233     */
234    protected function constraintToText($constraint)
235    {
236        return ($constraint) ? ' '.$constraint->getPrettyString() : '';
237    }
238}
239