You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

59691 lines
1.1 MiB

#!/usr/bin/env php
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view
* the license that is located at the bottom of this file.
*/
// Avoid APC causing random fatal errors per https://github.com/composer/composer/issues/264
if (extension_loaded('apc') && ini_get('apc.enable_cli') && ini_get('apc.cache_by_default')) {
if (version_compare(phpversion('apc'), '3.0.12', '>=')) {
ini_set('apc.cache_by_default', 0);
} else {
fwrite(STDERR, 'Warning: APC <= 3.0.12 may cause fatal errors when running composer commands.'.PHP_EOL);
fwrite(STDERR, 'Update APC, or set apc.enable_cli or apc.cache_by_default to 0 in your php.ini.'.PHP_EOL);
}
}
Phar::mapPhar('composer.phar');
define('COMPOSER_DEV_WARNING_TIME', 1435792229);
require 'phar://composer.phar/bin/composer';
__HALT_COMPILER(); ?>
}ui composer.phar+src/Composer/Autoload/AutoloadGenerator.php€EeYEU€E»26¶+src/Composer/Autoload/ClassMapGenerator.php eYEU …G®Ò¶src/Composer/Cache.phpReYEUR.Uȶ%src/Composer/Command/AboutCommand.php»eYEU»#{ik¶'src/Composer/Command/ArchiveCommand.phpeYEU¸Uöª¶*src/Composer/Command/ClearCacheCommand.phpZeYEUZ‰ì>¶ src/Composer/Command/Command.php‰eYEU‰µ vJ¶&src/Composer/Command/ConfigCommand.phpý4eYEUý4ø{_‡¶-src/Composer/Command/CreateProjectCommand.phpÇ1eYEUÇ1DYÝ¿¶'src/Composer/Command/DependsCommand.php„
eYEU„
È! "¶(src/Composer/Command/DiagnoseCommand.php­9eYEU­9P0«¶,src/Composer/Command/DumpAutoloadCommand.phpÿeYEUÿFZ¶&src/Composer/Command/GlobalCommand.phpeYEU©¨@•¶$src/Composer/Command/HomeCommand.php+eYEU+^š¶$src/Composer/Command/InitCommand.phpt8eYEUt8gãí¶'src/Composer/Command/InstallCommand.php#eYEU#=J%¶(src/Composer/Command/LicensesCommand.phpžeYEUž}ì´¿¶&src/Composer/Command/RemoveCommand.php^eYEU^$”žy¶'src/Composer/Command/RequireCommand.phpÂeYEUÂ9y¸B¶)src/Composer/Command/RunScriptCommand.php� eYEU� s£4¶+src/Composer/Command/ScriptAliasCommand.php²eYEU²ñÇ$½¶&src/Composer/Command/SearchCommand.phpl eYEUl ¶K4¶*src/Composer/Command/SelfUpdateCommand.php#eYEU#¡#ˆ)¶$src/Composer/Command/ShowCommand.phpò0eYEUò0Ù“ý¶&src/Composer/Command/StatusCommand.phpo eYEUo —²Î¶&src/Composer/Command/UpdateCommand.php*eYEU*Í
#ö(src/Composer/Command/ValidateCommand.php eYEU yw‚¶src/Composer/Composer.php) eYEU) ²Zô¶src/Composer/Config.phpíeYEUíþŒ¼&¶-src/Composer/Config/ConfigSourceInterface.php®eYEU®6J[ª¶(src/Composer/Config/JsonConfigSource.php“ eYEU“ *íÞT¶$src/Composer/Console/Application.phpX!eYEUX!È ’õ¶,src/Composer/Console/HtmlOutputFormatter.phpÎeYEUÎ๟„¶/src/Composer/DependencyResolver/DebugSolver.php‰eYEU‰£Ò­…¶-src/Composer/DependencyResolver/Decisions.phpQeYEUQ?˜¬$¶1src/Composer/DependencyResolver/DefaultPolicy.phpðeYEUð‰ho³¶>src/Composer/DependencyResolver/Operation/InstallOperation.phpCeYEUC´\õ*¶Isrc/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.phpÐeYEUÐxUZa¶Ksrc/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.phpÖeYEUÖ_iÇ«¶@src/Composer/DependencyResolver/Operation/OperationInterface.phpÓeYEUÓÙâ&ä¶=src/Composer/DependencyResolver/Operation/SolverOperation.phpëeYEUëħݔ¶@src/Composer/DependencyResolver/Operation/UninstallOperation.phpIeYEUIFûÂɶ=src/Composer/DependencyResolver/Operation/UpdateOperation.phpheYEUhöSÕ]¶3src/Composer/DependencyResolver/PolicyInterface.php’eYEU’n°&³¶(src/Composer/DependencyResolver/Pool.phpý!eYEUý!†6ð¶+src/Composer/DependencyResolver/Problem.php+eYEU+˜:$�¶+src/Composer/DependencyResolver/Request.phpœeYEUœfDC¶(src/Composer/DependencyResolver/Rule.php$eYEU$KüÈý¶+src/Composer/DependencyResolver/RuleSet.php%
eYEU%
9z ¶4src/Composer/DependencyResolver/RuleSetGenerator.php]eYEU]4“Ñ9¶3src/Composer/DependencyResolver/RuleSetIterator.phpeYEU}õÇù¶2src/Composer/DependencyResolver/RuleWatchChain.phpieYEUihïš,¶2src/Composer/DependencyResolver/RuleWatchGraph.phpÜeYEU܉8¶1src/Composer/DependencyResolver/RuleWatchNode.phpçeYEUç—Þȶ*src/Composer/DependencyResolver/Solver.php
7eYEU
7I©-!¶6src/Composer/DependencyResolver/SolverBugException.php˜eYEU˜"qN¶;src/Composer/DependencyResolver/SolverProblemsException.php%eYEU%TíP¶/src/Composer/DependencyResolver/Transaction.phpÔeYEUÔ 3ô¶-src/Composer/Downloader/ArchiveDownloader.php  eYEU  жTj¶1src/Composer/Downloader/ChangeReportInterface.phpÌeYEU̯ਿ¶+src/Composer/Downloader/DownloadManager.php‘eYEU‘'oÅb¶/src/Composer/Downloader/DownloaderInterface.phpÊeYEUÊgs!l¶*src/Composer/Downloader/FileDownloader.php¦eYEU¦c‹ζ/src/Composer/Downloader/FilesystemException.phpeYEU]T½ˆ¶)src/Composer/Downloader/GitDownloader.phpv#eYEUv#Ö‹fʶ*src/Composer/Downloader/GzipDownloader.phpÈeYEUÈ­äßж(src/Composer/Downloader/HgDownloader.phpceYEUc‡‚T„¶0src/Composer/Downloader/PearPackageExtractor.phpaeYEUa@ÔØ#¶.src/Composer/Downloader/PerforceDownloader.phpxeYEUx<éc¶*src/Composer/Downloader/PharDownloader.phpåeYEUåÞÉç¶)src/Composer/Downloader/RarDownloader.phpßeYEUß¾¼¶)src/Composer/Downloader/SvnDownloader.php\eYEU\¨Ž=¶)src/Composer/Downloader/TarDownloader.phpãeYEUãÍ’X?¶.src/Composer/Downloader/TransportException.php–eYEU–h"Br¶)src/Composer/Downloader/VcsDownloader.php÷eYEU÷«‘ßò¶)src/Composer/Downloader/ZipDownloader.phpC eYEUC ]^+¶&src/Composer/EventDispatcher/Event.php eYEU ±™jï¶0src/Composer/EventDispatcher/EventDispatcher.phpšeYEUšW¶9src/Composer/EventDispatcher/EventSubscriberInterface.php©eYEU©h·0¶src/Composer/Factory.php-eYEU-ß„°á¶src/Composer/IO/BaseIO.phppeYEUpÈNñZ¶src/Composer/IO/BufferIO.phpeYEUhvá¶src/Composer/IO/ConsoleIO.phpheYEUh¿*]Ŷsrc/Composer/IO/IOInterface.php†eYEU†
žÕ8¶src/Composer/IO/NullIO.php³eYEU³~1Ķsrc/Composer/Installer.phpÿ~eYEUÿ~ìíw¶.src/Composer/Installer/InstallationManager.php@eYEU@›ö«¶)src/Composer/Installer/InstallerEvent.phpeYEUlÔzi¶*src/Composer/Installer/InstallerEvents.phpÞeYEUÞìŸ@G¶-src/Composer/Installer/InstallerInterface.phpÅeYEUÅHS“¡¶+src/Composer/Installer/LibraryInstaller.php‰eYEU‰†ƒ­¶/src/Composer/Installer/MetapackageInstaller.phpœeYEUœÆÅ!¶(src/Composer/Installer/NoopInstaller.php+eYEU+À·M}¶'src/Composer/Installer/PackageEvent.php‰eYEU‰‘: ¶(src/Composer/Installer/PackageEvents.php¸eYEU¸dbØs¶(src/Composer/Installer/PearInstaller.phpVeYEUV�zð¶*src/Composer/Installer/PluginInstaller.phpJeYEUJ«èV¶+src/Composer/Installer/ProjectInstaller.phpeYEU*0@P¶src/Composer/Json/JsonFile.phpeYEUoö…Á¶#src/Composer/Json/JsonFormatter.phpeYEUc–]Y¶%src/Composer/Json/JsonManipulator.php*eYEU*r% ¶-src/Composer/Json/JsonValidationException.php\eYEU\.Xóܶ%src/Composer/Package/AliasPackage.phpeYEUR³¶Ð¶7src/Composer/Package/Archiver/ArchivableFilesFinder.php¿eYEU¿ŽcEl¶0src/Composer/Package/Archiver/ArchiveManager.php' eYEU' é‰ô¶3src/Composer/Package/Archiver/ArchiverInterface.phpïeYEUï<ʸ¶3src/Composer/Package/Archiver/BaseExcludeFilter.php‘eYEU‘Mù¶7src/Composer/Package/Archiver/ComposerExcludeFilter.phpeYEU‹SZ0¶2src/Composer/Package/Archiver/GitExcludeFilter.phpweYEUwLgU»¶1src/Composer/Package/Archiver/HgExcludeFilter.phpeYEU~”¸¶.src/Composer/Package/Archiver/PharArchiver.php[eYEU[Ê5Íø¶$src/Composer/Package/BasePackage.phpM eYEUM · %þ¶(src/Composer/Package/CompletePackage.phpÿeYEUÿo+ã ¶1src/Composer/Package/CompletePackageInterface.phpõeYEUõ¦Ê�ò¶+src/Composer/Package/Dumper/ArrayDumper.phpì eYEUì ª–æ¶src/Composer/Package/Link.php*eYEU*_’…¶7src/Composer/Package/LinkConstraint/EmptyConstraint.phpêeYEUê쾶?src/Composer/Package/LinkConstraint/LinkConstraintInterface.phpeYEUåþ‡¢¶7src/Composer/Package/LinkConstraint/MultiConstraint.phpgeYEUgs3¶:src/Composer/Package/LinkConstraint/SpecificConstraint.phppeYEUp_„ˆY¶9src/Composer/Package/LinkConstraint/VersionConstraint.phpÉeYEUÉy?³Ø¶+src/Composer/Package/Loader/ArrayLoader.phpeYEUIû˶7src/Composer/Package/Loader/InvalidPackageException.phpEeYEUExb¾¶*src/Composer/Package/Loader/JsonLoader.phpùeYEUù!~ˆ{¶/src/Composer/Package/Loader/LoaderInterface.php²eYEU²¦}úζ1src/Composer/Package/Loader/RootPackageLoader.phpS"eYEUS"ð¨<¶5src/Composer/Package/Loader/ValidatingArrayLoader.phpÙ/eYEUÙ/1¯…K¶src/Composer/Package/Locker.phpñeYEUñm=3­¶ src/Composer/Package/Package.phpÄeYEUÄ„ô¶)src/Composer/Package/PackageInterface.php_eYEU_戹‚¶)src/Composer/Package/RootAliasPackage.phpyeYEUyÀE'¶$src/Composer/Package/RootPackage.phpneYEUnáACO¶-src/Composer/Package/RootPackageInterface.php´eYEU´êqKж.src/Composer/Package/Version/VersionParser.phpï-eYEUï-êâ°r¶0src/Composer/Package/Version/VersionSelector.phpƒeYEUƒ»j6¶$src/Composer/Plugin/CommandEvent.phpâeYEUâ³ÆÇW¶$src/Composer/Plugin/PluginEvents.php¤eYEU¤0ïÞX¶'src/Composer/Plugin/PluginInterface.phpôeYEUô 1‰%¶%src/Composer/Plugin/PluginManager.phpveYEUvšU�i¶,src/Composer/Plugin/PreFileDownloadEvent.php`eYEU`9-ζ+src/Composer/Repository/ArrayRepository.php eYEU ´¯Þ/¶.src/Composer/Repository/ArtifactRepository.phpë
eYEUë
šÏoð¶.src/Composer/Repository/ComposerRepository.php¤>eYEU¤>Þè¶/src/Composer/Repository/CompositeRepository.php eYEU 4úE¶0src/Composer/Repository/FilesystemRepository.phpÀeYEUÀ&xb£¶4src/Composer/Repository/InstalledArrayRepository.php£eYEU£/ö~>¶9src/Composer/Repository/InstalledFilesystemRepository.php£eYEU£V
•_¶8src/Composer/Repository/InstalledRepositoryInterface.php‡eYEU‡£9p¶6src/Composer/Repository/InvalidRepositoryException.phpneYEUnà“똶-src/Composer/Repository/PackageRepository.phpGeYEUGí:k¶2src/Composer/Repository/Pear/BaseChannelReader.php6eYEU6.fi!¶,src/Composer/Repository/Pear/ChannelInfo.phpÄeYEUÄ:T*ɶ.src/Composer/Repository/Pear/ChannelReader.phpneYEUnš8¶4src/Composer/Repository/Pear/ChannelRest10Reader.phpÁ eYEUÁ O€ë¶4src/Composer/Repository/Pear/ChannelRest11Reader.php& eYEU& òUb¶5src/Composer/Repository/Pear/DependencyConstraint.phpqeYEUq9=¶/src/Composer/Repository/Pear/DependencyInfo.phpqeYEUqfºTò¶8src/Composer/Repository/Pear/PackageDependencyParser.php%eYEU%j?“¶,src/Composer/Repository/Pear/PackageInfo.php°eYEU°Ÿ ¸ ¶,src/Composer/Repository/Pear/ReleaseInfo.php’eYEU’o“ŠÃ¶*src/Composer/Repository/PearRepository.php°eYEU°
,B·¶.src/Composer/Repository/PlatformRepository.php�eYEU�:§ÕA¶/src/Composer/Repository/RepositoryInterface.phpÔeYEUÔò�ŸÉ¶-src/Composer/Repository/RepositoryManager.php³eYEU³33¸ï¶7src/Composer/Repository/RepositorySecurityException.phpoeYEUopÕ«ª¶2src/Composer/Repository/Vcs/GitBitbucketDriver.phpì eYEUì Fÿô¶)src/Composer/Repository/Vcs/GitDriver.phpeYEU\îï¶,src/Composer/Repository/Vcs/GitHubDriver.phpr'eYEUr'".j0¶1src/Composer/Repository/Vcs/HgBitbucketDriver.phpô eYEUô ˜áWõ¶(src/Composer/Repository/Vcs/HgDriver.phpàeYEUàñ‘綶.src/Composer/Repository/Vcs/PerforceDriver.php!
eYEU!
�€Ùk¶)src/Composer/Repository/Vcs/SvnDriver.php²eYEU²Ë W¶)src/Composer/Repository/Vcs/VcsDriver.phpÑeYEUÑå%R¶2src/Composer/Repository/Vcs/VcsDriverInterface.php‰eYEU‰pO㤶)src/Composer/Repository/VcsRepository.php@eYEU@ƒ²£«¶3src/Composer/Repository/WritableArrayRepository.phpeYEU¾G*¶7src/Composer/Repository/WritableRepositoryInterface.php‰eYEU‰‘/sï¶$src/Composer/Script/CommandEvent.phpWeYEUW£VZt¶src/Composer/Script/Event.phpµeYEUµlt¦M¶$src/Composer/Script/PackageEvent.phpœeYEUœ§ÿÉ ¶$src/Composer/Script/ScriptEvents.phpPeYEUPìhQ¶ src/Composer/Util/AuthHelper.phpËeYEUË>zx–¶$src/Composer/Util/ComposerMirror.php±eYEU±­½øض%src/Composer/Util/ConfigValidator.php(eYEU(=_õT¶"src/Composer/Util/ErrorHandler.phpeYEU´@…æ¶ src/Composer/Util/Filesystem.php4&eYEU4&Rl—‡¶src/Composer/Util/Git.phpeYEUOš½é¶src/Composer/Util/GitHub.php^eYEU^ŒùX¶$src/Composer/Util/NoProxyPattern.php¾eYEU¾Z+°m¶src/Composer/Util/Perforce.php3eYEU3‚=e.¶%src/Composer/Util/ProcessExecutor.phpîeYEUîÔÀ¶&src/Composer/Util/RemoteFilesystem.php¹%eYEU¹%eÃ'¶!src/Composer/Util/SpdxLicense.php± eYEU± ›a’9¶)src/Composer/Util/SpdxLicensesUpdater.phpqeYEUqÈ×ê¶*src/Composer/Util/StreamContextFactory.phpâ eYEUâ Ð B¶src/Composer/Util/Svn.phpGeYEUGD§¶src/bootstrap.phpÅeYEUŨ¯2�¶%src/Composer/Autoload/ClassLoader.php„0eYEU„0&’Þ=¶res/composer-schema.jsonìReYEUìRå”_¶res/spdx-licenses.jsonâ`eYEUâ`’’þ¶*vendor/seld/cli-prompt/res/hiddeninput.exe$eYEU$•�¥v¶@vendor/symfony/console/Symfony/Component/Console/Application.php¶ReYEU¶R6ÝXñ¶Dvendor/symfony/console/Symfony/Component/Console/Command/Command.phpðeYEUðpŶHvendor/symfony/console/Symfony/Component/Console/Command/HelpCommand.php6eYEU6#¯¾}¶Hvendor/symfony/console/Symfony/Component/Console/Command/ListCommand.php³eYEU³VÓé¶Bvendor/symfony/console/Symfony/Component/Console/ConsoleEvents.phpïeYEUï ÕH¸¶Vvendor/symfony/console/Symfony/Component/Console/Descriptor/ApplicationDescription.phpùeYEUù‰>O¶Jvendor/symfony/console/Symfony/Component/Console/Descriptor/Descriptor.php\eYEU\WJ[í¶Svendor/symfony/console/Symfony/Component/Console/Descriptor/DescriptorInterface.phpüeYEUü±Qµ¶Nvendor/symfony/console/Symfony/Component/Console/Descriptor/JsonDescriptor.php2 eYEU2 †ca¶Rvendor/symfony/console/Symfony/Component/Console/Descriptor/MarkdownDescriptor.php
eYEU
LÛ*¶Nvendor/symfony/console/Symfony/Component/Console/Descriptor/TextDescriptor.php6eYEU6ªàí;¶Mvendor/symfony/console/Symfony/Component/Console/Descriptor/XmlDescriptor.php eYEU …{îm¶Nvendor/symfony/console/Symfony/Component/Console/Event/ConsoleCommandEvent.php²eYEU²Zk‰2¶Gvendor/symfony/console/Symfony/Component/Console/Event/ConsoleEvent.phpÅeYEUÅÒxÛ\¶Pvendor/symfony/console/Symfony/Component/Console/Event/ConsoleExceptionEvent.phpeYEUá2é¶Pvendor/symfony/console/Symfony/Component/Console/Event/ConsoleTerminateEvent.phpzeYEUz³,îL¶Nvendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatter.phpf eYEUf Kdÿ-¶Wvendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterInterface.php˜eYEU˜3l~´¶Svendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyle.php·eYEU·ÇÅK¶\vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleInterface.phpŽeYEUŽöëÄ=¶Xvendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleStack.php
eYEU
,½-¶Pvendor/symfony/console/Symfony/Component/Console/Helper/DebugFormatterHelper.phpmeYEUmò¯s>¶Lvendor/symfony/console/Symfony/Component/Console/Helper/DescriptorHelper.php9eYEU9ûùäð¶Hvendor/symfony/console/Symfony/Component/Console/Helper/DialogHelper.phpÊeYEUÊ�°ë¥¶Kvendor/symfony/console/Symfony/Component/Console/Helper/FormatterHelper.phpceYEUc“ý«N¶Bvendor/symfony/console/Symfony/Component/Console/Helper/Helper.phpßeYEUßo¾ã¶Kvendor/symfony/console/Symfony/Component/Console/Helper/HelperInterface.phpïeYEUï=e ¶Evendor/symfony/console/Symfony/Component/Console/Helper/HelperSet.php/eYEU/âwd¶Lvendor/symfony/console/Symfony/Component/Console/Helper/InputAwareHelper.phpceYEUcñø�|¶Ivendor/symfony/console/Symfony/Component/Console/Helper/ProcessHelper.phpâeYEUâ|̼¶Gvendor/symfony/console/Symfony/Component/Console/Helper/ProgressBar.php$eYEU$2Œ5J¶Jvendor/symfony/console/Symfony/Component/Console/Helper/ProgressHelper.phpƒeYEUƒ“h™¶Jvendor/symfony/console/Symfony/Component/Console/Helper/QuestionHelper.phpeYEUR Š¶Avendor/symfony/console/Symfony/Component/Console/Helper/Table.phpeYEU{ŸV‚¶Gvendor/symfony/console/Symfony/Component/Console/Helper/TableHelper.phpØ
eYEUØ
,  ¶Jvendor/symfony/console/Symfony/Component/Console/Helper/TableSeparator.php[eYEU[LV¡¶Fvendor/symfony/console/Symfony/Component/Console/Helper/TableStyle.phpÕeYEUÕæ"ðù¶Dvendor/symfony/console/Symfony/Component/Console/Input/ArgvInput.phpÙeYEUÙËkE¶Evendor/symfony/console/Symfony/Component/Console/Input/ArrayInput.phpû eYEUû âö¥p¶@vendor/symfony/console/Symfony/Component/Console/Input/Input.php
eYEU
ÇýT¶Hvendor/symfony/console/Symfony/Component/Console/Input/InputArgument.phpžeYEUžK]ìi¶Nvendor/symfony/console/Symfony/Component/Console/Input/InputAwareInterface.phpšeYEUš‡jTŸ¶Jvendor/symfony/console/Symfony/Component/Console/Input/InputDefinition.php eYEU ˜£JM¶Ivendor/symfony/console/Symfony/Component/Console/Input/InputInterface.php eYEU 9”øǶFvendor/symfony/console/Symfony/Component/Console/Input/InputOption.php« eYEU« ꆮ½¶Fvendor/symfony/console/Symfony/Component/Console/Input/StringInput.php‹eYEU‹†uný¶8vendor/symfony/console/Symfony/Component/Console/LICENSE)eYEU)ë&•¶Ivendor/symfony/console/Symfony/Component/Console/Logger/ConsoleLogger.php; eYEU; #ØB~¶Jvendor/symfony/console/Symfony/Component/Console/Output/BufferedOutput.php_eYEU_ûBÍ·¶Ivendor/symfony/console/Symfony/Component/Console/Output/ConsoleOutput.phpeYEUj嬶Rvendor/symfony/console/Symfony/Component/Console/Output/ConsoleOutputInterface.phpåeYEUårNô¶Fvendor/symfony/console/Symfony/Component/Console/Output/NullOutput.php¿eYEU¿`5E˶Bvendor/symfony/console/Symfony/Component/Console/Output/Output.php§eYEU§Ú _¶Kvendor/symfony/console/Symfony/Component/Console/Output/OutputInterface.phpIeYEUIÈâãB¶Hvendor/symfony/console/Symfony/Component/Console/Output/StreamOutput.php¢eYEU¢ü0¶Lvendor/symfony/console/Symfony/Component/Console/Question/ChoiceQuestion.phpfeYEUfÔh¶Rvendor/symfony/console/Symfony/Component/Console/Question/ConfirmationQuestion.phpKeYEUKõÃTȶFvendor/symfony/console/Symfony/Component/Console/Question/Question.php®eYEU®.e8Ö¶:vendor/symfony/console/Symfony/Component/Console/Shell.php.eYEU.þÉŽ‡¶Mvendor/symfony/console/Symfony/Component/Console/Tester/ApplicationTester.phpÔeYEUÔ¬ì¤d¶Ivendor/symfony/console/Symfony/Component/Console/Tester/CommandTester.php�eYEU�H»â`¶Jvendor/symfony/finder/Symfony/Component/Finder/Adapter/AbstractAdapter.php¤
eYEU¤
¢)z9¶Nvendor/symfony/finder/Symfony/Component/Finder/Adapter/AbstractFindAdapter.phpÝeYEUÝÞ_“ø¶Kvendor/symfony/finder/Symfony/Component/Finder/Adapter/AdapterInterface.php¯eYEU¯‹éȶIvendor/symfony/finder/Symfony/Component/Finder/Adapter/BsdFindAdapter.php{eYEU{Q,D2¶Ivendor/symfony/finder/Symfony/Component/Finder/Adapter/GnuFindAdapter.php^eYEU^ßz˜r¶Evendor/symfony/finder/Symfony/Component/Finder/Adapter/PhpAdapter.php+eYEU+&˜îÒ¶Hvendor/symfony/finder/Symfony/Component/Finder/Comparator/Comparator.phpŒeYEUŒwþT¶Lvendor/symfony/finder/Symfony/Component/Finder/Comparator/DateComparator.php%eYEU%L¿EǶNvendor/symfony/finder/Symfony/Component/Finder/Comparator/NumberComparator.php~eYEU~”‡ x¶Rvendor/symfony/finder/Symfony/Component/Finder/Exception/AccessDeniedException.php„eYEU„½¾sœ¶Tvendor/symfony/finder/Symfony/Component/Finder/Exception/AdapterFailureException.phpeYEUmŒ_,¶Ovendor/symfony/finder/Symfony/Component/Finder/Exception/ExceptionInterface.php„eYEU„Gz-¶Zvendor/symfony/finder/Symfony/Component/Finder/Exception/OperationNotPermitedException.phpŠeYEUŠU88¶Yvendor/symfony/finder/Symfony/Component/Finder/Exception/ShellCommandFailureException.php$eYEU$C”sÓ¶Hvendor/symfony/finder/Symfony/Component/Finder/Expression/Expression.php}eYEU}/·cð¶Bvendor/symfony/finder/Symfony/Component/Finder/Expression/Glob.php¡eYEU¡ V¿¶Cvendor/symfony/finder/Symfony/Component/Finder/Expression/Regex.php�eYEU�S7Pæ¶Lvendor/symfony/finder/Symfony/Component/Finder/Expression/ValueInterface.php;eYEU; îãÓ¶9vendor/symfony/finder/Symfony/Component/Finder/Finder.phpú"eYEUú"gƒ¶7vendor/symfony/finder/Symfony/Component/Finder/Glob.php eYEU z�ø
¶Pvendor/symfony/finder/Symfony/Component/Finder/Iterator/CustomFilterIterator.php]eYEU]tà±µ¶Svendor/symfony/finder/Symfony/Component/Finder/Iterator/DateRangeFilterIterator.phpzeYEUz}¢¶Tvendor/symfony/finder/Symfony/Component/Finder/Iterator/DepthRangeFilterIterator.phpðeYEUðß0™¶Zvendor/symfony/finder/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php”eYEU”"ÖóÁ¶Mvendor/symfony/finder/Symfony/Component/Finder/Iterator/FilePathsIterator.php�eYEU�ýòäQ¶Rvendor/symfony/finder/Symfony/Component/Finder/Iterator/FileTypeFilterIterator.php\eYEU\p‘'˜¶Uvendor/symfony/finder/Symfony/Component/Finder/Iterator/FilecontentFilterIterator.php#eYEU#Ú_VǶRvendor/symfony/finder/Symfony/Component/Finder/Iterator/FilenameFilterIterator.php‡eYEU‡F ’ ¶Jvendor/symfony/finder/Symfony/Component/Finder/Iterator/FilterIterator.php†eYEU†0£¾Ô¶Vvendor/symfony/finder/Symfony/Component/Finder/Iterator/MultiplePcreFilterIterator.phpØeYEUØÒù“¶Nvendor/symfony/finder/Symfony/Component/Finder/Iterator/PathFilterIterator.php¸eYEU¸E*E¶Vvendor/symfony/finder/Symfony/Component/Finder/Iterator/RecursiveDirectoryIterator.phpYeYEUYêÓÊܶSvendor/symfony/finder/Symfony/Component/Finder/Iterator/SizeRangeFilterIterator.phpgeYEUg!Ô—é¶Lvendor/symfony/finder/Symfony/Component/Finder/Iterator/SortableIterator.phpÞeYEUÞö³%¶6vendor/symfony/finder/Symfony/Component/Finder/LICENSE)eYEU)ë&•¶@vendor/symfony/finder/Symfony/Component/Finder/Shell/Command.php¥
eYEU¥
†€þŠ¶>vendor/symfony/finder/Symfony/Component/Finder/Shell/Shell.phpéeYEUé¿ëÛ•¶>vendor/symfony/finder/Symfony/Component/Finder/SplFileInfo.phpûeYEUû‘†6¶Qvendor/symfony/process/Symfony/Component/Process/Exception/ExceptionInterface.phpfeYEUf]ö>T¶Wvendor/symfony/process/Symfony/Component/Process/Exception/InvalidArgumentException.php¨eYEU¨ÐÀ+_¶Mvendor/symfony/process/Symfony/Component/Process/Exception/LogicException.php”eYEU” ³ãñ¶Uvendor/symfony/process/Symfony/Component/Process/Exception/ProcessFailedException.php<eYEU<"wÛn¶Wvendor/symfony/process/Symfony/Component/Process/Exception/ProcessTimedOutException.phpeYEU. Ãá¶Ovendor/symfony/process/Symfony/Component/Process/Exception/RuntimeException.php˜eYEU˜¢Ø:¶Evendor/symfony/process/Symfony/Component/Process/ExecutableFinder.php~eYEU~+…¶8vendor/symfony/process/Symfony/Component/Process/LICENSE)eYEU)ë&•¶Hvendor/symfony/process/Symfony/Component/Process/PhpExecutableFinder.phpeYEUûÔM>¶?vendor/symfony/process/Symfony/Component/Process/PhpProcess.php×eYEU׊€«¶Hvendor/symfony/process/Symfony/Component/Process/Pipes/AbstractPipes.phpeYEU˜|¥¾¶Ivendor/symfony/process/Symfony/Component/Process/Pipes/PipesInterface.phpDeYEUDvØDvendor/symfony/process/Symfony/Component/Process/Pipes/UnixPipes.php¤ eYEU¤ øUt¶Gvendor/symfony/process/Symfony/Component/Process/Pipes/WindowsPipes.php½eYEU½.X£¶<vendor/symfony/process/Symfony/Component/Process/Process.phpÚNeYEUÚNZEkv¶Cvendor/symfony/process/Symfony/Component/Process/ProcessBuilder.php eYEU �ïy¶Avendor/symfony/process/Symfony/Component/Process/ProcessUtils.phpŒeYEUŒÈbÝv¶vendor/seld/jsonlint/LICENSE"eYEU"aƒsy¶5vendor/seld/jsonlint/src/Seld/JsonLint/JsonParser.php)1eYEU)1?5R3¶0vendor/seld/jsonlint/src/Seld/JsonLint/Lexer.phpeYEU‰„m!¶;vendor/seld/jsonlint/src/Seld/JsonLint/ParsingException.phpeYEU‰²ñ¶4vendor/seld/jsonlint/src/Seld/JsonLint/Undefined.php>eYEU>ÿqŸŸ¶vendor/seld/cli-prompt/LICENSE"eYEU"ˆñ?e¶&vendor/seld/cli-prompt/res/example.php'eYEU'I£¶(vendor/seld/cli-prompt/src/CliPrompt.phpeYEU­é™v¶(vendor/justinrainbow/json-schema/LICENSE÷eYEU÷xÞxt¶Tvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/CollectionConstraint.php eYEU »~«x¶Jvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Constraint.php‰eYEU‰!Êf¹¶Svendor/justinrainbow/json-schema/src/JsonSchema/Constraints/ConstraintInterface.phpNeYEUNøÆMy¶Nvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/EnumConstraint.phpOeYEUO&.˶Pvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/FormatConstraint.php÷ eYEU÷ øî½K¶Pvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/NumberConstraint.phpµeYEUµ–è¸L¶Pvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/ObjectConstraint.phpæ
eYEUæ
·E˜¶Pvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/SchemaConstraint.php eYEU ÈÌÕâ¶Pvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/StringConstraint.php©eYEU©mòeà¶Nvendor/justinrainbow/json-schema/src/JsonSchema/Constraints/TypeConstraint.php|eYEU|,$¢Û¶Svendor/justinrainbow/json-schema/src/JsonSchema/Constraints/UndefinedConstraint.phpžeYEUžï®¶Vvendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidArgumentException.phpveYEUv¬ «"¶]vendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidSchemaMediaTypeException.phpveYEUvŠCÓ¶Wvendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidSourceUriException.phpweYEUwN-ò[¶Svendor/justinrainbow/json-schema/src/JsonSchema/Exception/JsonDecodingException.phpÞeYEUÞ†¾©‘¶Wvendor/justinrainbow/json-schema/src/JsonSchema/Exception/ResourceNotFoundException.phpoeYEUoÆ$"ŶRvendor/justinrainbow/json-schema/src/JsonSchema/Exception/UriResolverException.phpjeYEUjSÓdz¶?vendor/justinrainbow/json-schema/src/JsonSchema/RefResolver.php|
eYEU|
™& i¶Tvendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/AbstractRetriever.phpÜeYEUÜ]j¶Gvendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/Curl.phpteYEUtI·ý¶Rvendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/FileGetContents.phpÑeYEUÑ懨¶Rvendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/PredefinedArray.php^eYEU^"ß6o¶Xvendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/UriRetrieverInterface.php©eYEU©CO¶Cvendor/justinrainbow/json-schema/src/JsonSchema/Uri/UriResolver.php® eYEU® àP¾¡¶Dvendor/justinrainbow/json-schema/src/JsonSchema/Uri/UriRetriever.php–eYEU–ªÿ¨Ü¶=vendor/justinrainbow/json-schema/src/JsonSchema/Validator.php‡eYEU‡-Úô¶vendor/autoload.php‡eYEU‡%ååY¶'vendor/composer/autoload_namespaces.php±eYEU±[®ã¶!vendor/composer/autoload_psr4.php8eYEU8‰ÕEz¶%vendor/composer/autoload_classmap.phpdeYEUdZ¡¦H¶!vendor/composer/autoload_real.php7eYEU7ƒ#ãï¶!vendor/composer/include_paths.php²eYEU²õE¶vendor/composer/ClassLoader.php2eYEU2+¡ÚK¶ bin/composerleYEUlԚà ¶LICENSE3eYEU3fýÞX¶<?php
namespace Composer\Autoload;
use Composer\Config;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Installer\InstallationManager;
use Composer\IO\IOInterface;
use Composer\Package\AliasPackage;
use Composer\Package\PackageInterface;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Util\Filesystem;
use Composer\Script\ScriptEvents;
class AutoloadGenerator
{
private $eventDispatcher;
private $io;
private $devMode = false;
public function __construct(EventDispatcher $eventDispatcher, IOInterface $io = null)
{
$this->eventDispatcher = $eventDispatcher;
$this->io = $io;
}
public function setDevMode($devMode = true)
{
$this->devMode = (boolean) $devMode;
}
public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
{
$this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, array(), array(
'optimize' => (bool) $scanPsr0Packages,
));
$filesystem = new Filesystem();
$filesystem->ensureDirectoryExists($config->get('vendor-dir'));
$basePath = $filesystem->normalizePath(realpath(getcwd()));
$vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
$useGlobalIncludePath = (bool) $config->get('use-include-path');
$prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
$classMapAuthoritative = $config->get('classmap-authoritative');
$targetDir = $vendorPath.'/'.$targetDir;
$filesystem->ensureDirectoryExists($targetDir);
$vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
$vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
$vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
$appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
$appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
$namespacesFile = <<<EOF
<?php
// autoload_namespaces.php @generated by Composer
\$vendorDir = $vendorPathCode52;
\$baseDir = $appBaseDirCode;
return array(
EOF;
$psr4File = <<<EOF
<?php
// autoload_psr4.php @generated by Composer
\$vendorDir = $vendorPathCode52;
\$baseDir = $appBaseDirCode;
return array(
EOF;
$packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages());
$autoloads = $this->parseAutoloads($packageMap, $mainPackage);
foreach ($autoloads['psr-0'] as $namespace => $paths) {
$exportedPaths = array();
foreach ($paths as $path) {
$exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
}
$exportedPrefix = var_export($namespace, true);
$namespacesFile .= " $exportedPrefix => ";
$namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n";
}
$namespacesFile .= ");\n";
foreach ($autoloads['psr-4'] as $namespace => $paths) {
$exportedPaths = array();
foreach ($paths as $path) {
$exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
}
$exportedPrefix = var_export($namespace, true);
$psr4File .= " $exportedPrefix => ";
$psr4File .= "array(".implode(', ', $exportedPaths)."),\n";
}
$psr4File .= ");\n";
$classmapFile = <<<EOF
<?php
// autoload_classmap.php @generated by Composer
\$vendorDir = $vendorPathCode52;
\$baseDir = $appBaseDirCode;
return array(
EOF;
$targetDirLoader = null;
$mainAutoload = $mainPackage->getAutoload();
if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
$levels = count(explode('/', $filesystem->normalizePath($mainPackage->getTargetDir())));
$prefixes = implode(', ', array_map(function ($prefix) {
return var_export($prefix, true);
}, array_keys($mainAutoload['psr-0'])));
$baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
$targetDirLoader = <<<EOF
public static function autoload(\$class)
{
\$dir = $baseDirFromTargetDirCode . '/';
\$prefixes = array($prefixes);
foreach (\$prefixes as \$prefix) {
if (0 !== strpos(\$class, \$prefix)) {
continue;
}
\$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php';
if (!\$path = stream_resolve_include_path(\$path)) {
return false;
}
require \$path;
return true;
}
}
EOF;
}
$classMap = array();
if ($scanPsr0Packages) {
foreach (array('psr-0', 'psr-4') as $psrType) {
foreach ($autoloads[$psrType] as $namespace => $paths) {
foreach ($paths as $dir) {
$dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath.'/'.$dir);
if (!is_dir($dir)) {
continue;
}
$whitelist = sprintf(
'{%s/%s.+(?<!(?<!/)Test\.php)$}',
preg_quote($dir),
($psrType === 'psr-0' && strpos($namespace, '_') === false) ? preg_quote(strtr($namespace, '\\', '/')) : ''
);
$namespaceFilter = $namespace === '' ? null : $namespace;
foreach (ClassMapGenerator::createMap($dir, $whitelist, $this->io, $namespaceFilter) as $class => $path) {
if (!isset($classMap[$class])) {
$path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
$classMap[$class] = $path.",\n";
}
}
}
}
}
}
foreach ($autoloads['classmap'] as $dir) {
foreach (ClassMapGenerator::createMap($dir, null, $this->io) as $class => $path) {
$path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
$classMap[$class] = $path.",\n";
}
}
ksort($classMap);
foreach ($classMap as $class => $code) {
$classmapFile .= ' '.var_export($class, true).' => '.$code;
}
$classmapFile .= ");\n";
if (!$suffix) {
if (!$config->get('autoloader-suffix') && is_readable($vendorPath.'/autoload.php')) {
$content = file_get_contents($vendorPath.'/autoload.php');
if (preg_match('{ComposerAutoloaderInit([^:\s]+)::}', $content, $match)) {
$suffix = $match[1];
}
}
if (!$suffix) {
$suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
}
}
file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
file_put_contents($targetDir.'/autoload_psr4.php', $psr4File);
file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
file_put_contents($targetDir.'/include_paths.php', $includePathFile);
}
if ($includeFilesFile = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
file_put_contents($targetDir.'/autoload_files.php', $includeFilesFile);
}
file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFile, $targetDirLoader, (bool) $includeFilesFile, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $classMapAuthoritative));
$sourceLoader = fopen(__DIR__.'/ClassLoader.php', 'r');
$targetLoader = fopen($targetDir.'/ClassLoader.php', 'w+');
stream_copy_to_stream($sourceLoader, $targetLoader);
fclose($sourceLoader);
fclose($targetLoader);
unset($sourceLoader, $targetLoader);
$this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, array(), array(
'optimize' => (bool) $scanPsr0Packages,
));
}
public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
{
$packageMap = array(array($mainPackage, ''));
foreach ($packages as $package) {
if ($package instanceof AliasPackage) {
continue;
}
$this->validatePackage($package);
$packageMap[] = array(
$package,
$installationManager->getInstallPath($package),
);
}
return $packageMap;
}
protected function validatePackage(PackageInterface $package)
{
$autoload = $package->getAutoload();
if (!empty($autoload['psr-4']) && null !== $package->getTargetDir()) {
$name = $package->getName();
$package->getTargetDir();
throw new \InvalidArgumentException("PSR-4 autoloading is incompatible with the target-dir property, remove the target-dir in package '$name'.");
}
if (!empty($autoload['psr-4'])) {
foreach ($autoload['psr-4'] as $namespace => $dirs) {
if ($namespace !== '' && '\\' !== substr($namespace, -1)) {
throw new \InvalidArgumentException("psr-4 namespaces must end with a namespace separator, '$namespace' does not, use '$namespace\\'.");
}
}
}
}
public function parseAutoloads(array $packageMap, PackageInterface $mainPackage)
{
$mainPackageMap = array_shift($packageMap);
$sortedPackageMap = $this->sortPackageMap($packageMap);
$sortedPackageMap[] = $mainPackageMap;
array_unshift($packageMap, $mainPackageMap);
$psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $mainPackage);
$psr4 = $this->parseAutoloadsType($packageMap, 'psr-4', $mainPackage);
$classmap = $this->parseAutoloadsType($sortedPackageMap, 'classmap', $mainPackage);
$files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage);
krsort($psr0);
krsort($psr4);
return array('psr-0' => $psr0, 'psr-4' => $psr4, 'classmap' => $classmap, 'files' => $files);
}
public function createLoader(array $autoloads)
{
$loader = new ClassLoader();
if (isset($autoloads['psr-0'])) {
foreach ($autoloads['psr-0'] as $namespace => $path) {
$loader->add($namespace, $path);
}
}
if (isset($autoloads['psr-4'])) {
foreach ($autoloads['psr-4'] as $namespace => $path) {
$loader->addPsr4($namespace, $path);
}
}
return $loader;
}
protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
{
$includePaths = array();
foreach ($packageMap as $item) {
list($package, $installPath) = $item;
if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) {
$installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
}
foreach ($package->getIncludePaths() as $includePath) {
$includePath = trim($includePath, '/');
$includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath;
}
}
if (!$includePaths) {
return;
}
$includePathsCode = '';
foreach ($includePaths as $path) {
$includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n";
}
return <<<EOF
<?php
// include_paths.php @generated by Composer
\$vendorDir = $vendorPathCode;
\$baseDir = $appBaseDirCode;
return array(
$includePathsCode);
EOF;
}
protected function getIncludeFilesFile(array $files, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
{
$filesCode = '';
foreach ($files as $functionFile) {
$filesCode .= ' '.$this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile).",\n";
}
if (!$filesCode) {
return false;
}
return <<<EOF
<?php
// autoload_files.php @generated by Composer
\$vendorDir = $vendorPathCode;
\$baseDir = $appBaseDirCode;
return array(
$filesCode);
EOF;
}
protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $path)
{
if (!$filesystem->isAbsolutePath($path)) {
$path = $basePath . '/' . $path;
}
$path = $filesystem->normalizePath($path);
$baseDir = '';
if (strpos($path.'/', $vendorPath.'/') === 0) {
$path = substr($path, strlen($vendorPath));
$baseDir = '$vendorDir';
if ($path !== false) {
$baseDir .= " . ";
}
} else {
$path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true));
if (!$filesystem->isAbsolutePath($path)) {
$baseDir = '$baseDir . ';
$path = '/' . $path;
}
}
if (preg_match('/\.phar$/', $path)) {
$baseDir = "'phar://' . " . $baseDir;
}
return $baseDir . (($path !== false) ? var_export($path, true) : "");
}
protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix)
{
return <<<AUTOLOAD
<?php
// autoload.php @generated by Composer
require_once $vendorPathToTargetDirCode . '/autoload_real.php';
return ComposerAutoloaderInit$suffix::getLoader();
AUTOLOAD;
}
protected function getAutoloadRealFile($useClassMap, $useIncludePath, $targetDirLoader, $useIncludeFiles, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $classMapAuthoritative)
{
$file = <<<HEADER
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit$suffix
{
private static \$loader;
public static function loadClassLoader(\$class)
{
if ('Composer\\Autoload\\ClassLoader' === \$class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::\$loader) {
return self::\$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'), true, $prependAutoloader);
self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
HEADER;
if ($useIncludePath) {
$file .= <<<'INCLUDE_PATH'
$includePaths = require __DIR__ . '/include_paths.php';
array_push($includePaths, get_include_path());
set_include_path(join(PATH_SEPARATOR, $includePaths));
INCLUDE_PATH;
}
$file .= <<<'PSR0'
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
PSR0;
$file .= <<<'PSR4'
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
PSR4;
if ($useClassMap) {
$file .= <<<'CLASSMAP'
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
CLASSMAP;
}
if ($classMapAuthoritative) {
$file .= <<<'CLASSMAPAUTHORITATIVE'
$loader->setClassMapAuthoritative(true);
CLASSMAPAUTHORITATIVE;
}
if ($useGlobalIncludePath) {
$file .= <<<'INCLUDEPATH'
$loader->setUseIncludePath(true);
INCLUDEPATH;
}
if ($targetDirLoader) {
$file .= <<<REGISTER_AUTOLOAD
spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true);
REGISTER_AUTOLOAD;
}
$file .= <<<REGISTER_LOADER
\$loader->register($prependAutoloader);
REGISTER_LOADER;
if ($useIncludeFiles) {
$file .= <<<INCLUDE_FILES
\$includeFiles = require __DIR__ . '/autoload_files.php';
foreach (\$includeFiles as \$file) {
composerRequire$suffix(\$file);
}
INCLUDE_FILES;
}
$file .= <<<METHOD_FOOTER
return \$loader;
}
METHOD_FOOTER;
$file .= $targetDirLoader;
return $file . <<<FOOTER
}
function composerRequire$suffix(\$file)
{
require \$file;
}
FOOTER;
}
protected function parseAutoloadsType(array $packageMap, $type, PackageInterface $mainPackage)
{
$autoloads = array();
foreach ($packageMap as $item) {
list($package, $installPath) = $item;
$autoload = $package->getAutoload();
if ($this->devMode && $package === $mainPackage) {
$autoload = array_merge_recursive($autoload, $package->getDevAutoload());
}
if (!isset($autoload[$type]) || !is_array($autoload[$type])) {
continue;
}
if (null !== $package->getTargetDir() && $package !== $mainPackage) {
$installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
}
foreach ($autoload[$type] as $namespace => $paths) {
foreach ((array) $paths as $path) {
if (($type === 'files' || $type === 'classmap') && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
if ($package === $mainPackage) {
$targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
$path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
} else {
$path = $package->getTargetDir() . '/' . $path;
}
}
$relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path;
if ($type === 'files' || $type === 'classmap') {
$autoloads[] = $relativePath;
continue;
}
$autoloads[$namespace][] = $relativePath;
}
}
}
return $autoloads;
}
protected function sortPackageMap(array $packageMap)
{
$packages = array();
$paths = array();
$usageList = array();
foreach ($packageMap as $item) {
list($package, $path) = $item;
$name = $package->getName();
$packages[$name] = $package;
$paths[$name] = $path;
foreach (array_merge($package->getRequires(), $package->getDevRequires()) as $link) {
$target = $link->getTarget();
$usageList[$target][] = $name;
}
}
$computing = array();
$computed = array();
$computeImportance = function ($name) use (&$computeImportance, &$computing, &$computed, $usageList) {
if (isset($computed[$name])) {
return $computed[$name];
}
if (isset($computing[$name])) {
return 0;
}
$computing[$name] = true;
$weight = 0;
if (isset($usageList[$name])) {
foreach ($usageList[$name] as $user) {
$weight -= 1 - $computeImportance($user);
}
}
unset($computing[$name]);
$computed[$name] = $weight;
return $weight;
};
$weightList = array();
foreach ($packages as $name => $package) {
$weight = $computeImportance($name);
$weightList[$name] = $weight;
}
$stable_sort = function (&$array) {
static $transform, $restore;
$i = 0;
if (!$transform) {
$transform = function (&$v, $k) use (&$i) {
$v = array($v, ++$i, $k, $v);
};
$restore = function (&$v, $k) {
$v = $v[3];
};
}
array_walk($array, $transform);
asort($array);
array_walk($array, $restore);
};
$stable_sort($weightList);
$sortedPackageMap = array();
foreach (array_keys($weightList) as $name) {
$sortedPackageMap[] = array($packages[$name], $paths[$name]);
}
return $sortedPackageMap;
}
}
<?php
namespace Composer\Autoload;
use Symfony\Component\Finder\Finder;
use Composer\IO\IOInterface;
class ClassMapGenerator
{
public static function dump($dirs, $file)
{
$maps = array();
foreach ($dirs as $dir) {
$maps = array_merge($maps, static::createMap($dir));
}
file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true)));
}
public static function createMap($path, $whitelist = null, IOInterface $io = null, $namespace = null)
{
if (is_string($path)) {
if (is_file($path)) {
$path = array(new \SplFileInfo($path));
} elseif (is_dir($path)) {
$path = Finder::create()->files()->followLinks()->name('/\.(php|inc|hh)$/')->in($path);
} else {
throw new \RuntimeException(
'Could not scan for classes inside "'.$path.
'" which does not appear to be a file nor a folder'
);
}
}
$map = array();
foreach ($path as $file) {
$filePath = $file->getRealPath();
if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) {
continue;
}
if ($whitelist && !preg_match($whitelist, strtr($filePath, '\\', '/'))) {
continue;
}
$classes = self::findClasses($filePath);
foreach ($classes as $class) {
if (null !== $namespace && 0 !== strpos($class, $namespace)) {
continue;
}
if (!isset($map[$class])) {
$map[$class] = $filePath;
} elseif ($io && $map[$class] !== $filePath && !preg_match('{/(test|fixture|example)s?/}i', strtr($map[$class].' '.$filePath, '\\', '/'))) {
$io->writeError(
'<warning>Warning: Ambiguous class resolution, "'.$class.'"'.
' was found in both "'.$map[$class].'" and "'.$filePath.'", the first will be used.</warning>'
);
}
}
}
return $map;
}
private static function findClasses($path)
{
$extraTypes = version_compare(PHP_VERSION, '5.4', '<') ? '' : '|trait';
if (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>=')) {
$extraTypes .= '|enum';
}
try {
$contents = @php_strip_whitespace($path);
if (!$contents) {
if (!file_exists($path)) {
throw new \Exception('File does not exist');
}
if (!is_readable($path)) {
throw new \Exception('File is not readable');
}
}
} catch (\Exception $e) {
throw new \RuntimeException('Could not scan for classes inside '.$path.": \n".$e->getMessage(), 0, $e);
}
if (!preg_match('{\b(?:class|interface'.$extraTypes.')\s}i', $contents)) {
return array();
}
$contents = preg_replace('{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents);
$contents = preg_replace('{"[^"\\\\]*(\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(\\\\.[^\'\\\\]*)*\'}s', 'null', $contents);
if (substr($contents, 0, 2) !== '<?') {
$contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
if ($replacements === 0) {
return array();
}
}
$contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
$pos = strrpos($contents, '?>');
if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
$contents = substr($contents, 0, $pos);
}
preg_match_all('{
(?:
\b(?<![\$:>])(?P<type>class|interface'.$extraTypes.') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*)
| \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;]
)
}ix', $contents, $matches);
$classes = array();
$namespace = '';
for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
if (!empty($matches['ns'][$i])) {
$namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
} else {
$name = $matches['name'][$i];
if ($name[0] === ':') {
$name = 'xhp'.substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
} elseif ($matches['type'][$i] === 'enum') {
$name = rtrim($name, ':');
}
$classes[] = ltrim($namespace . $name, '\\');
}
}
return $classes;
}
}
<?php
namespace Composer;
use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
use Symfony\Component\Finder\Finder;
class Cache
{
private static $cacheCollected = false;
private $io;
private $root;
private $enabled = true;
private $whitelist;
private $filesystem;
public function __construct(IOInterface $io, $cacheDir, $whitelist = 'a-z0-9.', Filesystem $filesystem = null)
{
$this->io = $io;
$this->root = rtrim($cacheDir, '/\\') . '/';
$this->whitelist = $whitelist;
$this->filesystem = $filesystem ?: new Filesystem();
if (!is_dir($this->root)) {
if (!@mkdir($this->root, 0777, true)) {
$this->enabled = false;
}
}
}
public function isEnabled()
{
return $this->enabled;
}
public function getRoot()
{
return $this->root;
}
public function read($file)
{
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->enabled && file_exists($this->root . $file)) {
if ($this->io->isDebug()) {
$this->io->writeError('Reading '.$this->root . $file.' from cache');
}
return file_get_contents($this->root . $file);
}
return false;
}
public function write($file, $contents)
{
if ($this->enabled) {
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->io->isDebug()) {
$this->io->writeError('Writing '.$this->root . $file.' into cache');
}
try {
return file_put_contents($this->root . $file, $contents);
} catch (\ErrorException $e) {
if (preg_match('{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}', $e->getMessage(), $m)) {
unlink($this->root . $file);
$message = sprintf(
'<warning>Writing %1$s into cache failed after %2$u of %3$u bytes written, only %4$u bytes of free space available</warning>',
$this->root . $file,
$m[1],
$m[2],
@disk_free_space($this->root . dirname($file))
);
$this->io->writeError($message);
return false;
}
throw $e;
}
}
return false;
}
public function copyFrom($file, $source)
{
if ($this->enabled) {
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
$this->filesystem->ensureDirectoryExists(dirname($this->root . $file));
if ($this->io->isDebug()) {
$this->io->writeError('Writing '.$this->root . $file.' into cache');
}
return copy($source, $this->root . $file);
}
return false;
}
public function copyTo($file, $target)
{
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->enabled && file_exists($this->root . $file)) {
touch($this->root . $file, filemtime($this->root . $file), time());
if ($this->io->isDebug()) {
$this->io->writeError('Reading '.$this->root . $file.' from cache');
}
return copy($this->root . $file, $target);
}
return false;
}
public function gcIsNecessary()
{
return (!self::$cacheCollected && !mt_rand(0, 50));
}
public function remove($file)
{
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->enabled && file_exists($this->root . $file)) {
return $this->filesystem->unlink($this->root . $file);
}
return false;
}
public function gc($ttl, $maxSize)
{
if ($this->enabled) {
$expire = new \DateTime();
$expire->modify('-'.$ttl.' seconds');
$finder = $this->getFinder()->date('until '.$expire->format('Y-m-d H:i:s'));
foreach ($finder as $file) {
$this->filesystem->unlink($file->getPathname());
}
$totalSize = $this->filesystem->size($this->root);
if ($totalSize > $maxSize) {
$iterator = $this->getFinder()->sortByAccessedTime()->getIterator();
while ($totalSize > $maxSize && $iterator->valid()) {
$filepath = $iterator->current()->getPathname();
$totalSize -= $this->filesystem->size($filepath);
$this->filesystem->unlink($filepath);
$iterator->next();
}
}
self::$cacheCollected = true;
return true;
}
return false;
}
public function sha1($file)
{
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->enabled && file_exists($this->root . $file)) {
return sha1_file($this->root . $file);
}
return false;
}
public function sha256($file)
{
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->enabled && file_exists($this->root . $file)) {
return hash_file('sha256', $this->root . $file);
}
return false;
}
protected function getFinder()
{
return Finder::create()->in($this->root)->files();
}
}
<?php
namespace Composer\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class AboutCommand extends Command
{
protected function configure()
{
$this
->setName('about')
->setDescription('Short information about Composer')
->setHelp(<<<EOT
<info>php composer.phar about</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->getIO()->write(<<<EOT
<info>Composer - Package Management for PHP</info>
<comment>Composer is a dependency manager tracking local dependencies of your projects and libraries.
See http://getcomposer.org/ for more information.</comment>
EOT
);
}
}
<?php
namespace Composer\Command;
use Composer\Factory;
use Composer\IO\IOInterface;
use Composer\DependencyResolver\Pool;
use Composer\Repository\CompositeRepository;
use Composer\Script\ScriptEvents;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Composer\Package\Version\VersionParser;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ArchiveCommand extends Command
{
protected function configure()
{
$this
->setName('archive')
->setDescription('Create an archive of this composer package')
->setDefinition(array(
new InputArgument('package', InputArgument::OPTIONAL, 'The package to archive instead of the current project'),
new InputArgument('version', InputArgument::OPTIONAL, 'A version constraint to find the package to archive'),
new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the resulting archive: tar or zip', 'tar'),
new InputOption('dir', false, InputOption::VALUE_REQUIRED, 'Write the archive to this directory', '.'),
))
->setHelp(<<<EOT
The <info>archive</info> command creates an archive of the specified format
containing the files and directories of the Composer project or the specified
package in the specified version and writes it to the specified directory.
<info>php composer.phar archive [--format=zip] [--dir=/foo] [package [version]]</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer(false);
if ($composer) {
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'archive', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$composer->getEventDispatcher()->dispatchScript(ScriptEvents::PRE_ARCHIVE_CMD);
}
$returnCode = $this->archive(
$this->getIO(),
$input->getArgument('package'),
$input->getArgument('version'),
$input->getOption('format'),
$input->getOption('dir')
);
if (0 === $returnCode && $composer) {
$composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ARCHIVE_CMD);
}
return $returnCode;
}
protected function archive(IOInterface $io, $packageName = null, $version = null, $format = 'tar', $dest = '.')
{
$config = Factory::createConfig();
$factory = new Factory;
$downloadManager = $factory->createDownloadManager($io, $config);
$archiveManager = $factory->createArchiveManager($config, $downloadManager);
if ($packageName) {
$package = $this->selectPackage($io, $packageName, $version);
if (!$package) {
return 1;
}
} else {
$package = $this->getComposer()->getPackage();
}
$io->writeError('<info>Creating the archive.</info>');
$archiveManager->archive($package, $format, $dest);
return 0;
}
protected function selectPackage(IOInterface $io, $packageName, $version = null)
{
$io->writeError('<info>Searching for the specified package.</info>');
if ($composer = $this->getComposer(false)) {
$localRepo = $composer->getRepositoryManager()->getLocalRepository();
$repos = new CompositeRepository(array_merge(array($localRepo), $composer->getRepositoryManager()->getRepositories()));
} else {
$defaultRepos = Factory::createDefaultRepositories($this->getIO());
$io->writeError('No composer.json found in the current directory, searching packages from ' . implode(', ', array_keys($defaultRepos)));
$repos = new CompositeRepository($defaultRepos);
}
$pool = new Pool();
$pool->addRepository($repos);
$parser = new VersionParser();
$constraint = ($version) ? $parser->parseConstraints($version) : null;
$packages = $pool->whatProvides($packageName, $constraint, true);
if (count($packages) > 1) {
$package = reset($packages);
$io->writeError('<info>Found multiple matches, selected '.$package->getPrettyString().'.</info>');
$io->writeError('Alternatives were '.implode(', ', array_map(function ($p) { return $p->getPrettyString(); }, $packages)).'.');
$io->writeError('<comment>Please use a more specific constraint to pick a different package.</comment>');
} elseif ($packages) {
$package = reset($packages);
$io->writeError('<info>Found an exact match '.$package->getPrettyString().'.</info>');
} else {
$io->writeError('<error>Could not find a package matching '.$packageName.'.</error>');
return false;
}
return $package;
}
}
<?php
namespace Composer\Command;
use Composer\Cache;
use Composer\Factory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ClearCacheCommand extends Command
{
protected function configure()
{
$this
->setName('clear-cache')
->setAliases(array('clearcache'))
->setDescription('Clears composer\'s internal package cache.')
->setHelp(<<<EOT
The <info>clear-cache</info> deletes all cached packages from composer's
cache directory.
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$config = Factory::createConfig();
$io = $this->getIO();
$cachePaths = array(
'cache-dir' => $config->get('cache-dir'),
'cache-files-dir' => $config->get('cache-files-dir'),
'cache-repo-dir' => $config->get('cache-repo-dir'),
'cache-vcs-dir' => $config->get('cache-vcs-dir'),
);
foreach ($cachePaths as $key => $cachePath) {
$cachePath = realpath($cachePath);
if (!$cachePath) {
$io->writeError("<info>Cache directory does not exist ($key): $cachePath</info>");
continue;
}
$cache = new Cache($io, $cachePath);
if (!$cache->isEnabled()) {
$io->writeError("<info>Cache is not enabled ($key): $cachePath</info>");
continue;
}
$io->writeError("<info>Clearing cache ($key): $cachePath</info>");
$cache->gc(0, 0);
}
$io->writeError('<info>All caches cleared.</info>');
}
}
<?php
namespace Composer\Command;
use Composer\Composer;
use Composer\Console\Application;
use Composer\IO\IOInterface;
use Composer\IO\NullIO;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command as BaseCommand;
abstract class Command extends BaseCommand
{
private $composer;
private $io;
public function getComposer($required = true, $disablePlugins = false)
{
if (null === $this->composer) {
$application = $this->getApplication();
if ($application instanceof Application) {
$this->composer = $application->getComposer($required, $disablePlugins);
} elseif ($required) {
throw new \RuntimeException(
'Could not create a Composer\Composer instance, you must inject '.
'one if this command is not used with a Composer\Console\Application instance'
);
}
}
return $this->composer;
}
public function setComposer(Composer $composer)
{
$this->composer = $composer;
}
public function resetComposer()
{
$this->composer = null;
$this->getApplication()->resetComposer();
}
public function getIO()
{
if (null === $this->io) {
$application = $this->getApplication();
if ($application instanceof Application) {
$this->io = $application->getIO();
} else {
$this->io = new NullIO();
}
}
return $this->io;
}
public function setIO(IOInterface $io)
{
$this->io = $io;
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
if (true === $input->hasParameterOption(array('--no-ansi')) && $input->hasOption('no-progress')) {
$input->setOption('no-progress', true);
}
parent::initialize($input, $output);
}
}
<?php
namespace Composer\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Config;
use Composer\Config\JsonConfigSource;
use Composer\Factory;
use Composer\Json\JsonFile;
class ConfigCommand extends Command
{
protected $config;
protected $configFile;
protected $configSource;
protected $authConfigFile;
protected $authConfigSource;
protected function configure()
{
$this
->setName('config')
->setDescription('Set config options')
->setDefinition(array(
new InputOption('global', 'g', InputOption::VALUE_NONE, 'Apply command to the global config file'),
new InputOption('editor', 'e', InputOption::VALUE_NONE, 'Open editor'),
new InputOption('auth', 'a', InputOption::VALUE_NONE, 'Affect auth config file (only used for --editor)'),
new InputOption('unset', null, InputOption::VALUE_NONE, 'Unset the given setting-key'),
new InputOption('list', 'l', InputOption::VALUE_NONE, 'List configuration settings'),
new InputOption('file', 'f', InputOption::VALUE_REQUIRED, 'If you want to choose a different composer.json or config.json', 'composer.json'),
new InputOption('absolute', null, InputOption::VALUE_NONE, 'Returns absolute paths when fetching *-dir config values instead of relative'),
new InputArgument('setting-key', null, 'Setting key'),
new InputArgument('setting-value', InputArgument::IS_ARRAY, 'Setting value'),
))
->setHelp(<<<EOT
This command allows you to edit some basic composer settings in either the
local composer.json file or the global config.json file.
To set a config setting:
<comment>%command.full_name% bin-dir bin/</comment>
To read a config setting:
<comment>%command.full_name% bin-dir</comment>
Outputs: <info>bin</info>
To edit the global config.json file:
<comment>%command.full_name% --global</comment>
To add a repository:
<comment>%command.full_name% repositories.foo vcs http://bar.com</comment>
To remove a repository (repo is a short alias for repositories):
<comment>%command.full_name% --unset repo.foo</comment>
To disable packagist:
<comment>%command.full_name% repo.packagist false</comment>
You can alter repositories in the global config.json file by passing in the
<info>--global</info> option.
To edit the file in an external editor:
<comment>%command.full_name% --editor</comment>
To choose your editor you can set the "EDITOR" env variable.
To get a list of configuration values in the file:
<comment>%command.full_name% --list</comment>
You can always pass more than one option. As an example, if you want to edit the
global config.json file.
<comment>%command.full_name% --editor --global</comment>
EOT
)
;
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output);
if ($input->getOption('global') && 'composer.json' !== $input->getOption('file')) {
throw new \RuntimeException('--file and --global can not be combined');
}
$this->config = Factory::createConfig($this->getIO());
$configFile = $input->getOption('global')
? ($this->config->get('home') . '/config.json')
: $input->getOption('file');
$this->configFile = new JsonFile($configFile);
$this->configSource = new JsonConfigSource($this->configFile);
$authConfigFile = $input->getOption('global')
? ($this->config->get('home') . '/auth.json')
: dirname(realpath($input->getOption('file'))) . '/auth.json';
$this->authConfigFile = new JsonFile($authConfigFile);
$this->authConfigSource = new JsonConfigSource($this->authConfigFile, true);
if ($input->getOption('global') && !$this->configFile->exists()) {
touch($this->configFile->getPath());
$this->configFile->write(array('config' => new \ArrayObject));
@chmod($this->configFile->getPath(), 0600);
}
if ($input->getOption('global') && !$this->authConfigFile->exists()) {
touch($this->authConfigFile->getPath());
$this->authConfigFile->write(array('http-basic' => new \ArrayObject, 'github-oauth' => new \ArrayObject));
@chmod($this->authConfigFile->getPath(), 0600);
}
if (!$this->configFile->exists()) {
throw new \RuntimeException(sprintf('File "%s" cannot be found in the current directory', $configFile));
}
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($input->getOption('editor')) {
$editor = escapeshellcmd(getenv('EDITOR'));
if (!$editor) {
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$editor = 'notepad';
} else {
foreach (array('vim', 'vi', 'nano', 'pico', 'ed') as $candidate) {
if (exec('which '.$candidate)) {
$editor = $candidate;
break;
}
}
}
}
$file = $input->getOption('auth') ? $this->authConfigFile->getPath() : $this->configFile->getPath();
system($editor . ' ' . $file . (defined('PHP_WINDOWS_VERSION_BUILD') ? '' : ' > `tty`'));
return 0;
}
if (!$input->getOption('global')) {
$this->config->merge($this->configFile->read());
$this->config->merge(array('config' => $this->authConfigFile->exists() ? $this->authConfigFile->read() : array()));
}
if ($input->getOption('list')) {
$this->listConfiguration($this->config->all(), $this->config->raw(), $output);
return 0;
}
$settingKey = $input->getArgument('setting-key');
if (!$settingKey) {
return 0;
}
if (array() !== $input->getArgument('setting-value') && $input->getOption('unset')) {
throw new \RuntimeException('You can not combine a setting value with --unset');
}
if (array() === $input->getArgument('setting-value') && !$input->getOption('unset')) {
$data = $this->config->all();
if (preg_match('/^repos?(?:itories)?(?:\.(.+))?/', $settingKey, $matches)) {
if (empty($matches[1])) {
$value = isset($data['repositories']) ? $data['repositories'] : array();
} else {
if (!isset($data['repositories'][$matches[1]])) {
throw new \InvalidArgumentException('There is no '.$matches[1].' repository defined');
}
$value = $data['repositories'][$matches[1]];
}
} elseif (strpos($settingKey, '.')) {
$bits = explode('.', $settingKey);
$data = $data['config'];
foreach ($bits as $bit) {
if (isset($data[$bit])) {
$data = $data[$bit];
} elseif (isset($data[implode('.', $bits)])) {
$data = $data[implode('.', $bits)];
break;
} else {
throw new \RuntimeException($settingKey.' is not defined');
}
array_shift($bits);
}
$value = $data;
} elseif (isset($data['config'][$settingKey])) {
$value = $this->config->get($settingKey, $input->getOption('absolute') ? 0 : Config::RELATIVE_PATHS);
} else {
throw new \RuntimeException($settingKey.' is not defined');
}
if (is_array($value)) {
$value = json_encode($value);
}
$this->getIO()->write($value);
return 0;
}
$values = $input->getArgument('setting-value');
$booleanValidator = function ($val) { return in_array($val, array('true', 'false', '1', '0'), true); };
$booleanNormalizer = function ($val) { return $val !== 'false' && (bool) $val; };
$uniqueConfigValues = array(
'process-timeout' => array('is_numeric', 'intval'),
'use-include-path' => array($booleanValidator, $booleanNormalizer),
'preferred-install' => array(
function ($val) { return in_array($val, array('auto', 'source', 'dist'), true); },
function ($val) { return $val; }
),
'store-auths' => array(
function ($val) { return in_array($val, array('true', 'false', 'prompt'), true); },
function ($val) {
if ('prompt' === $val) {
return 'prompt';
}
return $val !== 'false' && (bool) $val;
}
),
'notify-on-install' => array($booleanValidator, $booleanNormalizer),
'vendor-dir' => array('is_string', function ($val) { return $val; }),
'bin-dir' => array('is_string', function ($val) { return $val; }),
'cache-dir' => array('is_string', function ($val) { return $val; }),
'cache-files-dir' => array('is_string', function ($val) { return $val; }),
'cache-repo-dir' => array('is_string', function ($val) { return $val; }),
'cache-vcs-dir' => array('is_string', function ($val) { return $val; }),
'cache-ttl' => array('is_numeric', 'intval'),
'cache-files-ttl' => array('is_numeric', 'intval'),
'cache-files-maxsize' => array(
function ($val) { return preg_match('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val) > 0; },
function ($val) { return $val; }
),
'discard-changes' => array(
function ($val) { return in_array($val, array('stash', 'true', 'false', '1', '0'), true); },
function ($val) {
if ('stash' === $val) {
return 'stash';
}
return $val !== 'false' && (bool) $val;
}
),
'autoloader-suffix' => array('is_string', function ($val) { return $val === 'null' ? null : $val; }),
'optimize-autoloader' => array($booleanValidator, $booleanNormalizer),
'classmap-authoritative' => array($booleanValidator, $booleanNormalizer),
'prepend-autoloader' => array($booleanValidator, $booleanNormalizer),
'github-expose-hostname' => array($booleanValidator, $booleanNormalizer),
);
$multiConfigValues = array(
'github-protocols' => array(
function ($vals) {
if (!is_array($vals)) {
return 'array expected';
}
foreach ($vals as $val) {
if (!in_array($val, array('git', 'https', 'ssh'))) {
return 'valid protocols include: git, https, ssh';
}
}
return true;
},
function ($vals) {
return $vals;
}
),
'github-domains' => array(
function ($vals) {
if (!is_array($vals)) {
return 'array expected';
}
return true;
},
function ($vals) {
return $vals;
}
),
);
foreach ($uniqueConfigValues as $name => $callbacks) {
if ($settingKey === $name) {
if ($input->getOption('unset')) {
return $this->configSource->removeConfigSetting($settingKey);
}
list($validator, $normalizer) = $callbacks;
if (1 !== count($values)) {
throw new \RuntimeException('You can only pass one value. Example: php composer.phar config process-timeout 300');
}
if (true !== $validation = $validator($values[0])) {
throw new \RuntimeException(sprintf(
'"%s" is an invalid value'.($validation ? ' ('.$validation.')' : ''),
$values[0]
));
}
return $this->configSource->addConfigSetting($settingKey, $normalizer($values[0]));
}
}
foreach ($multiConfigValues as $name => $callbacks) {
if ($settingKey === $name) {
if ($input->getOption('unset')) {
return $this->configSource->removeConfigSetting($settingKey);
}
list($validator, $normalizer) = $callbacks;
if (true !== $validation = $validator($values)) {
throw new \RuntimeException(sprintf(
'%s is an invalid value'.($validation ? ' ('.$validation.')' : ''),
json_encode($values)
));
}
return $this->configSource->addConfigSetting($settingKey, $normalizer($values));
}
}
if (preg_match('/^repos?(?:itories)?\.(.+)/', $settingKey, $matches)) {
if ($input->getOption('unset')) {
return $this->configSource->removeRepository($matches[1]);
}
if (2 === count($values)) {
return $this->configSource->addRepository($matches[1], array(
'type' => $values[0],
'url' => $values[1],
));
}
if (1 === count($values)) {
$bool = strtolower($values[0]);
if (true === $booleanValidator($bool) && false === $booleanNormalizer($bool)) {
return $this->configSource->addRepository($matches[1], false);
}
}
throw new \RuntimeException('You must pass the type and a url. Example: php composer.phar config repositories.foo vcs http://bar.com');
}
if (preg_match('/^platform\.(.+)/', $settingKey, $matches)) {
if ($input->getOption('unset')) {
return $this->configSource->removeConfigSetting($settingKey);
}
return $this->configSource->addConfigSetting($settingKey, $values[0]);
}
if (preg_match('/^(github-oauth|http-basic)\.(.+)/', $settingKey, $matches)) {
if ($input->getOption('unset')) {
$this->authConfigSource->removeConfigSetting($matches[1].'.'.$matches[2]);
$this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]);
return;
}
if ($matches[1] === 'github-oauth') {
if (1 !== count($values)) {
throw new \RuntimeException('Too many arguments, expected only one token');
}
$this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]);
$this->authConfigSource->addConfigSetting($matches[1].'.'.$matches[2], $values[0]);
} elseif ($matches[1] === 'http-basic') {
if (2 !== count($values)) {
throw new \RuntimeException('Expected two arguments (username, password), got '.count($values));
}
$this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]);
$this->authConfigSource->addConfigSetting($matches[1].'.'.$matches[2], array('username' => $values[0], 'password' => $values[1]));
}
return;
}
throw new \InvalidArgumentException('Setting '.$settingKey.' does not exist or is not supported by this command');
}
protected function listConfiguration(array $contents, array $rawContents, OutputInterface $output, $k = null)
{
$origK = $k;
foreach ($contents as $key => $value) {
if ($k === null && !in_array($key, array('config', 'repositories'))) {
continue;
}
$rawVal = isset($rawContents[$key]) ? $rawContents[$key] : null;
if (is_array($value) && (!is_numeric(key($value)) || ($key === 'repositories' && null === $k))) {
$k .= preg_replace('{^config\.}', '', $key . '.');
$this->listConfiguration($value, $rawVal, $output, $k);
if (substr_count($k, '.') > 1) {
$k = str_split($k, strrpos($k, '.', -2));
$k = $k[0] . '.';
} else {
$k = $origK;
}
continue;
}
if (is_array($value)) {
$value = array_map(function ($val) {
return is_array($val) ? json_encode($val) : $val;
}, $value);
$value = '['.implode(', ', $value).']';
}
if (is_bool($value)) {
$value = var_export($value, true);
}
if (is_string($rawVal) && $rawVal != $value) {
$this->getIO()->write('[<comment>' . $k . $key . '</comment>] <info>' . $rawVal . ' (' . $value . ')</info>');
} else {
$this->getIO()->write('[<comment>' . $k . $key . '</comment>] <info>' . $value . '</info>');
}
}
}
}
<?php
namespace Composer\Command;
use Composer\Config;
use Composer\Factory;
use Composer\Installer;
use Composer\Installer\ProjectInstaller;
use Composer\Installer\InstallationManager;
use Composer\IO\IOInterface;
use Composer\Package\BasePackage;
use Composer\DependencyResolver\Pool;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\Package\Version\VersionSelector;
use Composer\Repository\ComposerRepository;
use Composer\Repository\CompositeRepository;
use Composer\Repository\FilesystemRepository;
use Composer\Repository\InstalledFilesystemRepository;
use Composer\Script\ScriptEvents;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
use Composer\Json\JsonFile;
use Composer\Config\JsonConfigSource;
use Composer\Util\Filesystem;
use Composer\Util\RemoteFilesystem;
use Composer\Package\Version\VersionParser;
class CreateProjectCommand extends Command
{
protected function configure()
{
$this
->setName('create-project')
->setDescription('Create new project from a package into given directory.')
->setDefinition(array(
new InputArgument('package', InputArgument::OPTIONAL, 'Package name to be installed'),
new InputArgument('directory', InputArgument::OPTIONAL, 'Directory where the files should be created'),
new InputArgument('version', InputArgument::OPTIONAL, 'Version, will default to latest'),
new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum-stability allowed (unless a version is specified).'),
new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
new InputOption('repository-url', null, InputOption::VALUE_REQUIRED, 'Pick a different repository url to look for the package.'),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'),
new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'),
new InputOption('no-plugins', null, InputOption::VALUE_NONE, 'Whether to disable plugins.'),
new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'),
new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Whether to prevent execution of all defined scripts in the root package.'),
new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
new InputOption('keep-vcs', null, InputOption::VALUE_NONE, 'Whether to prevent deletion vcs folder.'),
new InputOption('no-install', null, InputOption::VALUE_NONE, 'Whether to skip installation of the package dependencies.'),
new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
))
->setHelp(<<<EOT
The <info>create-project</info> command creates a new project from a given
package into a new directory. If executed without params and in a directory
with a composer.json file it installs the packages for the current project.
You can use this command to bootstrap new projects or setup a clean
version-controlled installation for developers of your project.
<info>php composer.phar create-project vendor/project target-directory [version]</info>
You can also specify the version with the package name using = or : as separator.
To install unstable packages, either specify the version you want, or use the
--stability=dev (where dev can be one of RC, beta, alpha or dev).
To setup a developer workable version you should create the project using the source
controlled code by appending the <info>'--prefer-source'</info> flag.
To install a package from another repository than the default one you
can pass the <info>'--repository-url=http://myrepository.org'</info> flag.
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$config = Factory::createConfig();
$preferSource = false;
$preferDist = false;
$this->updatePreferredOptions($config, $input, $preferSource, $preferDist);
if ($input->getOption('no-custom-installers')) {
$this->getIO()->writeError('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>');
$input->setOption('no-plugins', true);
}
return $this->installProject(
$this->getIO(),
$config,
$input->getArgument('package'),
$input->getArgument('directory'),
$input->getArgument('version'),
$input->getOption('stability'),
$preferSource,
$preferDist,
!$input->getOption('no-dev'),
$input->getOption('repository-url'),
$input->getOption('no-plugins'),
$input->getOption('no-scripts'),
$input->getOption('keep-vcs'),
$input->getOption('no-progress'),
$input->getOption('no-install'),
$input->getOption('ignore-platform-reqs'),
$input
);
}
public function installProject(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false, $noInstall = false, $ignorePlatformReqs = false, InputInterface $input)
{
$oldCwd = getcwd();
$io->loadConfiguration($config);
if ($packageName !== null) {
$installedFromVcs = $this->installRootPackage($io, $config, $packageName, $directory, $packageVersion, $stability, $preferSource, $preferDist, $installDevPackages, $repositoryUrl, $disablePlugins, $noScripts, $keepVcs, $noProgress);
} else {
$installedFromVcs = false;
}
$composer = Factory::create($io, null, $disablePlugins);
$composer->getDownloadManager()->setOutputProgress(!$noProgress);
$fs = new Filesystem();
if ($noScripts === false) {
$composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ROOT_PACKAGE_INSTALL, $installDevPackages);
}
$rootPackageConfig = $composer->getConfig();
$this->updatePreferredOptions($rootPackageConfig, $input, $preferSource, $preferDist);
if ($noInstall === false) {
$installer = Installer::create($io, $composer);
$installer->setPreferSource($preferSource)
->setPreferDist($preferDist)
->setDevMode($installDevPackages)
->setRunScripts(!$noScripts)
->setIgnorePlatformRequirements($ignorePlatformReqs);
if ($disablePlugins) {
$installer->disablePlugins();
}
$status = $installer->run();
if (0 !== $status) {
return $status;
}
}
$hasVcs = $installedFromVcs;
if (!$keepVcs && $installedFromVcs
&& (
!$io->isInteractive()
|| $io->askConfirmation('<info>Do you want to remove the existing VCS (.git, .svn..) history?</info> [<comment>Y,n</comment>]? ', true)
)
) {
$finder = new Finder();
$finder->depth(0)->directories()->in(getcwd())->ignoreVCS(false)->ignoreDotFiles(false);
foreach (array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg') as $vcsName) {
$finder->name($vcsName);
}
try {
$dirs = iterator_to_array($finder);
unset($finder);
foreach ($dirs as $dir) {
if (!$fs->removeDirectory($dir)) {
throw new \RuntimeException('Could not remove '.$dir);
}
}
} catch (\Exception $e) {
$io->writeError('<error>An error occurred while removing the VCS metadata: '.$e->getMessage().'</error>');
}
$hasVcs = false;
}
if (!$hasVcs) {
$package = $composer->getPackage();
$configSource = new JsonConfigSource(new JsonFile('composer.json'));
foreach (BasePackage::$supportedLinkTypes as $type => $meta) {
foreach ($package->{'get'.$meta['method']}() as $link) {
if ($link->getPrettyConstraint() === 'self.version') {
$configSource->addLink($type, $link->getTarget(), $package->getPrettyVersion());
}
}
}
}
if ($noScripts === false) {
$composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_CREATE_PROJECT_CMD, $installDevPackages);
}
chdir($oldCwd);
$vendorComposerDir = $composer->getConfig()->get('vendor-dir').'/composer';
if (is_dir($vendorComposerDir) && $fs->isDirEmpty($vendorComposerDir)) {
@rmdir($vendorComposerDir);
$vendorDir = $composer->getConfig()->get('vendor-dir');
if (is_dir($vendorDir) && $fs->isDirEmpty($vendorDir)) {
@rmdir($vendorDir);
}
}
return 0;
}
protected function installRootPackage(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false)
{
if (null === $repositoryUrl) {
$sourceRepo = new CompositeRepository(Factory::createDefaultRepositories($io, $config));
} elseif ("json" === pathinfo($repositoryUrl, PATHINFO_EXTENSION) && file_exists($repositoryUrl)) {
$json = new JsonFile($repositoryUrl, new RemoteFilesystem($io, $config));
$data = $json->read();
if (!empty($data['packages']) || !empty($data['includes']) || !empty($data['provider-includes'])) {
$sourceRepo = new ComposerRepository(array('url' => 'file://' . strtr(realpath($repositoryUrl), '\\', '/')), $io, $config);
} else {
$sourceRepo = new FilesystemRepository($json);
}
} elseif (0 === strpos($repositoryUrl, 'http')) {
$sourceRepo = new ComposerRepository(array('url' => $repositoryUrl), $io, $config);
} else {
throw new \InvalidArgumentException("Invalid repository url given. Has to be a .json file or an http url.");
}
$parser = new VersionParser();
$requirements = $parser->parseNameVersionPairs(array($packageName));
$name = strtolower($requirements[0]['name']);
if (!$packageVersion && isset($requirements[0]['version'])) {
$packageVersion = $requirements[0]['version'];
}
if (null === $stability) {
if (preg_match('{^[^,\s]*?@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $packageVersion, $match)) {
$stability = $match[1];
} else {
$stability = VersionParser::parseStability($packageVersion);
}
}
$stability = VersionParser::normalizeStability($stability);
if (!isset(BasePackage::$stabilities[$stability])) {
throw new \InvalidArgumentException('Invalid stability provided ('.$stability.'), must be one of: '.implode(', ', array_keys(BasePackage::$stabilities)));
}
$pool = new Pool($stability);
$pool->addRepository($sourceRepo);
$versionSelector = new VersionSelector($pool);
$package = $versionSelector->findBestCandidate($name, $packageVersion);
if (!$package) {
throw new \InvalidArgumentException("Could not find package $name" . ($packageVersion ? " with version $packageVersion." : " with stability $stability."));
}
if (null === $directory) {
$parts = explode("/", $name, 2);
$directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts);
}
$io->writeError('<info>Installing ' . $package->getName() . ' (' . VersionParser::formatVersion($package, false) . ')</info>');
if ($disablePlugins) {
$io->writeError('<info>Plugins have been disabled.</info>');
}
if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) {
$package->setSourceReference(substr($package->getPrettyVersion(), 4));
}
$dm = $this->createDownloadManager($io, $config);
$dm->setPreferSource($preferSource)
->setPreferDist($preferDist)
->setOutputProgress(!$noProgress);
$projectInstaller = new ProjectInstaller($directory, $dm);
$im = $this->createInstallationManager();
$im->addInstaller($projectInstaller);
$im->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), new InstallOperation($package));
$im->notifyInstalls();
$installedFromVcs = 'source' === $package->getInstallationSource();
$io->writeError('<info>Created project in ' . $directory . '</info>');
chdir($directory);
$_SERVER['COMPOSER_ROOT_VERSION'] = $package->getPrettyVersion();
putenv('COMPOSER_ROOT_VERSION='.$_SERVER['COMPOSER_ROOT_VERSION']);
return $installedFromVcs;
}
protected function createDownloadManager(IOInterface $io, Config $config)
{
$factory = new Factory();
return $factory->createDownloadManager($io, $config);
}
protected function createInstallationManager()
{
return new InstallationManager();
}
protected function updatePreferredOptions(Config $config, InputInterface $input, &$preferSource, &$preferDist)
{
switch ($config->get('preferred-install')) {
case 'source':
$preferSource = true;
$preferDist = false;
break;
case 'dist':
$preferSource = false;
$preferDist = true;
break;
case 'auto':
default:
break;
}
if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) {
$preferSource = $input->getOption('prefer-source');
$preferDist = $input->getOption('prefer-dist');
}
}
}
<?php
namespace Composer\Command;
use Composer\DependencyResolver\Pool;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class DependsCommand extends Command
{
protected $linkTypes = array(
'require' => array('requires', 'requires'),
'require-dev' => array('devRequires', 'requires (dev)'),
);
protected function configure()
{
$this
->setName('depends')
->setDescription('Shows which packages depend on the given package')
->setDefinition(array(
new InputArgument('package', InputArgument::REQUIRED, 'Package to inspect'),
new InputOption('link-type', '', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Link types to show (require, require-dev)', array_keys($this->linkTypes)),
))
->setHelp(<<<EOT
Displays detailed information about where a package is referenced.
<info>php composer.phar depends composer/composer</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'depends', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$repo = $composer->getRepositoryManager()->getLocalRepository();
$needle = $input->getArgument('package');
$pool = new Pool();
$pool->addRepository($repo);
$packages = $pool->whatProvides($needle);
if (empty($packages)) {
throw new \InvalidArgumentException('Could not find package "'.$needle.'" in your project.');
}
$linkTypes = $this->linkTypes;
$types = array_map(function ($type) use ($linkTypes) {
$type = rtrim($type, 's');
if (!isset($linkTypes[$type])) {
throw new \InvalidArgumentException('Unexpected link type: '.$type.', valid types: '.implode(', ', array_keys($linkTypes)));
}
return $type;
}, $input->getOption('link-type'));
$messages = array();
$outputPackages = array();
foreach ($repo->getPackages() as $package) {
foreach ($types as $type) {
foreach ($package->{'get'.$linkTypes[$type][0]}() as $link) {
if ($link->getTarget() === $needle) {
if (!isset($outputPackages[$package->getName()])) {
$messages[] = '<info>'.$package->getPrettyName() . '</info> ' . $linkTypes[$type][1] . ' ' . $needle .' (<info>' . $link->getPrettyConstraint() . '</info>)';
$outputPackages[$package->getName()] = true;
}
}
}
}
}
if ($messages) {
sort($messages);
$this->getIO()->write($messages);
} else {
$this->getIO()->writeError('<info>There is no installed package depending on "'.$needle.'".</info>');
}
}
}
<?php
namespace Composer\Command;
use Composer\Composer;
use Composer\Factory;
use Composer\Downloader\TransportException;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Composer\Util\ConfigValidator;
use Composer\Util\ProcessExecutor;
use Composer\Util\RemoteFilesystem;
use Composer\Util\StreamContextFactory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DiagnoseCommand extends Command
{
protected $rfs;
protected $process;
protected $failures = 0;
protected function configure()
{
$this
->setName('diagnose')
->setDescription('Diagnoses the system to identify common errors.')
->setHelp(<<<EOT
The <info>diagnose</info> command checks common errors to help debugging problems.
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer(false);
if ($composer) {
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$this->getIO()->write('Checking composer.json: ', false);
$this->outputResult($this->checkComposerSchema());
}
if ($composer) {
$config = $composer->getConfig();
} else {
$config = Factory::createConfig();
}
$this->rfs = new RemoteFilesystem($this->getIO(), $config);
$this->process = new ProcessExecutor($this->getIO());
$this->getIO()->write('Checking platform settings: ', false);
$this->outputResult($this->checkPlatform());
$this->getIO()->write('Checking git settings: ', false);
$this->outputResult($this->checkGit());
$this->getIO()->write('Checking http connectivity: ', false);
$this->outputResult($this->checkHttp());
$opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org'));
if (!empty($opts['http']['proxy'])) {
$this->getIO()->write('Checking HTTP proxy: ', false);
$this->outputResult($this->checkHttpProxy());
$this->getIO()->write('Checking HTTP proxy support for request_fulluri: ', false);
$this->outputResult($this->checkHttpProxyFullUriRequestParam());
$this->getIO()->write('Checking HTTPS proxy support for request_fulluri: ', false);
$this->outputResult($this->checkHttpsProxyFullUriRequestParam());
}
if ($oauth = $config->get('github-oauth')) {
foreach ($oauth as $domain => $token) {
$this->getIO()->write('Checking '.$domain.' oauth access: ', false);
$this->outputResult($this->checkGithubOauth($domain, $token));
}
} else {
$this->getIO()->write('Checking github.com rate limit: ', false);
try {
$rate = $this->getGithubRateLimit('github.com');
$this->outputResult(true);
if (10 > $rate['remaining']) {
$this->getIO()->write('<warning>WARNING</warning>');
$this->getIO()->write(sprintf(
'<comment>Github has a rate limit on their API. '
. 'You currently have <options=bold>%u</options=bold> '
. 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL
. 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL
. ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>',
$rate['remaining'],
$rate['limit']
));
}
} catch (\Exception $e) {
if ($e instanceof TransportException && $e->getCode() === 401) {
$this->outputResult('<comment>The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it</comment>');
} else {
$this->outputResult($e);
}
}
}
$this->getIO()->write('Checking disk free space: ', false);
$this->outputResult($this->checkDiskSpace($config));
$this->getIO()->write('Checking composer version: ', false);
$this->outputResult($this->checkVersion());
return $this->failures;
}
private function checkComposerSchema()
{
$validator = new ConfigValidator($this->getIO());
list($errors, $publishErrors, $warnings) = $validator->validate(Factory::getComposerFile());
if ($errors || $publishErrors || $warnings) {
$messages = array(
'error' => array_merge($errors, $publishErrors),
'warning' => $warnings,
);
$output = '';
foreach ($messages as $style => $msgs) {
foreach ($msgs as $msg) {
$output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL;
}
}
return rtrim($output);
}
return true;
}
private function checkGit()
{
$this->process->execute('git config color.ui', $output);
if (strtolower(trim($output)) === 'always') {
return '<comment>Your git color.ui setting is set to always, this is known to create issues. Use "git config --global color.ui true" to set it correctly.</comment>';
}
return true;
}
private function checkHttp()
{
$protocol = extension_loaded('openssl') ? 'https' : 'http';
try {
$this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false);
} catch (\Exception $e) {
return $e;
}
return true;
}
private function checkHttpProxy()
{
$protocol = extension_loaded('openssl') ? 'https' : 'http';
try {
$json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false), true);
$hash = reset($json['provider-includes']);
$hash = $hash['sha256'];
$path = str_replace('%hash%', $hash, key($json['provider-includes']));
$provider = $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/'.$path, false);
if (hash('sha256', $provider) !== $hash) {
return 'It seems that your proxy is modifying http traffic on the fly';
}
} catch (\Exception $e) {
return $e;
}
return true;
}
private function checkHttpProxyFullUriRequestParam()
{
$url = 'http://packagist.org/packages.json';
try {
$this->rfs->getContents('packagist.org', $url, false);
} catch (TransportException $e) {
try {
$this->rfs->getContents('packagist.org', $url, false, array('http' => array('request_fulluri' => false)));
} catch (TransportException $e) {
return 'Unable to assess the situation, maybe packagist.org is down ('.$e->getMessage().')';
}
return 'It seems there is a problem with your proxy server, try setting the "HTTP_PROXY_REQUEST_FULLURI" and "HTTPS_PROXY_REQUEST_FULLURI" environment variables to "false"';
}
return true;
}
private function checkHttpsProxyFullUriRequestParam()
{
if (!extension_loaded('openssl')) {
return 'You need the openssl extension installed for this check';
}
$url = 'https://api.github.com/repos/Seldaek/jsonlint/zipball/1.0.0';
try {
$this->rfs->getContents('github.com', $url, false);
} catch (TransportException $e) {
try {
$this->rfs->getContents('github.com', $url, false, array('http' => array('request_fulluri' => false)));
} catch (TransportException $e) {
return 'Unable to assess the situation, maybe github is down ('.$e->getMessage().')';
}
return 'It seems there is a problem with your proxy server, try setting the "HTTPS_PROXY_REQUEST_FULLURI" environment variable to "false"';
}
return true;
}
private function checkGithubOauth($domain, $token)
{
$this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
try {
$url = $domain === 'github.com' ? 'https://api.'.$domain.'/user/repos' : 'https://'.$domain.'/api/v3/user/repos';
return $this->rfs->getContents($domain, $url, false, array(
'retry-auth-failure' => false
)) ? true : 'Unexpected error';
} catch (\Exception $e) {
if ($e instanceof TransportException && $e->getCode() === 401) {
return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>';
}
return $e;
}
}
private function getGithubRateLimit($domain, $token = null)
{
if ($token) {
$this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
}
$url = $domain === 'github.com' ? 'https://api.'.$domain.'/rate_limit' : 'https://'.$domain.'/api/rate_limit';
$json = $this->rfs->getContents($domain, $url, false, array('retry-auth-failure' => false));
$data = json_decode($json, true);
return $data['resources']['core'];
}
private function checkDiskSpace($config)
{
$minSpaceFree = 1024*1024;
if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
|| (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
) {
return '<error>The disk hosting '.$dir.' is full</error>';
}
return true;
}
private function checkVersion()
{
$protocol = extension_loaded('openssl') ? 'https' : 'http';
$latest = trim($this->rfs->getContents('getcomposer.org', $protocol . '://getcomposer.org/version', false));
if (Composer::VERSION !== $latest && Composer::VERSION !== '@package_version@') {
return '<comment>You are not running the latest version</comment>';
}
return true;
}
private function outputResult($result)
{
if (true === $result) {
$this->getIO()->write('<info>OK</info>');
} else {
$this->failures++;
$this->getIO()->write('<error>FAIL</error>');
if ($result instanceof \Exception) {
$this->getIO()->write('['.get_class($result).'] '.$result->getMessage());
} elseif ($result) {
$this->getIO()->write(trim($result));
}
}
}
private function checkPlatform()
{
$output = '';
$out = function ($msg, $style) use (&$output) {
$output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL;
};
$errors = array();
$warnings = array();
$iniPath = php_ini_loaded_file();
$displayIniMessage = false;
if ($iniPath) {
$iniMessage = PHP_EOL.PHP_EOL.'The php.ini used by your command-line PHP is: ' . $iniPath;
} else {
$iniMessage = PHP_EOL.PHP_EOL.'A php.ini file does not exist. You will have to create one.';
}
$iniMessage .= PHP_EOL.'If you can not modify the ini file, you can also run `php -d option=value` to modify ini values on the fly. You can use -d multiple times.';
if (!function_exists('json_decode')) {
$errors['json'] = true;
}
if (!extension_loaded('Phar')) {
$errors['phar'] = true;
}
if (!extension_loaded('filter')) {
$errors['filter'] = true;
}
if (!extension_loaded('hash')) {
$errors['hash'] = true;
}
if (!ini_get('allow_url_fopen')) {
$errors['allow_url_fopen'] = true;
}
if (extension_loaded('ionCube Loader') && ioncube_loader_iversion() < 40009) {
$errors['ioncube'] = ioncube_loader_version();
}
if (version_compare(PHP_VERSION, '5.3.2', '<')) {
$errors['php'] = PHP_VERSION;
}
if (!isset($errors['php']) && version_compare(PHP_VERSION, '5.3.4', '<')) {
$warnings['php'] = PHP_VERSION;
}
if (!extension_loaded('openssl')) {
$errors['openssl'] = true;
}
if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && ini_get('apc.enable_cli')) {
$warnings['apc_cli'] = true;
}
ob_start();
phpinfo(INFO_GENERAL);
$phpinfo = ob_get_clean();
if (preg_match('{Configure Command(?: *</td><td class="v">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) {
$configure = $match[1];
if (false !== strpos($configure, '--enable-sigchild')) {
$warnings['sigchild'] = true;
}
if (false !== strpos($configure, '--with-curlwrappers')) {
$warnings['curlwrappers'] = true;
}
}
if (ini_get('xdebug.profiler_enabled')) {
$warnings['xdebug_profile'] = true;
} elseif (extension_loaded('xdebug')) {
$warnings['xdebug_loaded'] = true;
}
if (!empty($errors)) {
foreach ($errors as $error => $current) {
switch ($error) {
case 'json':
$text = PHP_EOL."The json extension is missing.".PHP_EOL;
$text .= "Install it or recompile php without --disable-json";
break;
case 'phar':
$text = PHP_EOL."The phar extension is missing.".PHP_EOL;
$text .= "Install it or recompile php without --disable-phar";
break;
case 'filter':
$text = PHP_EOL."The filter extension is missing.".PHP_EOL;
$text .= "Install it or recompile php without --disable-filter";
break;
case 'hash':
$text = PHP_EOL."The hash extension is missing.".PHP_EOL;
$text .= "Install it or recompile php without --disable-hash";
break;
case 'unicode':
$text = PHP_EOL."The detect_unicode setting must be disabled.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
$text .= " detect_unicode = Off";
$displayIniMessage = true;
break;
case 'suhosin':
$text = PHP_EOL."The suhosin.executor.include.whitelist setting is incorrect.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini` or suhosin.ini (Example path [for Debian]: /etc/php5/cli/conf.d/suhosin.ini):".PHP_EOL;
$text .= " suhosin.executor.include.whitelist = phar ".$current;
$displayIniMessage = true;
break;
case 'php':
$text = PHP_EOL."Your PHP ({$current}) is too old, you must upgrade to PHP 5.3.2 or higher.";
break;
case 'allow_url_fopen':
$text = PHP_EOL."The allow_url_fopen setting is incorrect.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
$text .= " allow_url_fopen = On";
$displayIniMessage = true;
break;
case 'ioncube':
$text = PHP_EOL."Your ionCube Loader extension ($current) is incompatible with Phar files.".PHP_EOL;
$text .= "Upgrade to ionCube 4.0.9 or higher or remove this line (path may be different) from your `php.ini` to disable it:".PHP_EOL;
$text .= " zend_extension = /usr/lib/php5/20090626+lfs/ioncube_loader_lin_5.3.so";
$displayIniMessage = true;
break;
case 'openssl':
$text = PHP_EOL."The openssl extension is missing, which means that secure HTTPS transfers are impossible.".PHP_EOL;
$text .= "If possible you should enable it or recompile php with --with-openssl";
break;
}
$out($text, 'error');
}
$output .= PHP_EOL;
}
if (!empty($warnings)) {
foreach ($warnings as $warning => $current) {
switch ($warning) {
case 'apc_cli':
$text = "The apc.enable_cli setting is incorrect.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
$text .= " apc.enable_cli = Off";
$displayIniMessage = true;
break;
case 'sigchild':
$text = "PHP was compiled with --enable-sigchild which can cause issues on some platforms.".PHP_EOL;
$text .= "Recompile it without this flag if possible, see also:".PHP_EOL;
$text .= " https://bugs.php.net/bug.php?id=22999";
break;
case 'curlwrappers':
$text = "PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.".PHP_EOL;
$text .= " Recompile it without this flag if possible";
break;
case 'php':
$text = "Your PHP ({$current}) is quite old, upgrading to PHP 5.3.4 or higher is recommended.".PHP_EOL;
$text .= " Composer works with 5.3.2+ for most people, but there might be edge case issues.";
break;
case 'xdebug_loaded':
$text = "The xdebug extension is loaded, this can slow down Composer a little.".PHP_EOL;
$text .= " Disabling it when using Composer is recommended.";
break;
case 'xdebug_profile':
$text = "The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini` to disable it:".PHP_EOL;
$text .= " xdebug.profiler_enabled = 0";
$displayIniMessage = true;
break;
}
$out($text, 'comment');
}
}
if ($displayIniMessage) {
$out($iniMessage, 'comment');
}
return !$warnings && !$errors ? true : $output;
}
}
<?php
namespace Composer\Command;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class DumpAutoloadCommand extends Command
{
protected function configure()
{
$this
->setName('dump-autoload')
->setAliases(array('dumpautoload'))
->setDescription('Dumps the autoloader')
->setDefinition(array(
new InputOption('optimize', 'o', InputOption::VALUE_NONE, 'Optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production.'),
new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables autoload-dev rules.'),
))
->setHelp(<<<EOT
<info>php composer.phar dump-autoload</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'dump-autoload', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$installationManager = $composer->getInstallationManager();
$localRepo = $composer->getRepositoryManager()->getLocalRepository();
$package = $composer->getPackage();
$config = $composer->getConfig();
$optimize = $input->getOption('optimize') || $config->get('optimize-autoloader') || $config->get('classmap-authoritative');
if ($optimize) {
$this->getIO()->writeError('<info>Generating optimized autoload files</info>');
} else {
$this->getIO()->writeError('<info>Generating autoload files</info>');
}
$generator = $composer->getAutoloadGenerator();
$generator->setDevMode(!$input->getOption('no-dev'));
$generator->dump($config, $localRepo, $package, $installationManager, 'composer', $optimize);
}
}
<?php
namespace Composer\Command;
use Composer\Factory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\OutputInterface;
class GlobalCommand extends Command
{
protected function configure()
{
$this
->setName('global')
->setDescription('Allows running commands in the global composer dir ($COMPOSER_HOME).')
->setDefinition(array(
new InputArgument('command-name', InputArgument::REQUIRED, ''),
new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''),
))
->setHelp(<<<EOT
Use this command as a wrapper to run other Composer commands
within the global context of COMPOSER_HOME.
You can use this to install CLI utilities globally, all you need
is to add the COMPOSER_HOME/vendor/bin dir to your PATH env var.
COMPOSER_HOME is c:\Users\<user>\AppData\Roaming\Composer on Windows
and /home/<user>/.composer on unix systems.
Note: This path may vary depending on customizations to bin-dir in
composer.json or the environmental variable COMPOSER_BIN_DIR.
EOT
)
;
}
public function run(InputInterface $input, OutputInterface $output)
{
$tokens = preg_split('{\s+}', $input->__toString());
$args = array();
foreach ($tokens as $token) {
if ($token && $token[0] !== '-') {
$args[] = $token;
if (count($args) >= 2) {
break;
}
}
}
if (count($args) < 2) {
return parent::run($input, $output);
}
$config = Factory::createConfig();
chdir($config->get('home'));
$this->getIO()->writeError('<info>Changed current directory to '.$config->get('home').'</info>');
$input = new StringInput(preg_replace('{\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\b}', '', $input->__toString(), 1));
return $this->getApplication()->run($input, $output);
}
}
<?php
namespace Composer\Command;
use Composer\DependencyResolver\Pool;
use Composer\Factory;
use Composer\Package\CompletePackageInterface;
use Composer\Repository\CompositeRepository;
use Composer\Repository\RepositoryInterface;
use Composer\Util\ProcessExecutor;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class HomeCommand extends Command
{
protected function configure()
{
$this
->setName('browse')
->setAliases(array('home'))
->setDescription('Opens the package\'s repository URL or homepage in your browser.')
->setDefinition(array(
new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Package(s) to browse to.'),
new InputOption('homepage', 'H', InputOption::VALUE_NONE, 'Open the homepage instead of the repository URL.'),
new InputOption('show', 's', InputOption::VALUE_NONE, 'Only show the homepage or repository URL.'),
))
->setHelp(<<<EOT
The home command opens or shows a package's repository URL or
homepage in your default browser.
To open the homepage by default, use -H or --homepage.
To show instead of open the repository or homepage URL, use -s or --show.
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$repos = $this->initializeRepos();
$return = 0;
foreach ($input->getArgument('packages') as $packageName) {
foreach ($repos as $repo) {
$package = $this->getPackage($repo, $packageName);
if ($package instanceof CompletePackageInterface) {
break;
}
}
$package = $this->getPackage($repo, $packageName);
if (!$package instanceof CompletePackageInterface) {
$return = 1;
$this->getIO()->writeError('<warning>Package '.$packageName.' not found</warning>');
continue;
}
$support = $package->getSupport();
$url = isset($support['source']) ? $support['source'] : $package->getSourceUrl();
if (!$url || $input->getOption('homepage')) {
$url = $package->getHomepage();
}
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$return = 1;
$this->getIO()->writeError('<warning>'.($input->getOption('homepage') ? 'Invalid or missing homepage' : 'Invalid or missing repository URL').' for '.$packageName.'</warning>');
continue;
}
if ($input->getOption('show')) {
$this->getIO()->write(sprintf('<info>%s</info>', $url));
} else {
$this->openBrowser($url);
}
}
return $return;
}
protected function getPackage(RepositoryInterface $repos, $name)
{
$name = strtolower($name);
$pool = new Pool('dev');
$pool->addRepository($repos);
$matches = $pool->whatProvides($name);
foreach ($matches as $index => $package) {
if ($package->getName() !== $name) {
unset($matches[$index]);
continue;
}
return $package;
}
}
private function openBrowser($url)
{
$url = ProcessExecutor::escape($url);
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
return passthru('start "web" explorer "' . $url . '"');
}
passthru('which xdg-open', $linux);
passthru('which open', $osx);
if (0 === $linux) {
passthru('xdg-open ' . $url);
} elseif (0 === $osx) {
passthru('open ' . $url);
} else {
$this->getIO()->writeError('no suitable browser opening command found, open yourself: ' . $url);
}
}
private function initializeRepos()
{
$composer = $this->getComposer(false);
if ($composer) {
return array(
$composer->getRepositoryManager()->getLocalRepository(),
new CompositeRepository($composer->getRepositoryManager()->getRepositories())
);
}
$defaultRepos = Factory::createDefaultRepositories($this->getIO());
return array(new CompositeRepository($defaultRepos));
}
}
<?php
namespace Composer\Command;
use Composer\DependencyResolver\Pool;
use Composer\Json\JsonFile;
use Composer\Factory;
use Composer\Package\BasePackage;
use Composer\Package\Version\VersionSelector;
use Composer\Repository\CompositeRepository;
use Composer\Repository\PlatformRepository;
use Composer\Package\Version\VersionParser;
use Composer\Util\ProcessExecutor;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\ExecutableFinder;
class InitCommand extends Command
{
protected $repos;
private $gitConfig;
private $pool;
protected function configure()
{
$this
->setName('init')
->setDescription('Creates a basic composer.json file in current directory.')
->setDefinition(array(
new InputOption('name', null, InputOption::VALUE_REQUIRED, 'Name of the package'),
new InputOption('description', null, InputOption::VALUE_REQUIRED, 'Description of package'),
new InputOption('author', null, InputOption::VALUE_REQUIRED, 'Author name of package'),
new InputOption('type', null, InputOption::VALUE_OPTIONAL, 'Type of package'),
new InputOption('homepage', null, InputOption::VALUE_REQUIRED, 'Homepage of package'),
new InputOption('require', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
new InputOption('require-dev', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require for development with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum stability (empty or one of: '.implode(', ', array_keys(BasePackage::$stabilities)).')'),
new InputOption('license', 'l', InputOption::VALUE_REQUIRED, 'License of package'),
))
->setHelp(<<<EOT
The <info>init</info> command creates a basic composer.json file
in the current directory.
<info>php composer.phar init</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$whitelist = array('name', 'description', 'author', 'type', 'homepage', 'require', 'require-dev', 'stability', 'license');
$options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
if (isset($options['author'])) {
$options['authors'] = $this->formatAuthors($options['author']);
unset($options['author']);
}
if (isset($options['stability'])) {
$options['minimum-stability'] = $options['stability'];
unset($options['stability']);
}
$options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass;
if (array() === $options['require']) {
$options['require'] = new \stdClass;
}
if (isset($options['require-dev'])) {
$options['require-dev'] = $this->formatRequirements($options['require-dev']);
if (array() === $options['require-dev']) {
$options['require-dev'] = new \stdClass;
}
}
$file = new JsonFile('composer.json');
$json = $file->encode($options);
if ($input->isInteractive()) {
$this->getIO()->writeError(array('', $json, ''));
if (!$this->getIO()->askConfirmation('Do you confirm generation [<comment>yes</comment>]? ', true)) {
$this->getIO()->writeError('<error>Command aborted</error>');
return 1;
}
}
$file->write($options);
if ($input->isInteractive() && is_dir('.git')) {
$ignoreFile = realpath('.gitignore');
if (false === $ignoreFile) {
$ignoreFile = realpath('.') . '/.gitignore';
}
if (!$this->hasVendorIgnore($ignoreFile)) {
$question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]? ';
if ($this->getIO()->askConfirmation($question, true)) {
$this->addVendorIgnore($ignoreFile);
}
}
}
}
protected function interact(InputInterface $input, OutputInterface $output)
{
$git = $this->getGitConfig();
$formatter = $this->getHelperSet()->get('formatter');
$this->getIO()->writeError(array(
'',
$formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
''
));
$this->getIO()->writeError(array(
'',
'This command will guide you through creating your composer.json config.',
'',
));
$cwd = realpath(".");
if (!$name = $input->getOption('name')) {
$name = basename($cwd);
$name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
$name = strtolower($name);
if (isset($git['github.user'])) {
$name = $git['github.user'] . '/' . $name;
} elseif (!empty($_SERVER['USERNAME'])) {
$name = $_SERVER['USERNAME'] . '/' . $name;
} elseif (get_current_user()) {
$name = get_current_user() . '/' . $name;
} else {
$name = $name . '/' . $name;
}
} else {
if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $name)) {
throw new \InvalidArgumentException(
'The package name '.$name.' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+'
);
}
}
$name = $this->getIO()->askAndValidate(
'Package name (<vendor>/<name>) [<comment>'.$name.'</comment>]: ',
function ($value) use ($name) {
if (null === $value) {
return $name;
}
if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $value)) {
throw new \InvalidArgumentException(
'The package name '.$value.' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+'
);
}
return $value;
},
null,
$name
);
$input->setOption('name', $name);
$description = $input->getOption('description') ?: false;
$description = $this->getIO()->ask(
'Description [<comment>'.$description.'</comment>]: ',
$description
);
$input->setOption('description', $description);
if (null === $author = $input->getOption('author')) {
if (isset($git['user.name']) && isset($git['user.email'])) {
$author = sprintf('%s <%s>', $git['user.name'], $git['user.email']);
}
}
$self = $this;
$author = $this->getIO()->askAndValidate(
'Author [<comment>'.$author.'</comment>]: ',
function ($value) use ($self, $author) {
$value = $value ?: $author;
$author = $self->parseAuthorString($value);
return sprintf('%s <%s>', $author['name'], $author['email']);
},
null,
$author
);
$input->setOption('author', $author);
$minimumStability = $input->getOption('stability') ?: null;
$minimumStability = $this->getIO()->askAndValidate(
'Minimum Stability [<comment>'.$minimumStability.'</comment>]: ',
function ($value) use ($self, $minimumStability) {
if (null === $value) {
return $minimumStability;
}
if (!isset(BasePackage::$stabilities[$value])) {
throw new \InvalidArgumentException(
'Invalid minimum stability "'.$value.'". Must be empty or one of: '.
implode(', ', array_keys(BasePackage::$stabilities))
);
}
return $value;
},
null,
$minimumStability
);
$input->setOption('stability', $minimumStability);
$type = $input->getOption('type') ?: false;
$type = $this->getIO()->ask(
'Package Type [<comment>'.$type.'</comment>]: ',
$type
);
$input->setOption('type', $type);
$license = $input->getOption('license') ?: false;
$license = $this->getIO()->ask(
'License [<comment>'.$license.'</comment>]: ',
$license
);
$input->setOption('license', $license);
$this->getIO()->writeError(array('', 'Define your dependencies.', ''));
$question = 'Would you like to define your dependencies (require) interactively [<comment>yes</comment>]? ';
$requirements = array();
if ($this->getIO()->askConfirmation($question, true)) {
$requirements = $this->determineRequirements($input, $output, $input->getOption('require'));
}
$input->setOption('require', $requirements);
$question = 'Would you like to define your dev dependencies (require-dev) interactively [<comment>yes</comment>]? ';
$devRequirements = array();
if ($this->getIO()->askConfirmation($question, true)) {
$devRequirements = $this->determineRequirements($input, $output, $input->getOption('require-dev'));
}
$input->setOption('require-dev', $devRequirements);
}
public function parseAuthorString($author)
{
if (preg_match('/^(?P<name>[- \.,\p{L}\p{N}\'’]+) <(?P<email>.+?)>$/u', $author, $match)) {
if ($this->isValidEmail($match['email'])) {
return array(
'name' => trim($match['name']),
'email' => $match['email']
);
}
}
throw new \InvalidArgumentException(
'Invalid author string. Must be in the format: '.
'John Smith <john@example.com>'
);
}
protected function findPackages($name)
{
return $this->getRepos()->search($name);
}
protected function getRepos()
{
if (!$this->repos) {
$this->repos = new CompositeRepository(array_merge(
array(new PlatformRepository),
Factory::createDefaultRepositories($this->getIO())
));
}
return $this->repos;
}
protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array())
{
if ($requires) {
$requires = $this->normalizeRequirements($requires);
$result = array();
foreach ($requires as $requirement) {
if (!isset($requirement['version'])) {
$version = $this->findBestVersionForPackage($input, $requirement['name']);
$requirement['version'] = $version;
$this->getIO()->writeError(sprintf(
'Using version <info>%s</info> for <info>%s</info>',
$requirement['version'],
$requirement['name']
));
}
$result[] = $requirement['name'] . ' ' . $requirement['version'];
}
return $result;
}
$versionParser = new VersionParser();
while (null !== $package = $this->getIO()->ask('Search for a package: ')) {
$matches = $this->findPackages($package);
if (count($matches)) {
$exactMatch = null;
$choices = array();
foreach ($matches as $position => $foundPackage) {
$choices[] = sprintf(' <info>%5s</info> %s', "[$position]", $foundPackage['name']);
if ($foundPackage['name'] === $package) {
$exactMatch = true;
break;
}
}
if (!$exactMatch) {
$this->getIO()->writeError(array(
'',
sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
''
));
$this->getIO()->writeError($choices);
$this->getIO()->writeError('');
$validator = function ($selection) use ($matches, $versionParser) {
if ('' === $selection) {
return false;
}
if (is_numeric($selection) && isset($matches[(int) $selection])) {
$package = $matches[(int) $selection];
return $package['name'];
}
if (preg_match('{^\s*(?P<name>[\S/]+)(?:\s+(?P<version>\S+))?\s*$}', $selection, $packageMatches)) {
if (isset($packageMatches['version'])) {
$versionParser->parseConstraints($packageMatches['version']);
return $packageMatches['name'].' '.$packageMatches['version'];
}
return $packageMatches['name'];
}
throw new \Exception('Not a valid selection');
};
$package = $this->getIO()->askAndValidate(
'Enter package # to add, or the complete package name if it is not listed: ',
$validator,
3,
false
);
}
if (false !== $package && false === strpos($package, ' ')) {
$validator = function ($input) {
$input = trim($input);
return $input ?: false;
};
$constraint = $this->getIO()->askAndValidate(
'Enter the version constraint to require (or leave blank to use the latest version): ',
$validator,
3,
false
);
if (false === $constraint) {
$constraint = $this->findBestVersionForPackage($input, $package);
$this->getIO()->writeError(sprintf(
'Using version <info>%s</info> for <info>%s</info>',
$constraint,
$package
));
}
$package .= ' '.$constraint;
}
if (false !== $package) {
$requires[] = $package;
}
}
}
return $requires;
}
protected function formatAuthors($author)
{
return array($this->parseAuthorString($author));
}
protected function formatRequirements(array $requirements)
{
$requires = array();
$requirements = $this->normalizeRequirements($requirements);
foreach ($requirements as $requirement) {
$requires[$requirement['name']] = $requirement['version'];
}
return $requires;
}
protected function getGitConfig()
{
if (null !== $this->gitConfig) {
return $this->gitConfig;
}
$finder = new ExecutableFinder();
$gitBin = $finder->find('git');
$cmd = new Process(sprintf('%s config -l', ProcessExecutor::escape($gitBin)));
$cmd->run();
if ($cmd->isSuccessful()) {
$this->gitConfig = array();
preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$this->gitConfig[$match[1]] = $match[2];
}
return $this->gitConfig;
}
return $this->gitConfig = array();
}
protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
{
if (!file_exists($ignoreFile)) {
return false;
}
$pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
$lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
if (preg_match($pattern, $line)) {
return true;
}
}
return false;
}
protected function normalizeRequirements(array $requirements)
{
$parser = new VersionParser();
return $parser->parseNameVersionPairs($requirements);
}
protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
{
$contents = "";
if (file_exists($ignoreFile)) {
$contents = file_get_contents($ignoreFile);
if ("\n" !== substr($contents, 0, -1)) {
$contents .= "\n";
}