ValidatingArrayLoader.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Package\Loader;
  12. use Composer\Package;
  13. use Composer\Package\BasePackage;
  14. use Composer\Semver\Constraint\Constraint;
  15. use Composer\Package\Version\VersionParser;
  16. use Composer\Repository\PlatformRepository;
  17. use Composer\Spdx\SpdxLicenses;
  18. /**
  19. * @author Jordi Boggiano <j.boggiano@seld.be>
  20. */
  21. class ValidatingArrayLoader implements LoaderInterface
  22. {
  23. const CHECK_ALL = 3;
  24. const CHECK_UNBOUND_CONSTRAINTS = 1;
  25. const CHECK_STRICT_CONSTRAINTS = 2;
  26. private $loader;
  27. private $versionParser;
  28. private $errors;
  29. private $warnings;
  30. private $config;
  31. private $strictName;
  32. private $flags;
  33. public function __construct(LoaderInterface $loader, $strictName = true, VersionParser $parser = null, $flags = 0)
  34. {
  35. $this->loader = $loader;
  36. $this->versionParser = $parser ?: new VersionParser();
  37. $this->strictName = $strictName;
  38. $this->flags = $flags;
  39. }
  40. public function load(array $config, $class = 'Composer\Package\CompletePackage')
  41. {
  42. $this->errors = array();
  43. $this->warnings = array();
  44. $this->config = $config;
  45. if ($this->strictName) {
  46. $this->validateRegex('name', '[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*', true);
  47. } else {
  48. $this->validateString('name', true);
  49. }
  50. if (!empty($this->config['version'])) {
  51. try {
  52. $this->versionParser->normalize($this->config['version']);
  53. } catch (\Exception $e) {
  54. $this->errors[] = 'version : invalid value ('.$this->config['version'].'): '.$e->getMessage();
  55. unset($this->config['version']);
  56. }
  57. }
  58. if (!empty($this->config['config']['platform'])) {
  59. foreach ((array) $this->config['config']['platform'] as $key => $platform) {
  60. try {
  61. $this->versionParser->normalize($platform);
  62. } catch (\Exception $e) {
  63. $this->errors[] = 'config.platform.' . $key . ' : invalid value ('.$platform.'): '.$e->getMessage();
  64. }
  65. }
  66. }
  67. $this->validateRegex('type', '[A-Za-z0-9-]+');
  68. $this->validateString('target-dir');
  69. $this->validateArray('extra');
  70. if (isset($this->config['bin'])) {
  71. if (is_string($this->config['bin'])) {
  72. $this->validateString('bin');
  73. } else {
  74. $this->validateFlatArray('bin');
  75. }
  76. }
  77. $this->validateArray('scripts'); // TODO validate event names & listener syntax
  78. $this->validateString('description');
  79. $this->validateUrl('homepage');
  80. $this->validateFlatArray('keywords', '[\p{N}\p{L} ._-]+');
  81. $releaseDate = null;
  82. $this->validateString('time');
  83. if (!empty($this->config['time'])) {
  84. try {
  85. $releaseDate = new \DateTime($this->config['time'], new \DateTimeZone('UTC'));
  86. } catch (\Exception $e) {
  87. $this->errors[] = 'time : invalid value ('.$this->config['time'].'): '.$e->getMessage();
  88. unset($this->config['time']);
  89. }
  90. }
  91. if (isset($this->config['license'])) {
  92. if (is_string($this->config['license'])) {
  93. $this->validateRegex('license', '[A-Za-z0-9+. ()-]+');
  94. } else {
  95. $this->validateFlatArray('license', '[A-Za-z0-9+. ()-]+');
  96. }
  97. if (is_array($this->config['license']) || is_string($this->config['license'])) {
  98. $licenses = (array) $this->config['license'];
  99. // strip proprietary since it's not a valid SPDX identifier, but is accepted by composer
  100. foreach ($licenses as $key => $license) {
  101. if ('proprietary' === $license) {
  102. unset($licenses[$key]);
  103. }
  104. }
  105. $licenseValidator = new SpdxLicenses();
  106. if (count($licenses) === 1 && !$licenseValidator->validate($licenses) && $licenseValidator->validate(trim($licenses[0]))) {
  107. $this->warnings[] = sprintf(
  108. 'License %s must not contain extra spaces, make sure to trim it.',
  109. json_encode($this->config['license'])
  110. );
  111. } elseif (array() !== $licenses && !$licenseValidator->validate($licenses)) {
  112. $this->warnings[] = sprintf(
  113. 'License %s is not a valid SPDX license identifier, see https://spdx.org/licenses/ if you use an open license.' . PHP_EOL .
  114. 'If the software is closed-source, you may use "proprietary" as license.',
  115. json_encode($this->config['license'])
  116. );
  117. } else if (!$releaseDate || $releaseDate->format('Y-m-d H:i:s') >= '2018-01-20 00:00:00') { // only warn for deprecations for releases/branches that follow the introduction of deprecated licenses
  118. foreach ($licenses as $license) {
  119. $spdxLicense = $licenseValidator->getLicenseByIdentifier($license);
  120. if ($spdxLicense && $spdxLicense[3]) {
  121. if (preg_match('{^[AL]?GPL-[123](\.[01])?\+$}i', $license)) {
  122. $this->warnings[] = sprintf(
  123. 'License "%s" is a deprecated SPDX license identifier, use "'.str_replace('+', '', $license).'-or-later" instead',
  124. $license
  125. );
  126. } elseif (preg_match('{^[AL]?GPL-[123](\.[01])?$}i', $license)) {
  127. $this->warnings[] = sprintf(
  128. 'License "%s" is a deprecated SPDX license identifier, use "'.$license.'-only" or "'.$license.'-or-later" instead',
  129. $license
  130. );
  131. } else {
  132. $this->warnings[] = sprintf(
  133. 'License "%s" is a deprecated SPDX license identifier, see https://spdx.org/licenses/',
  134. $license
  135. );
  136. }
  137. }
  138. }
  139. }
  140. }
  141. }
  142. if ($this->validateArray('authors') && !empty($this->config['authors'])) {
  143. foreach ($this->config['authors'] as $key => $author) {
  144. if (!is_array($author)) {
  145. $this->errors[] = 'authors.'.$key.' : should be an array, '.gettype($author).' given';
  146. unset($this->config['authors'][$key]);
  147. continue;
  148. }
  149. foreach (array('homepage', 'email', 'name', 'role') as $authorData) {
  150. if (isset($author[$authorData]) && !is_string($author[$authorData])) {
  151. $this->errors[] = 'authors.'.$key.'.'.$authorData.' : invalid value, must be a string';
  152. unset($this->config['authors'][$key][$authorData]);
  153. }
  154. }
  155. if (isset($author['homepage']) && !$this->filterUrl($author['homepage'])) {
  156. $this->warnings[] = 'authors.'.$key.'.homepage : invalid value ('.$author['homepage'].'), must be an http/https URL';
  157. unset($this->config['authors'][$key]['homepage']);
  158. }
  159. if (isset($author['email']) && !filter_var($author['email'], FILTER_VALIDATE_EMAIL)) {
  160. $this->warnings[] = 'authors.'.$key.'.email : invalid value ('.$author['email'].'), must be a valid email address';
  161. unset($this->config['authors'][$key]['email']);
  162. }
  163. if (empty($this->config['authors'][$key])) {
  164. unset($this->config['authors'][$key]);
  165. }
  166. }
  167. if (empty($this->config['authors'])) {
  168. unset($this->config['authors']);
  169. }
  170. }
  171. if ($this->validateArray('support') && !empty($this->config['support'])) {
  172. foreach (array('issues', 'forum', 'wiki', 'source', 'email', 'irc', 'docs', 'rss') as $key) {
  173. if (isset($this->config['support'][$key]) && !is_string($this->config['support'][$key])) {
  174. $this->errors[] = 'support.'.$key.' : invalid value, must be a string';
  175. unset($this->config['support'][$key]);
  176. }
  177. }
  178. if (isset($this->config['support']['email']) && !filter_var($this->config['support']['email'], FILTER_VALIDATE_EMAIL)) {
  179. $this->warnings[] = 'support.email : invalid value ('.$this->config['support']['email'].'), must be a valid email address';
  180. unset($this->config['support']['email']);
  181. }
  182. if (isset($this->config['support']['irc']) && !$this->filterUrl($this->config['support']['irc'], array('irc'))) {
  183. $this->warnings[] = 'support.irc : invalid value ('.$this->config['support']['irc'].'), must be a irc://<server>/<channel> URL';
  184. unset($this->config['support']['irc']);
  185. }
  186. foreach (array('issues', 'forum', 'wiki', 'source', 'docs') as $key) {
  187. if (isset($this->config['support'][$key]) && !$this->filterUrl($this->config['support'][$key])) {
  188. $this->warnings[] = 'support.'.$key.' : invalid value ('.$this->config['support'][$key].'), must be an http/https URL';
  189. unset($this->config['support'][$key]);
  190. }
  191. }
  192. if (empty($this->config['support'])) {
  193. unset($this->config['support']);
  194. }
  195. }
  196. $unboundConstraint = new Constraint('=', $this->versionParser->normalize('dev-master'));
  197. $stableConstraint = new Constraint('=', '1.0.0');
  198. foreach (array_keys(BasePackage::$supportedLinkTypes) as $linkType) {
  199. if ($this->validateArray($linkType) && isset($this->config[$linkType])) {
  200. foreach ($this->config[$linkType] as $package => $constraint) {
  201. if (!preg_match('{^[A-Za-z0-9_./-]+$}', $package)) {
  202. $this->warnings[] = $linkType.'.'.$package.' : invalid key, package names must be strings containing only [A-Za-z0-9_./-]';
  203. }
  204. if (!is_string($constraint)) {
  205. $this->errors[] = $linkType.'.'.$package.' : invalid value, must be a string containing a version constraint';
  206. unset($this->config[$linkType][$package]);
  207. } elseif ('self.version' !== $constraint) {
  208. try {
  209. $linkConstraint = $this->versionParser->parseConstraints($constraint);
  210. } catch (\Exception $e) {
  211. $this->errors[] = $linkType.'.'.$package.' : invalid version constraint ('.$e->getMessage().')';
  212. unset($this->config[$linkType][$package]);
  213. continue;
  214. }
  215. // check requires for unbound constraints on non-platform packages
  216. if (
  217. ($this->flags & self::CHECK_UNBOUND_CONSTRAINTS)
  218. && 'require' === $linkType
  219. && $linkConstraint->matches($unboundConstraint)
  220. && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $package)
  221. ) {
  222. $this->warnings[] = $linkType.'.'.$package.' : unbound version constraints ('.$constraint.') should be avoided';
  223. } elseif (
  224. // check requires for exact constraints
  225. ($this->flags & self::CHECK_STRICT_CONSTRAINTS)
  226. && 'require' === $linkType
  227. && substr($linkConstraint, 0, 1) === '='
  228. && $stableConstraint->versionCompare($stableConstraint, $linkConstraint, '<=')
  229. ) {
  230. $this->warnings[] = $linkType.'.'.$package.' : exact version constraints ('.$constraint.') should be avoided if the package follows semantic versioning';
  231. }
  232. }
  233. }
  234. }
  235. }
  236. if ($this->validateArray('suggest') && !empty($this->config['suggest'])) {
  237. foreach ($this->config['suggest'] as $package => $description) {
  238. if (!is_string($description)) {
  239. $this->errors[] = 'suggest.'.$package.' : invalid value, must be a string describing why the package is suggested';
  240. unset($this->config['suggest'][$package]);
  241. }
  242. }
  243. }
  244. if ($this->validateString('minimum-stability') && !empty($this->config['minimum-stability'])) {
  245. if (!isset(BasePackage::$stabilities[$this->config['minimum-stability']])) {
  246. $this->errors[] = 'minimum-stability : invalid value ('.$this->config['minimum-stability'].'), must be one of '.implode(', ', array_keys(BasePackage::$stabilities));
  247. unset($this->config['minimum-stability']);
  248. }
  249. }
  250. if ($this->validateArray('autoload') && !empty($this->config['autoload'])) {
  251. $types = array('psr-0', 'psr-4', 'classmap', 'files', 'exclude-from-classmap');
  252. foreach ($this->config['autoload'] as $type => $typeConfig) {
  253. if (!in_array($type, $types)) {
  254. $this->errors[] = 'autoload : invalid value ('.$type.'), must be one of '.implode(', ', $types);
  255. unset($this->config['autoload'][$type]);
  256. }
  257. if ($type === 'psr-4') {
  258. foreach ($typeConfig as $namespace => $dirs) {
  259. if ($namespace !== '' && '\\' !== substr($namespace, -1)) {
  260. $this->errors[] = 'autoload.psr-4 : invalid value ('.$namespace.'), namespaces must end with a namespace separator, should be '.$namespace.'\\\\';
  261. }
  262. }
  263. }
  264. }
  265. }
  266. if (!empty($this->config['autoload']['psr-4']) && !empty($this->config['target-dir'])) {
  267. $this->errors[] = 'target-dir : this can not be used together with the autoload.psr-4 setting, remove target-dir to upgrade to psr-4';
  268. // Unset the psr-4 setting, since unsetting target-dir might
  269. // interfere with other settings.
  270. unset($this->config['autoload']['psr-4']);
  271. }
  272. // TODO validate dist
  273. // TODO validate source
  274. // TODO validate repositories
  275. // TODO validate package repositories' packages using this recursively
  276. $this->validateFlatArray('include-path');
  277. $this->validateArray('transport-options');
  278. // branch alias validation
  279. if (isset($this->config['extra']['branch-alias'])) {
  280. if (!is_array($this->config['extra']['branch-alias'])) {
  281. $this->errors[] = 'extra.branch-alias : must be an array of versions => aliases';
  282. } else {
  283. foreach ($this->config['extra']['branch-alias'] as $sourceBranch => $targetBranch) {
  284. // ensure it is an alias to a -dev package
  285. if ('-dev' !== substr($targetBranch, -4)) {
  286. $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must end in -dev';
  287. unset($this->config['extra']['branch-alias'][$sourceBranch]);
  288. continue;
  289. }
  290. // normalize without -dev and ensure it's a numeric branch that is parseable
  291. $validatedTargetBranch = $this->versionParser->normalizeBranch(substr($targetBranch, 0, -4));
  292. if ('-dev' !== substr($validatedTargetBranch, -4)) {
  293. $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must be a parseable number like 2.0-dev';
  294. unset($this->config['extra']['branch-alias'][$sourceBranch]);
  295. continue;
  296. }
  297. // If using numeric aliases ensure the alias is a valid subversion
  298. if (($sourcePrefix = $this->versionParser->parseNumericAliasPrefix($sourceBranch))
  299. && ($targetPrefix = $this->versionParser->parseNumericAliasPrefix($targetBranch))
  300. && (stripos($targetPrefix, $sourcePrefix) !== 0)
  301. ) {
  302. $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') is not a valid numeric alias for this version';
  303. unset($this->config['extra']['branch-alias'][$sourceBranch]);
  304. }
  305. }
  306. }
  307. }
  308. if ($this->errors) {
  309. throw new InvalidPackageException($this->errors, $this->warnings, $config);
  310. }
  311. $package = $this->loader->load($this->config, $class);
  312. $this->config = null;
  313. return $package;
  314. }
  315. public function getWarnings()
  316. {
  317. return $this->warnings;
  318. }
  319. public function getErrors()
  320. {
  321. return $this->errors;
  322. }
  323. private function validateRegex($property, $regex, $mandatory = false)
  324. {
  325. if (!$this->validateString($property, $mandatory)) {
  326. return false;
  327. }
  328. if (!preg_match('{^'.$regex.'$}u', $this->config[$property])) {
  329. $message = $property.' : invalid value ('.$this->config[$property].'), must match '.$regex;
  330. if ($mandatory) {
  331. $this->errors[] = $message;
  332. } else {
  333. $this->warnings[] = $message;
  334. }
  335. unset($this->config[$property]);
  336. return false;
  337. }
  338. return true;
  339. }
  340. private function validateString($property, $mandatory = false)
  341. {
  342. if (isset($this->config[$property]) && !is_string($this->config[$property])) {
  343. $this->errors[] = $property.' : should be a string, '.gettype($this->config[$property]).' given';
  344. unset($this->config[$property]);
  345. return false;
  346. }
  347. if (!isset($this->config[$property]) || trim($this->config[$property]) === '') {
  348. if ($mandatory) {
  349. $this->errors[] = $property.' : must be present';
  350. }
  351. unset($this->config[$property]);
  352. return false;
  353. }
  354. return true;
  355. }
  356. private function validateArray($property, $mandatory = false)
  357. {
  358. if (isset($this->config[$property]) && !is_array($this->config[$property])) {
  359. $this->errors[] = $property.' : should be an array, '.gettype($this->config[$property]).' given';
  360. unset($this->config[$property]);
  361. return false;
  362. }
  363. if (!isset($this->config[$property]) || !count($this->config[$property])) {
  364. if ($mandatory) {
  365. $this->errors[] = $property.' : must be present and contain at least one element';
  366. }
  367. unset($this->config[$property]);
  368. return false;
  369. }
  370. return true;
  371. }
  372. private function validateFlatArray($property, $regex = null, $mandatory = false)
  373. {
  374. if (!$this->validateArray($property, $mandatory)) {
  375. return false;
  376. }
  377. $pass = true;
  378. foreach ($this->config[$property] as $key => $value) {
  379. if (!is_string($value) && !is_numeric($value)) {
  380. $this->errors[] = $property.'.'.$key.' : must be a string or int, '.gettype($value).' given';
  381. unset($this->config[$property][$key]);
  382. $pass = false;
  383. continue;
  384. }
  385. if ($regex && !preg_match('{^'.$regex.'$}u', $value)) {
  386. $this->warnings[] = $property.'.'.$key.' : invalid value ('.$value.'), must match '.$regex;
  387. unset($this->config[$property][$key]);
  388. $pass = false;
  389. }
  390. }
  391. return $pass;
  392. }
  393. private function validateUrl($property, $mandatory = false)
  394. {
  395. if (!$this->validateString($property, $mandatory)) {
  396. return false;
  397. }
  398. if (!$this->filterUrl($this->config[$property])) {
  399. $this->warnings[] = $property.' : invalid value ('.$this->config[$property].'), must be an http/https URL';
  400. unset($this->config[$property]);
  401. return false;
  402. }
  403. return true;
  404. }
  405. private function filterUrl($value, array $schemes = array('http', 'https'))
  406. {
  407. if ($value === '') {
  408. return true;
  409. }
  410. $bits = parse_url($value);
  411. if (empty($bits['scheme']) || empty($bits['host'])) {
  412. return false;
  413. }
  414. if (!in_array($bits['scheme'], $schemes, true)) {
  415. return false;
  416. }
  417. return true;
  418. }
  419. }