idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
51,600
protected function get ( array $ dataset ) { foreach ( $ dataset as $ key => $ firstItem ) { $ remaining = $ dataset ; \ array_splice ( $ remaining , $ key , 1 ) ; if ( 0 === \ count ( $ remaining ) ) { yield [ $ firstItem ] ; continue ; } foreach ( $ this -> get ( $ remaining ) as $ permutation ) { \ array_unshift ( $ permutation , $ firstItem ) ; yield $ permutation ; } } }
The permutations generator .
51,601
private function getFactors ( $ number ) { $ factors = [ ] ; for ( $ i = 2 ; $ number / $ i >= $ i ; ++ $ i ) { while ( 0 === $ number % $ i ) { $ factors [ ] = $ i ; $ number /= $ i ; } } if ( 1 < $ number ) { $ factors [ ] = $ number ; } return $ factors ; }
Compute the prime factors of the number .
51,602
public function next ( $ offset = 1 ) { $ offset = ( null === $ offset ) ? 1 : $ offset % $ this -> count ( ) ; $ this -> rotation = \ array_merge ( \ array_slice ( $ this -> rotation , $ offset ) , \ array_slice ( $ this -> rotation , 0 , $ offset ) ) ; }
Compute the next value of the Iterator .
51,603
public function order ( $ generator ) { $ result = [ ] ; foreach ( \ range ( 1 , $ this -> getSize ( ) ) as $ number ) { $ value = ( $ generator ** $ number ) % $ this -> getSize ( ) ; $ result [ $ value ] = $ value ; } return \ count ( $ result ) ; }
Get the order .
51,604
private function computeGroup ( ) { $ this -> group = [ ] ; foreach ( \ range ( 1 , $ this -> getSize ( ) ) as $ number ) { if ( 1 === $ this -> gcd ( $ number , $ this -> getSize ( ) ) ) { $ this -> group [ ] = $ number ; } } }
Clean out the group from unwanted values .
51,605
private function gcd ( $ a , $ b ) { return $ b ? $ this -> gcd ( $ b , $ a % $ b ) : $ a ; }
Get the greater common divisor between two numbers .
51,606
public function up ( ) { $ tableOptions = null ; if ( $ this -> db -> driverName === 'mysql' ) { $ tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB' ; } $ this -> createTable ( '{{%notifications}}' , [ 'id' => $ this -> primaryKey ( ) , 'class' => $ this -> string ( 64 ) -> notNull ( ) , 'key' => $ this -> string ( 32 ) -> notNull ( ) , 'message' => $ this -> string ( 255 ) -> notNull ( ) , 'route' => $ this -> string ( 255 ) -> notNull ( ) , 'seen' => $ this -> boolean ( ) -> notNull ( ) -> defaultValue ( false ) , 'read' => $ this -> boolean ( ) -> notNull ( ) -> defaultValue ( false ) , 'user_id' => $ this -> integer ( 11 ) -> unsigned ( ) -> notNull ( ) -> defaultValue ( 0 ) , 'created_at' => $ this -> integer ( 11 ) -> unsigned ( ) -> notNull ( ) -> defaultValue ( 0 ) , ] , $ tableOptions ) ; $ this -> createIndex ( 'index_2' , '{{%notifications}}' , [ 'user_id' ] ) ; $ this -> createIndex ( 'index_3' , '{{%notifications}}' , [ 'created_at' ] ) ; $ this -> createIndex ( 'index_4' , '{{%notifications}}' , [ 'seen' ] ) ; }
Create table notifications
51,607
public function send ( $ notification , array $ channels = null ) { if ( $ channels === null ) { $ channels = array_keys ( $ this -> channels ) ; } foreach ( ( array ) $ channels as $ id ) { $ channel = $ this -> getChannel ( $ id ) ; if ( ! $ notification -> shouldSend ( $ channel ) ) { continue ; } $ handle = 'to' . ucfirst ( $ id ) ; try { if ( $ notification -> hasMethod ( $ handle ) ) { call_user_func ( [ clone $ notification , $ handle ] , $ channel ) ; } else { $ channel -> send ( clone $ notification ) ; } } catch ( \ Exception $ e ) { Yii :: warning ( "Notification sended by channel '$id' has failed: " . $ e -> getMessage ( ) , __METHOD__ ) ; } } }
Send a notification to all channels
51,608
public function getChannel ( $ id ) { if ( ! isset ( $ this -> channels [ $ id ] ) ) { throw new InvalidParamException ( "Unknown channel '{$id}'." ) ; } if ( ! is_object ( $ this -> channels [ $ id ] ) ) { $ this -> channels [ $ id ] = $ this -> createChannel ( $ id , $ this -> channels [ $ id ] ) ; } return $ this -> channels [ $ id ] ; }
Gets the channel instance
51,609
public function actionIndex ( ) { $ userId = Yii :: $ app -> getUser ( ) -> getId ( ) ; $ query = ( new Query ( ) ) -> from ( '{{%notifications}}' ) -> andWhere ( [ 'or' , 'user_id = 0' , 'user_id = :user_id' ] , [ ':user_id' => $ userId ] ) ; $ pagination = new Pagination ( [ 'pageSize' => 20 , 'totalCount' => $ query -> count ( ) , ] ) ; $ list = $ query -> orderBy ( [ 'id' => SORT_DESC ] ) -> offset ( $ pagination -> offset ) -> limit ( $ pagination -> limit ) -> all ( ) ; $ notifs = $ this -> prepareNotifications ( $ list ) ; return $ this -> render ( 'index' , [ 'notifications' => $ notifs , 'pagination' => $ pagination , ] ) ; }
Displays index page .
51,610
public function send ( Notification $ notification ) { $ message = $ this -> composeMessage ( $ notification ) ; $ message -> send ( $ this -> mailer ) ; }
Sends a notification in this channel .
51,611
protected static function time2String ( $ timeline , $ intervals ) { $ output = '' ; foreach ( $ intervals as $ name => $ seconds ) { $ num = floor ( $ timeline / $ seconds ) ; $ timeline -= ( $ num * $ seconds ) ; if ( $ num > 0 ) { $ output .= $ num . ' ' . $ name . ( ( $ num > 1 ) ? 's' : '' ) . ' ' ; } } return trim ( $ output ) ; }
Get elapsed time converted to string
51,612
private function isItemCreatedHere ( $ rawItem ) { return is_array ( $ rawItem ) && array_key_exists ( 'value' , $ rawItem ) && array_key_exists ( 'tags' , $ rawItem ) && count ( $ rawItem ) === 2 ; }
Verify that the raw data is a cache item created by this class .
51,613
private function preRemoveItem ( $ key ) { $ item = $ this -> getItem ( $ key ) ; $ this -> removeTagEntries ( $ item ) ; return $ this ; }
Removes the key form all tag lists .
51,614
protected function getTaxTypes ( ) { $ taxTypes = $ this -> taxTypeRepository -> getAll ( ) ; $ taxTypes = array_filter ( $ taxTypes , function ( $ taxType ) { $ tag = $ taxType -> getTag ( ) ; return empty ( $ tag ) ; } ) ; return $ taxTypes ; }
Returns the non - tagged tax types .
51,615
protected function createTaxTypeFromDefinition ( array $ definition ) { $ definition [ 'zone' ] = $ this -> zoneRepository -> get ( $ definition [ 'zone' ] ) ; if ( ! isset ( $ definition [ 'compound' ] ) ) { $ definition [ 'compound' ] = false ; } if ( ! isset ( $ definition [ 'display_inclusive' ] ) ) { $ definition [ 'display_inclusive' ] = false ; } if ( ! isset ( $ definition [ 'rounding_mode' ] ) ) { $ definition [ 'rounding_mode' ] = PHP_ROUND_HALF_UP ; } $ type = new TaxType ( ) ; $ setValues = \ Closure :: bind ( function ( $ definition ) { $ this -> id = $ definition [ 'id' ] ; $ this -> name = $ definition [ 'name' ] ; $ this -> compound = $ definition [ 'compound' ] ; $ this -> displayInclusive = $ definition [ 'display_inclusive' ] ; $ this -> roundingMode = $ definition [ 'rounding_mode' ] ; $ this -> zone = $ definition [ 'zone' ] ; if ( isset ( $ definition [ 'generic_label' ] ) ) { $ this -> genericLabel = $ definition [ 'generic_label' ] ; } if ( isset ( $ definition [ 'tag' ] ) ) { $ this -> tag = $ definition [ 'tag' ] ; } } , $ type , '\CommerceGuys\Tax\Model\TaxType' ) ; $ setValues ( $ definition ) ; foreach ( $ definition [ 'rates' ] as $ rateDefinition ) { $ rate = $ this -> createTaxRateFromDefinition ( $ rateDefinition ) ; $ type -> addRate ( $ rate ) ; } return $ type ; }
Creates a tax type object from the provided definition .
51,616
protected function createTaxRateFromDefinition ( array $ definition ) { $ rate = new TaxRate ( ) ; $ setValues = \ Closure :: bind ( function ( $ definition ) { $ this -> id = $ definition [ 'id' ] ; $ this -> name = $ definition [ 'name' ] ; if ( isset ( $ definition [ 'default' ] ) ) { $ this -> default = $ definition [ 'default' ] ; } } , $ rate , '\CommerceGuys\Tax\Model\TaxRate' ) ; $ setValues ( $ definition ) ; foreach ( $ definition [ 'amounts' ] as $ amountDefinition ) { $ amount = $ this -> createTaxRateAmountFromDefinition ( $ amountDefinition ) ; $ rate -> addAmount ( $ amount ) ; } return $ rate ; }
Creates a tax rate object from the provided definition .
51,617
protected function createTaxRateAmountFromDefinition ( array $ definition ) { $ amount = new TaxRateAmount ( ) ; $ setValues = \ Closure :: bind ( function ( $ definition ) { $ this -> id = $ definition [ 'id' ] ; $ this -> amount = $ definition [ 'amount' ] ; if ( isset ( $ definition [ 'start_date' ] ) ) { $ this -> startDate = new \ DateTime ( $ definition [ 'start_date' ] ) ; } if ( isset ( $ definition [ 'end_date' ] ) ) { $ this -> endDate = new \ DateTime ( $ definition [ 'end_date' ] ) ; } } , $ amount , '\CommerceGuys\Tax\Model\TaxRateAmount' ) ; $ setValues ( $ definition ) ; return $ amount ; }
Creates a tax rate amount object from the provided definition .
51,618
protected function sortResolvers ( array $ resolvers ) { usort ( $ resolvers , function ( $ a , $ b ) { if ( $ a [ 'priority' ] == $ b [ 'priority' ] ) { return 0 ; } return ( $ a [ 'priority' ] > $ b [ 'priority' ] ) ? - 1 : 1 ; } ) ; $ sortedResolvers = [ ] ; foreach ( $ resolvers as $ resolver ) { $ sortedResolvers [ ] = $ resolver [ 'resolver' ] ; } return $ sortedResolvers ; }
Sorts the given resolvers .
51,619
protected function checkStoreRegistration ( ZoneInterface $ zone , Context $ context ) { $ storeRegistrations = $ context -> getStoreRegistrations ( ) ; foreach ( $ storeRegistrations as $ country ) { if ( ! isset ( $ this -> emptyAddresses [ $ country ] ) ) { $ this -> emptyAddresses [ $ country ] = new Address ( $ country ) ; } if ( $ zone -> match ( $ this -> emptyAddresses [ $ country ] ) ) { return true ; } } return false ; }
Checks whether the store is registered to collect taxes in the given zone .
51,620
protected function filterByStoreRegistration ( array $ taxTypes , Context $ context ) { $ taxTypes = array_filter ( $ taxTypes , function ( $ taxType ) use ( $ context ) { $ zone = $ taxType -> getZone ( ) ; return $ this -> checkStoreRegistration ( $ zone , $ context ) ; } ) ; return $ taxTypes ; }
Filters out tax types not matching the store registration .
51,621
protected function filterByAddress ( array $ taxTypes , AddressInterface $ address ) { $ taxTypes = array_filter ( $ taxTypes , function ( $ taxType ) use ( $ address ) { $ zone = $ taxType -> getZone ( ) ; return $ zone -> match ( $ address ) ; } ) ; return $ taxTypes ; }
Filters out tax types not matching the provided address .
51,622
protected function checkFacade ( File $ phpCsFile , int $ stackPointer ) : void { $ name = $ this -> findClassOrInterfaceName ( $ phpCsFile , $ stackPointer ) ; $ facadeInterfaceFile = str_replace ( 'Facade.php' , 'FacadeInterface.php' , $ phpCsFile -> getFilename ( ) ) ; if ( ! file_exists ( $ facadeInterfaceFile ) ) { $ phpCsFile -> addError ( 'FacadeInterface missing for ' . $ name , $ stackPointer , 'InterfaceMissing' ) ; } }
Facades must have a matching interface .
51,623
protected function assertNewLineAtTheBeginning ( File $ phpCsFile , int $ stackPointer ) : void { $ tokens = $ phpCsFile -> getTokens ( ) ; $ line = $ tokens [ $ stackPointer ] [ 'line' ] ; $ firstTokenInLineIndex = $ stackPointer ; while ( $ tokens [ $ firstTokenInLineIndex - 1 ] [ 'line' ] === $ line ) { $ firstTokenInLineIndex -- ; } $ prevContentIndex = $ phpCsFile -> findPrevious ( T_WHITESPACE , $ firstTokenInLineIndex - 1 , null , true ) ; if ( $ tokens [ $ prevContentIndex ] [ 'type' ] === 'T_DOC_COMMENT_CLOSE_TAG' ) { $ firstTokenInLineIndex = $ tokens [ $ prevContentIndex ] [ 'comment_opener' ] ; while ( $ tokens [ $ firstTokenInLineIndex - 1 ] [ 'line' ] === $ line ) { $ firstTokenInLineIndex -- ; } } $ prevContentIndex = $ phpCsFile -> findPrevious ( T_WHITESPACE , $ firstTokenInLineIndex - 1 , null , true ) ; if ( $ tokens [ $ prevContentIndex ] [ 'type' ] === 'T_OPEN_CURLY_BRACKET' ) { return ; } if ( $ tokens [ $ prevContentIndex ] [ 'line' ] < $ tokens [ $ firstTokenInLineIndex ] [ 'line' ] - 1 ) { return ; } $ fix = $ phpCsFile -> addFixableError ( 'Every function/method needs a newline before' , $ firstTokenInLineIndex , 'Concrete' ) ; if ( $ fix ) { $ phpCsFile -> fixer -> addNewline ( $ prevContentIndex ) ; } }
Asserts newline at the beginning including the doc block .
51,624
protected function detectReturnTypeVoid ( File $ phpcsFile , int $ index ) : ? string { $ tokens = $ phpcsFile -> getTokens ( ) ; $ type = 'void' ; $ methodStartIndex = $ tokens [ $ index ] [ 'scope_opener' ] ; $ methodEndIndex = $ tokens [ $ index ] [ 'scope_closer' ] ; for ( $ i = $ methodStartIndex + 1 ; $ i < $ methodEndIndex ; ++ $ i ) { if ( $ this -> isGivenKind ( [ T_FUNCTION ] , $ tokens [ $ i ] ) ) { $ endIndex = $ tokens [ $ i ] [ 'scope_closer' ] ; $ i = $ endIndex ; continue ; } if ( ! $ this -> isGivenKind ( [ T_RETURN ] , $ tokens [ $ i ] ) ) { continue ; } $ nextIndex = $ phpcsFile -> findNext ( Tokens :: $ emptyTokens , $ i + 1 , null , true ) ; if ( ! $ this -> isGivenKind ( T_SEMICOLON , $ tokens [ $ nextIndex ] ) ) { return null ; } } return $ type ; }
For right now we only try to detect void .
51,625
protected function addSpace ( File $ phpcsFile , int $ index ) : void { if ( $ phpcsFile -> fixer -> enabled !== true ) { return ; } $ phpcsFile -> fixer -> addContent ( $ index , ' ' ) ; }
Adds a single space on the right sight .
51,626
protected function getReturnTypes ( File $ phpCsFile , int $ stackPointer ) : array { $ tokens = $ phpCsFile -> getTokens ( ) ; if ( empty ( $ tokens [ $ stackPointer ] [ 'scope_opener' ] ) || empty ( $ tokens [ $ stackPointer ] [ 'scope_closer' ] ) ) { return [ ] ; } $ scopeOpener = $ tokens [ $ stackPointer ] [ 'scope_opener' ] ; $ scopeCloser = $ tokens [ $ stackPointer ] [ 'scope_closer' ] ; $ returnTypes = [ ] ; for ( $ i = $ scopeOpener ; $ i < $ scopeCloser ; $ i ++ ) { if ( $ tokens [ $ i ] [ 'code' ] !== T_RETURN ) { continue ; } if ( in_array ( T_CLOSURE , $ tokens [ $ i ] [ 'conditions' ] ) ) { continue ; } $ contentIndex = $ phpCsFile -> findNext ( Tokens :: $ emptyTokens , $ i + 1 , $ scopeCloser , true ) ; if ( ! $ contentIndex ) { continue ; } if ( $ tokens [ $ contentIndex ] [ 'code' ] === T_PARENT ) { $ parentMethodName = $ tokens [ $ contentIndex + 2 ] [ 'content' ] ; if ( $ parentMethodName === FunctionHelper :: getName ( $ phpCsFile , $ stackPointer ) ) { continue ; } } $ returnTypes [ ] = $ tokens [ $ contentIndex ] [ 'content' ] ; } return array_unique ( $ returnTypes ) ; }
We want to skip for static or other non chainable use cases .
51,627
protected function detectDirectoryDescendants ( ) { $ descendants = [ ] ; foreach ( new RecursiveIteratorIterator ( new RecursiveDirectoryIterator ( $ this -> getPath ( ) ) ) as $ file ) { if ( $ file -> isDir ( ) && ! in_array ( $ file -> getBasename ( ) , array ( '.' , '..' ) ) ) { $ resource = new DirectoryResource ( $ file , $ this -> files ) ; $ descendants [ $ resource -> getKey ( ) ] = $ resource ; } elseif ( $ file -> isFile ( ) ) { $ resource = new FileResource ( $ file , $ this -> files ) ; $ descendants [ $ resource -> getKey ( ) ] = $ resource ; } } return $ descendants ; }
Detect the descendant resources of the directory .
51,628
private function validateCreateRequest ( Request $ request ) { if ( $ request -> getContent ( ) === '' ) { throw new BadRequestHttpException ( 'Empty JSON data' , null , 1500559729 ) ; } if ( empty ( $ request -> get ( 'login_name' ) ) || empty ( $ request -> get ( 'password' ) ) ) { throw new BadRequestHttpException ( 'Incomplete credentials' , null , 1500562647 ) ; } }
Validates the request . If is it not valid throws an exception .
51,629
private function requireAuthentication ( Request $ request ) : Administrator { $ administrator = $ this -> authentication -> authenticateByApiKey ( $ request ) ; if ( $ administrator === null ) { throw new AccessDeniedHttpException ( 'No valid session key was provided as basic auth password.' , null , 1512749701 ) ; } return $ administrator ; }
Checks for valid authentication in the given request and throws an exception if there is none .
51,630
public function cgetAction ( Request $ request ) : View { $ this -> requireAuthentication ( $ request ) ; return View :: create ( ) -> setData ( $ this -> subscriberListRepository -> findAll ( ) ) ; }
Gets a list of all subscriber lists .
51,631
public function getAction ( Request $ request , SubscriberList $ list ) : View { $ this -> requireAuthentication ( $ request ) ; return View :: create ( ) -> setData ( $ list ) ; }
Gets a subscriber list .
51,632
public function deleteAction ( Request $ request , SubscriberList $ list ) : View { $ this -> requireAuthentication ( $ request ) ; $ this -> subscriberListRepository -> remove ( $ list ) ; return View :: create ( ) ; }
Deletes a subscriber list .
51,633
public static function open ( $ fileName ) { self :: checkRequirements ( ) ; if ( ! file_exists ( $ fileName ) || ! is_readable ( $ fileName ) ) throw new Exception ( 'Could not open file: ' . $ fileName ) ; $ type = self :: detectArchiveType ( $ fileName ) ; if ( ! self :: canOpenType ( $ type ) ) { return null ; } return new self ( $ fileName , $ type ) ; }
Creates instance with right type .
51,634
public static function canOpenArchive ( $ fileName ) { self :: checkRequirements ( ) ; $ type = self :: detectArchiveType ( $ fileName ) ; if ( $ type !== false && self :: canOpenType ( $ type ) ) { return true ; } return false ; }
Checks whether archive can be opened with current system configuration
51,635
public static function canOpenType ( $ type ) { self :: checkRequirements ( ) ; return ( isset ( self :: $ enabledTypes [ $ type ] ) ) ? self :: $ enabledTypes [ $ type ] : false ; }
Checks whether specific archive type can be opened with current system configuration
51,636
protected function scanArchive ( ) { $ information = $ this -> archive -> getArchiveInformation ( ) ; $ this -> files = $ information -> files ; $ this -> compressedFilesSize = $ information -> compressedFilesSize ; $ this -> uncompressedFilesSize = $ information -> uncompressedFilesSize ; $ this -> filesQuantity = count ( $ information -> files ) ; }
Rescans array after modification
51,637
public function getFileData ( $ fileName ) { if ( ! in_array ( $ fileName , $ this -> files , true ) ) return false ; return $ this -> archive -> getFileData ( $ fileName ) ; }
Returns file metadata
51,638
public function getFileContent ( $ fileName ) { if ( ! in_array ( $ fileName , $ this -> files , true ) ) return false ; return $ this -> archive -> getFileContent ( $ fileName ) ; }
Returns file content
51,639
public function getFileResource ( $ fileName ) { if ( ! in_array ( $ fileName , $ this -> files , true ) ) return false ; return $ this -> archive -> getFileResource ( $ fileName ) ; }
Returns a resource for reading file from archive
51,640
public function extractFiles ( $ outputFolder , $ files = null , $ expandFilesList = false ) { if ( $ files !== null ) { if ( is_string ( $ files ) ) $ files = [ $ files ] ; if ( $ expandFilesList ) $ files = self :: expandFileList ( $ this -> files , $ files ) ; return $ this -> archive -> extractFiles ( $ outputFolder , $ files ) ; } else { return $ this -> archive -> extractArchive ( $ outputFolder ) ; } }
Unpacks files to disk .
51,641
public function addFiles ( $ fileOrFiles ) { $ files_list = self :: createFilesList ( $ fileOrFiles ) ; if ( empty ( $ files_list ) ) throw new InvalidArgumentException ( 'Files list is empty!' ) ; $ result = $ this -> archive -> addFiles ( $ files_list ) ; $ this -> scanArchive ( ) ; return $ result ; }
Updates existing archive by adding new files
51,642
public function addFile ( $ file , $ inArchiveName = null ) { if ( ! is_file ( $ file ) ) throw new InvalidArgumentException ( $ file . ' is not a valid file to add in archive' ) ; return ( $ inArchiveName !== null ? $ this -> addFiles ( [ $ file => $ inArchiveName ] ) : $ this -> addFiles ( [ $ file ] ) ) === 1 ; }
Adds file into archive
51,643
public function addDirectory ( $ directory , $ inArchivePath = null ) { if ( ! is_dir ( $ directory ) || ! is_readable ( $ directory ) ) throw new InvalidArgumentException ( $ directory . ' is not a valid directory to add in archive' ) ; return ( $ inArchivePath !== null ? $ this -> addFiles ( [ $ directory => $ inArchivePath ] ) : $ this -> addFiles ( [ $ inArchivePath ] ) ) > 0 ; }
Adds directory contents to archive .
51,644
public static function archiveFiles ( $ fileOrFiles , $ archiveName , $ emulate = false ) { if ( file_exists ( $ archiveName ) ) throw new Exception ( 'Archive ' . $ archiveName . ' already exists!' ) ; self :: checkRequirements ( ) ; $ archiveType = self :: detectArchiveType ( $ archiveName , false ) ; if ( $ archiveType === false ) return false ; $ files_list = self :: createFilesList ( $ fileOrFiles ) ; if ( empty ( $ files_list ) ) throw new InvalidArgumentException ( 'Files list is empty!' ) ; if ( $ emulate ) { $ totalSize = 0 ; foreach ( $ files_list as $ fn ) $ totalSize += filesize ( $ fn ) ; return array ( 'totalSize' => $ totalSize , 'numberOfFiles' => count ( $ files_list ) , 'files' => $ files_list , 'type' => $ archiveType , ) ; } if ( ! isset ( static :: $ formatHandlers [ $ archiveType ] ) ) throw new Exception ( 'Unsupported archive type: ' . $ archiveType . ' of archive ' . $ archiveName ) ; $ handler_class = __NAMESPACE__ . '\\Formats\\' . static :: $ formatHandlers [ $ archiveType ] ; return $ handler_class :: createArchive ( $ files_list , $ archiveName ) ; }
Creates an archive with passed files list
51,645
public static function archiveFile ( $ file , $ archiveName ) { if ( ! is_file ( $ file ) ) throw new InvalidArgumentException ( $ file . ' is not a valid file to archive' ) ; return static :: archiveFiles ( $ file , $ archiveName ) === 1 ; }
Creates an archive with one file
51,646
public static function archiveDirectory ( $ directory , $ archiveName ) { if ( ! is_dir ( $ directory ) || ! is_readable ( $ directory ) ) throw new InvalidArgumentException ( $ directory . ' is not a valid directory to archive' ) ; return static :: archiveFiles ( $ directory , $ archiveName ) > 0 ; }
Creates an archive with full directory contents
51,647
protected static function checkRequirements ( ) { if ( empty ( self :: $ enabledTypes ) ) { self :: $ enabledTypes [ self :: ZIP ] = extension_loaded ( 'zip' ) ; self :: $ enabledTypes [ self :: SEVEN_ZIP ] = class_exists ( '\Archive7z\Archive7z' ) ; self :: $ enabledTypes [ self :: RAR ] = extension_loaded ( 'rar' ) ; self :: $ enabledTypes [ self :: GZIP ] = extension_loaded ( 'zlib' ) ; self :: $ enabledTypes [ self :: BZIP ] = extension_loaded ( 'bz2' ) ; self :: $ enabledTypes [ self :: LZMA ] = extension_loaded ( 'xz' ) ; self :: $ enabledTypes [ self :: ISO ] = class_exists ( '\CISOFile' ) ; self :: $ enabledTypes [ self :: CAB ] = class_exists ( '\CabArchive' ) ; self :: $ enabledTypes [ self :: TAR ] = class_exists ( '\Archive_Tar' ) || class_exists ( '\PharData' ) ; self :: $ enabledTypes [ self :: TAR_GZIP ] = ( class_exists ( '\Archive_Tar' ) || class_exists ( '\PharData' ) ) && extension_loaded ( 'zlib' ) ; self :: $ enabledTypes [ self :: TAR_BZIP ] = ( class_exists ( '\Archive_Tar' ) || class_exists ( '\PharData' ) ) && extension_loaded ( 'bz2' ) ; self :: $ enabledTypes [ self :: TAR_LZMA ] = class_exists ( '\Archive_Tar' ) && extension_loaded ( 'lzma2' ) ; self :: $ enabledTypes [ self :: TAR_LZMA ] = class_exists ( '\Archive_Tar' ) && LzwStreamWrapper :: isBinaryAvailable ( ) ; } }
Tests system configuration
51,648
protected static function expandFileList ( $ archiveFiles , $ files ) { $ newFiles = [ ] ; foreach ( $ files as $ file ) { foreach ( $ archiveFiles as $ archiveFile ) { if ( fnmatch ( $ file . '*' , $ archiveFile ) ) $ newFiles [ ] = $ archiveFile ; } } return $ newFiles ; }
Expands files list
51,649
protected static function checkRequirements ( ) { if ( self :: $ enabledPharData === null || self :: $ enabledPearTar === null ) { self :: $ enabledPearTar = class_exists ( '\Archive_Tar' ) ; self :: $ enabledPharData = class_exists ( '\PharData' ) ; } }
Checks system configuration for available Tar - manipulation libraries
51,650
protected static function createArchiveForPear ( array $ files , $ archiveFileName ) { $ compression = null ; switch ( strtolower ( pathinfo ( $ archiveFileName , PATHINFO_EXTENSION ) ) ) { case 'gz' : case 'tgz' : $ compression = 'gz' ; break ; case 'bz2' : case 'tbz2' : $ compression = 'bz2' ; break ; case 'xz' : $ compression = 'lzma2' ; break ; case 'z' : $ tar_aname = 'compress.lzw://' . $ archiveFileName ; break ; } if ( isset ( $ tar_aname ) ) $ tar = new Archive_Tar ( $ tar_aname , $ compression ) ; else $ tar = new Archive_Tar ( $ archiveFileName , $ compression ) ; foreach ( $ files as $ localName => $ filename ) { $ remove_dir = dirname ( $ filename ) ; $ add_dir = dirname ( $ localName ) ; if ( is_null ( $ filename ) ) { if ( $ tar -> addString ( $ localName , '' ) === false ) throw new Exception ( 'Error when adding directory ' . $ localName . ' to archive' ) ; } else { if ( $ tar -> addModify ( $ filename , $ add_dir , $ remove_dir ) === false ) throw new Exception ( 'Error when adding file ' . $ filename . ' to archive' ) ; } } $ tar = null ; return count ( $ files ) ; }
Creates an archive via Pear library
51,651
protected static function createArchiveForPhar ( array $ files , $ archiveFileName ) { if ( preg_match ( '~^(.+)\.(tar\.(gz|bz2))$~i' , $ archiveFileName , $ match ) ) { $ ext = $ match [ 2 ] ; $ basename = $ match [ 1 ] ; } else { $ ext = pathinfo ( $ archiveFileName , PATHINFO_EXTENSION ) ; $ basename = dirname ( $ archiveFileName ) . '/' . basename ( $ archiveFileName , '.' . $ ext ) ; } $ tar = new PharData ( $ basename . '.tar' , 0 , null , Phar :: TAR ) ; try { foreach ( $ files as $ localName => $ filename ) { if ( is_null ( $ filename ) ) { if ( ! in_array ( $ localName , [ '/' , '' ] , true ) ) { if ( $ tar -> addEmptyDir ( $ localName ) === false ) { return false ; } } } else { if ( $ tar -> addFile ( $ filename , $ localName ) === false ) { return false ; } } } } catch ( Exception $ e ) { return false ; } switch ( strtolower ( pathinfo ( $ archiveFileName , PATHINFO_EXTENSION ) ) ) { case 'gz' : case 'tgz' : $ tar -> compress ( Phar :: GZ , $ ext ) ; break ; case 'bz2' : case 'tbz2' : $ tar -> compress ( Phar :: BZ2 , $ ext ) ; break ; } $ tar = null ; return count ( $ files ) ; }
Creates an archive via Phar library
51,652
public function listContent ( ) { $ filesList = array ( ) ; $ numFiles = $ this -> archive -> numFiles ; for ( $ i = 0 ; $ i < $ numFiles ; $ i ++ ) { $ statIndex = $ this -> archive -> statIndex ( $ i ) ; $ filesList [ ] = ( object ) array ( 'filename' => $ statIndex [ 'name' ] , 'stored_filename' => $ statIndex [ 'name' ] , 'size' => $ statIndex [ 'size' ] , 'compressed_size' => $ statIndex [ 'comp_size' ] , 'mtime' => $ statIndex , 'comment' => ( $ comment = $ this -> archive -> getCommentIndex ( $ statIndex [ 'index' ] ) !== false ) ? $ comment : null , 'folder' => in_array ( substr ( $ statIndex [ 'name' ] , - 1 ) , array ( '/' , '\\' ) ) , 'index' => $ statIndex [ 'index' ] , 'status' => 'ok' , ) ; } return $ filesList ; }
Lists archive content
51,653
public function properties ( ) { return array ( 'nb' => $ this -> archive -> numFiles , 'comment' => ( ( $ comment = $ this -> archive -> getArchiveComment ( ) !== false ) ? $ comment : null ) , 'status' => 'OK' , ) ; }
Reads properties of archive
51,654
public function normalizeValue ( Parameter $ parameter , string $ value = null ) { if ( \ is_bool ( $ default = $ parameter -> default ( ) ) ) { return ! $ default ; } if ( $ parameter -> variadic ( ) ) { return ( array ) $ value ; } if ( null === $ value ) { return $ parameter -> required ( ) ? null : true ; } return $ parameter -> filter ( $ value ) ; }
Normalizes value as per context and runs thorugh filter if possible .
51,655
public function toWords ( string $ string ) : string { $ words = \ trim ( \ str_replace ( [ '-' , '_' ] , ' ' , $ string ) ) ; return \ ucwords ( $ words ) ; }
Convert a string to capitalized words .
51,656
public function parse ( array $ argv ) : self { $ this -> _normalizer = new Normalizer ; \ array_shift ( $ argv ) ; $ argv = $ this -> _normalizer -> normalizeArgs ( $ argv ) ; $ count = \ count ( $ argv ) ; $ literal = false ; for ( $ i = 0 ; $ i < $ count ; $ i ++ ) { list ( $ arg , $ nextArg ) = [ $ argv [ $ i ] , $ argv [ $ i + 1 ] ?? null ] ; if ( $ arg === '--' ) { $ literal = true ; } elseif ( $ arg [ 0 ] !== '-' || $ literal ) { $ this -> parseArgs ( $ arg ) ; } else { $ i += ( int ) $ this -> parseOptions ( $ arg , $ nextArg ) ; } } $ this -> validate ( ) ; return $ this ; }
Parse the argv input .
51,657
protected function parseArgs ( string $ arg ) { if ( $ this -> _lastVariadic ) { return $ this -> set ( $ this -> _lastVariadic , $ arg , true ) ; } if ( ! $ argument = \ reset ( $ this -> _arguments ) ) { return $ this -> set ( null , $ arg ) ; } $ this -> setValue ( $ argument , $ arg ) ; if ( ! $ argument -> variadic ( ) ) { \ array_shift ( $ this -> _arguments ) ; } }
Parse single arg .
51,658
protected function parseOptions ( string $ arg , string $ nextArg = null ) : bool { $ value = \ substr ( $ nextArg , 0 , 1 ) === '-' ? null : $ nextArg ; if ( null === $ option = $ this -> optionFor ( $ arg ) ) { return $ this -> handleUnknown ( $ arg , $ value ) ; } $ this -> _lastVariadic = $ option -> variadic ( ) ? $ option -> attributeName ( ) : null ; return false === $ this -> emit ( $ option -> attributeName ( ) , $ value ) ? false : $ this -> setValue ( $ option , $ value ) ; }
Parse an option emit its event and set value .
51,659
protected function setValue ( Parameter $ parameter , string $ value = null ) : bool { $ name = $ parameter -> attributeName ( ) ; $ value = $ this -> _normalizer -> normalizeValue ( $ parameter , $ value ) ; return $ this -> set ( $ name , $ value , $ parameter -> variadic ( ) ) ; }
Sets value of an option .
51,660
protected function set ( $ key , $ value , bool $ variadic = false ) : bool { if ( null === $ key ) { $ this -> _values [ ] = $ value ; } elseif ( $ variadic ) { $ this -> _values [ $ key ] = \ array_merge ( $ this -> _values [ $ key ] , ( array ) $ value ) ; } else { $ this -> _values [ $ key ] = $ value ; } return ! \ in_array ( $ value , [ true , false , null ] , true ) ; }
Set a raw value .
51,661
protected function ifAlreadyRegistered ( Parameter $ param ) { if ( $ this -> registered ( $ param -> attributeName ( ) ) ) { throw new InvalidParameterException ( \ sprintf ( 'The parameter "%s" is already registered' , $ param instanceof Option ? $ param -> long ( ) : $ param -> name ( ) ) ) ; } }
What if the given name is already registered .
51,662
public function values ( bool $ withDefaults = true ) : array { $ values = $ this -> _values ; $ values [ 'version' ] = $ this -> _version ?? null ; if ( ! $ withDefaults ) { unset ( $ values [ 'help' ] , $ values [ 'version' ] , $ values [ 'verbosity' ] ) ; } return $ values ; }
Get values indexed by camelized attribute name .
51,663
public function printTrace ( \ Throwable $ e ) { $ eClass = \ get_class ( $ e ) ; $ this -> writer -> colors ( "{$eClass} <red>{$e->getMessage()}</end><eol/>" . "(thrown in <yellow>{$e->getFile()}</end><white>:{$e->getLine()})</end>" ) ; if ( $ e instanceof Exception ) { return ; } $ traceStr = '<eol/><eol/><bold>Stack Trace:</end><eol/><eol/>' ; foreach ( $ e -> getTrace ( ) as $ i => $ trace ) { $ trace += [ 'class' => '' , 'type' => '' , 'function' => '' , 'file' => '' , 'line' => '' , 'args' => [ ] ] ; $ symbol = $ trace [ 'class' ] . $ trace [ 'type' ] . $ trace [ 'function' ] ; $ args = $ this -> stringifyArgs ( $ trace [ 'args' ] ) ; $ traceStr .= " <comment>$i)</end> <red>$symbol</end><comment>($args)</end>" ; if ( '' !== $ trace [ 'file' ] ) { $ file = \ realpath ( $ trace [ 'file' ] ) ; $ traceStr .= "<eol/> <yellow>at $file</end><white>:{$trace['line']}</end><eol/>" ; } } $ this -> writer -> colors ( $ traceStr ) ; }
Print stack trace and error msg of an exception .
51,664
protected function showHelp ( string $ for , array $ items , string $ header = '' , string $ footer = '' ) { if ( $ header ) { $ this -> writer -> bold ( $ header , true ) ; } $ this -> writer -> eol ( ) -> boldGreen ( $ for . ':' , true ) ; if ( empty ( $ items ) ) { $ this -> writer -> bold ( ' (n/a)' , true ) ; return ; } $ space = 4 ; foreach ( $ this -> sortItems ( $ items , $ padLen ) as $ item ) { $ name = $ this -> getName ( $ item ) ; $ desc = \ str_replace ( [ "\r\n" , "\n" ] , \ str_pad ( "\n" , $ padLen + $ space + 3 ) , $ item -> desc ( ) ) ; $ this -> writer -> bold ( ' ' . \ str_pad ( $ name , $ padLen + $ space ) ) ; $ this -> writer -> comment ( $ desc , true ) ; } if ( $ footer ) { $ this -> writer -> eol ( ) -> yellow ( $ footer , true ) ; } }
Show help with headers and footers .
51,665
protected function sortItems ( array $ items , & $ max = 0 ) : array { $ max = \ max ( \ array_map ( function ( $ item ) { return \ strlen ( $ this -> getName ( $ item ) ) ; } , $ items ) ) ; \ uasort ( $ items , function ( $ a , $ b ) { return $ a -> name ( ) <=> $ b -> name ( ) ; } ) ; return $ items ; }
Sort items by name . As a side effect sets max length of all names .
51,666
protected function getName ( $ item ) : string { $ name = $ item -> name ( ) ; if ( $ item instanceof Command ) { return \ trim ( \ str_pad ( $ name , $ this -> maxCmdName ) . ' ' . $ item -> alias ( ) ) ; } return $ this -> label ( $ item ) ; }
Prepare name for different items .
51,667
protected function label ( Parameter $ item ) { $ name = $ item -> name ( ) ; if ( $ item instanceof Option ) { $ name = $ item -> short ( ) . '|' . $ item -> long ( ) ; } $ variad = $ item -> variadic ( ) ? '...' : '' ; if ( $ item -> required ( ) ) { return "<$name$variad>" ; } return "[$name$variad]" ; }
Get parameter label for humans .
51,668
protected function defaults ( ) : self { $ this -> option ( '-h, --help' , 'Show help' ) -> on ( [ $ this , 'showHelp' ] ) ; $ this -> option ( '-V, --version' , 'Show version' ) -> on ( [ $ this , 'showVersion' ] ) ; $ this -> option ( '-v, --verbosity' , 'Verbosity level' , null , 0 ) -> on ( function ( ) { $ this -> set ( 'verbosity' , ( $ this -> verbosity ?? 0 ) + 1 ) ; return false ; } ) ; $ this -> onExit ( function ( $ exitCode = 0 ) { exit ( $ exitCode ) ; } ) ; return $ this ; }
Sets default options actions and exit handler .
51,669
public function argument ( string $ raw , string $ desc = '' , $ default = null ) : self { $ argument = new Argument ( $ raw , $ desc , $ default ) ; if ( $ this -> _argVariadic ) { throw new InvalidParameterException ( 'Only last argument can be variadic' ) ; } if ( $ argument -> variadic ( ) ) { $ this -> _argVariadic = true ; } $ this -> register ( $ argument ) ; return $ this ; }
Register an argument .
51,670
public function option ( string $ raw , string $ desc = '' , callable $ filter = null , $ default = null ) : self { $ option = new Option ( $ raw , $ desc , $ default , $ filter ) ; $ this -> register ( $ option ) ; return $ this ; }
Registers new option .
51,671
public function usage ( string $ usage = null ) { if ( \ func_num_args ( ) === 0 ) { return $ this -> _usage ; } $ this -> _usage = $ usage ; return $ this ; }
Gets or sets usage info .
51,672
public function showHelp ( ) { $ io = $ this -> io ( ) ; $ helper = new OutputHelper ( $ io -> writer ( ) ) ; $ io -> bold ( "Command {$this->_name}, version {$this->_version}" , true ) -> eol ( ) ; $ io -> comment ( $ this -> _desc , true ) -> eol ( ) ; $ io -> bold ( 'Usage: ' ) -> yellow ( "{$this->_name} [OPTIONS...] [ARGUMENTS...]" , true ) ; $ helper -> showArgumentsHelp ( $ this -> allArguments ( ) ) -> showOptionsHelp ( $ this -> allOptions ( ) , '' , 'Legend: <required> [optional] variadic...' ) ; if ( $ this -> _usage ) { $ io -> eol ( ) ; $ io -> boldGreen ( 'Usage Examples:' , true ) -> colors ( $ this -> _usage ) -> eol ( ) ; } return $ this -> emit ( '_exit' , 0 ) ; }
Shows command help then aborts .
51,673
public function action ( callable $ action = null ) { if ( \ func_num_args ( ) === 0 ) { return $ this -> _action ; } $ this -> _action = $ action ; return $ this ; }
Get or set command action .
51,674
public function ok ( string $ text , array $ style = [ ] ) : string { return $ this -> line ( $ text , [ 'fg' => static :: GREEN ] + $ style ) ; }
Returns a line formatted as ok msg .
51,675
public function warn ( string $ text , array $ style = [ ] ) : string { return $ this -> line ( $ text , [ 'fg' => static :: YELLOW ] + $ style ) ; }
Returns a line formatted as warning .
51,676
public function info ( string $ text , array $ style = [ ] ) : string { return $ this -> line ( $ text , [ 'fg' => static :: BLUE ] + $ style ) ; }
Returns a line formatted as info .
51,677
public function colors ( string $ text ) : string { $ text = \ str_replace ( [ '<eol>' , '<eol/>' , '</eol>' , "\r\n" , "\n" ] , '__PHP_EOL__' , $ text ) ; if ( ! \ preg_match_all ( '/<(\w+)>(.*?)<\/end>/' , $ text , $ matches ) ) { return \ str_replace ( '__PHP_EOL__' , \ PHP_EOL , $ text ) ; } $ end = "\033[0m" ; $ text = \ str_replace ( [ '<end>' , '</end>' ] , $ end , $ text ) ; foreach ( $ matches [ 1 ] as $ i => $ method ) { $ part = \ str_replace ( $ end , '' , $ this -> { $ method } ( '' ) ) ; $ text = \ str_replace ( "<$method>" , $ part , $ text ) ; } return \ str_replace ( '__PHP_EOL__' , \ PHP_EOL , $ text ) ; }
Prepare a multi colored string with html like tags .
51,678
public static function style ( string $ name , array $ style ) { $ allow = [ 'fg' => true , 'bg' => true , 'bold' => true ] ; $ style = \ array_intersect_key ( $ style , $ allow ) ; if ( empty ( $ style ) ) { throw new InvalidArgumentException ( 'Trying to set empty or invalid style' ) ; } if ( isset ( static :: $ styles [ $ name ] ) || \ method_exists ( static :: class , $ name ) ) { throw new InvalidArgumentException ( 'Trying to define existing style' ) ; } static :: $ styles [ $ name ] = $ style ; }
Register a custom style .
51,679
protected function parseCall ( string $ name , array $ arguments ) : array { list ( $ text , $ style ) = $ arguments + [ '' , [ ] ] ; if ( \ stripos ( $ name , 'bold' ) !== false ) { $ name = \ str_ireplace ( 'bold' , '' , $ name ) ; $ style += [ 'bold' => 1 ] ; } if ( ! \ preg_match_all ( '/([b|B|f|F]g)?([A-Z][a-z]+)([^A-Z])?/' , $ name , $ matches ) ) { return [ \ lcfirst ( $ name ) ? : 'line' , $ text , $ style ] ; } list ( $ name , $ style ) = $ this -> buildStyle ( $ name , $ style , $ matches ) ; return [ $ name , $ text , $ style ] ; }
Parse the name argument pairs to determine callable method and style params .
51,680
protected function buildStyle ( string $ name , array $ style , array $ matches ) : array { foreach ( $ matches [ 0 ] as $ i => $ match ) { $ name = \ str_replace ( $ match , '' , $ name ) ; $ type = \ strtolower ( $ matches [ 1 ] [ $ i ] ) ? : 'fg' ; if ( \ defined ( $ color = static :: class . '::' . \ strtoupper ( $ matches [ 2 ] [ $ i ] ) ) ) { $ style += [ $ type => \ constant ( $ color ) ] ; } } return [ \ lcfirst ( $ name ) ? : 'line' , $ style ] ; }
Build style parameter from matching combination .
51,681
public function is ( string $ arg ) : bool { return $ this -> short === $ arg || $ this -> long === $ arg ; }
Test if this option matches given arg .
51,682
public function logo ( string $ logo = null ) { if ( \ func_num_args ( ) === 0 ) { return $ this -> logo ; } $ this -> logo = $ logo ; return $ this ; }
Sets or gets the ASCII art logo .
51,683
public function command ( string $ name , string $ desc = '' , string $ alias = '' , bool $ allowUnknown = false , bool $ default = false ) : Command { $ command = new Command ( $ name , $ desc , $ allowUnknown , $ this ) ; $ this -> add ( $ command , $ alias , $ default ) ; return $ command ; }
Add a command by its name desc alias etc .
51,684
public function add ( Command $ command , string $ alias = '' , bool $ default = false ) : self { $ name = $ command -> name ( ) ; if ( $ this -> commands [ $ name ] ?? $ this -> aliases [ $ name ] ?? $ this -> commands [ $ alias ] ?? $ this -> aliases [ $ alias ] ?? null ) { throw new InvalidArgumentException ( \ sprintf ( 'Command "%s" already added' , $ name ) ) ; } if ( $ alias ) { $ command -> alias ( $ alias ) ; $ this -> aliases [ $ alias ] = $ name ; } if ( $ default ) { $ this -> default = $ name ; } $ this -> commands [ $ name ] = $ command -> version ( $ this -> version ) -> onExit ( $ this -> onExit ) -> bind ( $ this ) ; return $ this ; }
Add a prepred command .
51,685
public function commandFor ( array $ argv ) : Command { $ argv += [ null , null , null ] ; return $ this -> commands [ $ argv [ 1 ] ] ?? $ this -> commands [ $ this -> aliases [ $ argv [ 1 ] ] ?? null ] ?? $ this -> commands [ $ this -> default ] ; }
Gets matching command for given argv .
51,686
public function io ( Interactor $ io = null ) { if ( $ io || ! $ this -> io ) { $ this -> io = $ io ?? new Interactor ; } if ( \ func_num_args ( ) === 0 ) { return $ this -> io ; } return $ this ; }
Gets or sets io .
51,687
public function parse ( array $ argv ) : Command { $ this -> argv = $ argv ; $ command = $ this -> commandFor ( $ argv ) ; $ aliases = $ this -> aliasesFor ( $ command ) ; foreach ( $ argv as $ i => $ arg ) { if ( \ in_array ( $ arg , $ aliases ) ) { unset ( $ argv [ $ i ] ) ; break ; } if ( $ arg [ 0 ] === '-' ) { break ; } } return $ command -> parse ( $ argv ) ; }
Parse the arguments via the matching command but dont execute action ..
51,688
public function handle ( array $ argv ) { if ( \ count ( $ argv ) < 2 ) { return $ this -> showHelp ( ) ; } $ exitCode = 255 ; try { $ command = $ this -> parse ( $ argv ) ; $ this -> doAction ( $ command ) ; $ exitCode = 0 ; } catch ( \ Throwable $ e ) { $ this -> outputHelper ( ) -> printTrace ( $ e ) ; } return ( $ this -> onExit ) ( $ exitCode ) ; }
Handle the request invoke action and call exit handler .
51,689
protected function aliasesFor ( Command $ command ) : array { $ aliases = [ $ name = $ command -> name ( ) ] ; foreach ( $ this -> aliases as $ alias => $ command ) { if ( \ in_array ( $ name , [ $ alias , $ command ] ) ) { $ aliases [ ] = $ alias ; $ aliases [ ] = $ command ; } } return $ aliases ; }
Get aliases for given command .
51,690
public function showHelp ( ) { $ writer = $ this -> io ( ) -> writer ( ) ; $ header = "{$this->name}, version {$this->version}" ; $ footer = 'Run `<command> --help` for specific help' ; if ( $ this -> logo ) { $ writer -> write ( $ this -> logo , true ) ; } $ this -> outputHelper ( ) -> showCommandsHelp ( $ this -> commands ( ) , $ header , $ footer ) ; return ( $ this -> onExit ) ( ) ; }
Show help of all commands .
51,691
protected function doAction ( Command $ command ) { if ( $ command -> name ( ) === '__default__' ) { return $ this -> notFound ( ) ; } $ command -> interact ( $ this -> io ( ) ) ; if ( ! $ command -> action ( ) && ! \ method_exists ( $ command , 'execute' ) ) { return ; } $ params = [ ] ; $ values = $ command -> values ( ) ; $ action = $ command -> action ( ) ?? [ $ command , 'execute' ] ; foreach ( $ this -> getActionParameters ( $ action ) as $ param ) { $ params [ ] = $ values [ $ param -> getName ( ) ] ?? null ; } return $ action ( ... $ params ) ; }
Invoke command action .
51,692
protected function notFound ( ) { $ closest = [ ] ; $ attempted = $ this -> argv [ 1 ] ; $ available = \ array_keys ( $ this -> commands ( ) + $ this -> aliases ) ; foreach ( $ available as $ cmd ) { $ lev = \ levenshtein ( $ attempted , $ cmd ) ; if ( $ lev > 0 || $ lev < 5 ) { $ closest [ $ cmd ] = $ lev ; } } $ this -> io ( ) -> error ( "Command $attempted not found" , true ) ; if ( $ closest ) { \ asort ( $ closest ) ; $ closest = \ key ( $ closest ) ; $ this -> io ( ) -> bgRed ( "Did you mean $closest?" , true ) ; } return ( $ this -> onExit ) ( 127 ) ; }
Command not found handler .
51,693
public function write ( string $ text , bool $ eol = false ) : self { list ( $ method , $ this -> method ) = [ $ this -> method ? : 'line' , '' ] ; $ text = $ this -> colorizer -> { $ method } ( $ text , [ ] ) ; $ error = \ stripos ( $ method , 'error' ) !== false ; if ( $ eol ) { $ text .= \ PHP_EOL ; } return $ this -> doWrite ( $ text , $ error ) ; }
Write the formatted text to stdout or stderr .
51,694
protected function doWrite ( string $ text , bool $ error = false ) : self { $ stream = $ error ? $ this -> eStream : $ this -> stream ; \ fwrite ( $ stream , $ text ) ; return $ this ; }
Really write to the stream .
51,695
public function eol ( int $ n = 1 ) : self { return $ this -> doWrite ( \ str_repeat ( PHP_EOL , \ max ( $ n , 1 ) ) ) ; }
Write EOL n times .
51,696
public function table ( array $ rows , array $ styles = [ ] ) : self { if ( [ ] === $ table = $ this -> normalizeTable ( $ rows ) ) { return $ this ; } list ( $ head , $ rows ) = $ table ; $ styles = $ this -> normalizeStyles ( $ styles ) ; $ title = $ body = $ dash = [ ] ; list ( $ start , $ end ) = $ styles [ 'head' ] ; foreach ( $ head as $ col => $ size ) { $ dash [ ] = \ str_repeat ( '-' , $ size + 2 ) ; $ title [ ] = \ str_pad ( $ this -> toWords ( $ col ) , $ size , ' ' ) ; } $ title = "|$start " . \ implode ( " $end|$start " , $ title ) . " $end|" . \ PHP_EOL ; $ odd = true ; foreach ( $ rows as $ row ) { $ parts = [ ] ; list ( $ start , $ end ) = $ styles [ [ 'even' , 'odd' ] [ ( int ) $ odd ] ] ; foreach ( $ head as $ col => $ size ) { $ parts [ ] = \ str_pad ( $ row [ $ col ] ?? '' , $ size , ' ' ) ; } $ odd = ! $ odd ; $ body [ ] = "|$start " . \ implode ( " $end|$start " , $ parts ) . " $end|" ; } $ dash = '+' . \ implode ( '+' , $ dash ) . '+' . \ PHP_EOL ; $ body = \ implode ( \ PHP_EOL , $ body ) . \ PHP_EOL ; return $ this -> colors ( "$dash$title$dash$body$dash" ) ; }
Generate table for the console . Keys of first row are taken as header .
51,697
public function confirm ( string $ text , string $ default = 'y' ) : bool { $ choice = $ this -> choice ( $ text , [ 'y' , 'n' ] , $ default , false ) ; return \ strtolower ( $ choice [ 0 ] ?? $ default ) === 'y' ; }
Confirms if user agrees to prompt as indicated by given text .
51,698
public function choice ( string $ text , array $ choices , $ default = null , bool $ case = false ) { $ this -> writer -> yellow ( $ text ) ; $ this -> listOptions ( $ choices , $ default , false ) ; $ choice = $ this -> reader -> read ( $ default ) ; return $ this -> isValidChoice ( $ choice , $ choices , $ case ) ? $ choice : $ default ; }
Let user make a choice out of available choices .
51,699
public function choices ( string $ text , array $ choices , $ default = null , bool $ case = false ) { $ this -> writer -> yellow ( $ text ) ; $ this -> listOptions ( $ choices , $ default , true ) ; $ choice = $ this -> reader -> read ( $ default ) ; if ( \ is_string ( $ choice ) ) { $ choice = \ explode ( ',' , \ str_replace ( ' ' , '' , $ choice ) ) ; } $ valid = [ ] ; foreach ( $ choice as $ option ) { if ( $ this -> isValidChoice ( $ option , $ choices , $ case ) ) { $ valid [ ] = $ option ; } } return $ valid ? : ( array ) $ default ; }
Let user make multiple choices out of available choices .