idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
51,700
public function prompt ( string $ text , $ default = null , callable $ fn = null , int $ retry = 3 ) { $ error = 'Invalid value. Please try again!' ; $ this -> writer -> yellow ( $ text ) -> comment ( null !== $ default ? " [$default]: " : ': ' ) ; try { $ input = $ this -> reader -> read ( $ default , $ fn ) ; } catch ( \ Exception $ e ) { $ error = $ e -> getMessage ( ) ; } if ( $ retry > 0 && ( isset ( $ e ) || \ strlen ( $ input ?? '' ) === 0 ) ) { $ this -> writer -> bgRed ( $ error , true ) ; return $ this -> prompt ( $ text , $ default , $ fn , $ retry - 1 ) ; } return $ input ?? $ default ; }
Prompt user for free input .
51,701
protected function listOptions ( array $ choices , $ default = null , bool $ multi = false ) : self { if ( ! $ this -> isAssocChoice ( $ choices ) ) { return $ this -> promptOptions ( $ choices , $ default ) ; } $ maxLen = \ max ( \ array_map ( 'strlen' , \ array_keys ( $ choices ) ) ) ; foreach ( $ choices as $ choice => $ desc ) { $ this -> writer -> eol ( ) -> cyan ( \ str_pad ( " [$choice]" , $ maxLen + 6 ) ) -> comment ( $ desc ) ; } $ label = $ multi ? 'Choices (comma separated)' : 'Choice' ; $ this -> writer -> eol ( ) -> yellow ( $ label ) ; return $ this -> promptOptions ( \ array_keys ( $ choices ) , $ default ) ; }
Show choices list .
51,702
protected function promptOptions ( array $ choices , $ default ) : self { $ options = '' ; foreach ( $ choices as $ choice ) { $ style = \ in_array ( $ choice , ( array ) $ default ) ? 'boldCyan' : 'cyan' ; $ options .= "/<$style>$choice</end>" ; } $ options = \ ltrim ( $ options , '/' ) ; $ this -> writer -> colors ( " ($options): " ) ; return $ this ; }
Show prompt with possible options .
51,703
protected function isValidChoice ( $ choice , array $ choices , bool $ case ) { if ( $ this -> isAssocChoice ( $ choices ) ) { $ choices = \ array_keys ( $ choices ) ; } $ fn = [ '\strcasecmp' , '\strcmp' ] [ ( int ) $ case ] ; foreach ( $ choices as $ option ) { if ( $ fn ( $ choice , $ option ) == 0 ) { return true ; } } return false ; }
Check if user choice is one of possible choices .
51,704
public function verify ( string $ username = null , string $ password = null , string $ user = null ) { if ( $ username && $ password ) { $ users = $ this -> getUsers ( $ user ) ; foreach ( $ users as $ user => $ credentials ) { if ( password_verify ( $ username , reset ( $ credentials ) ) && password_verify ( $ password , end ( $ credentials ) ) ) { $ this -> currentUser = $ user ; return ; } } } throw new UnauthorizedHttpException ( 'Basic' ) ; }
Verify the user input .
51,705
protected function getUsers ( string $ user = null ) : array { if ( $ user !== null ) { return array_intersect_key ( $ this -> users , array_flip ( ( array ) $ user ) ) ; } return $ this -> users ; }
Get the user credentials array .
51,706
protected function createCrontab ( ) { $ tasks = $ this -> formatTasks ( ) ; $ missions = array ( ) ; foreach ( $ tasks as $ task ) { if ( $ task [ 'out' ] instanceof LoggerInterface ) { $ out = $ task [ 'out' ] ; } else { $ out = MissionLoggerFactory :: create ( $ task [ 'out' ] ) ; } if ( $ task [ 'err' ] instanceof LoggerInterface ) { $ err = $ task [ 'err' ] ; } else { $ err = MissionLoggerFactory :: create ( $ task [ 'err' ] ) ; } $ mission = new Mission ( $ task [ 'name' ] , $ task [ 'cmd' ] , $ task [ 'time' ] , $ out , $ err , $ task [ 'user' ] , $ task [ 'group' ] ) ; $ missions [ ] = $ mission ; } return new Crontab ( $ this -> logger , $ missions ) ; }
create crontab object
51,707
public function err ( LoggerInterface $ err = null ) { if ( ! is_null ( $ err ) ) { $ this -> err = $ err ; } else { return $ this -> err ; } }
get or set err
51,708
public function needRun ( $ time ) { if ( $ time - CrontabParse :: parse ( $ this -> getTime ( ) , $ time ) == 0 ) { return true ; } return false ; }
if the time is right
51,709
public function run ( ) { $ this -> setUserAndGroup ( ) ; $ out = $ this -> out ; $ err = $ this -> err ; $ process = new \ Symfony \ Component \ Process \ Process ( $ this -> cmd , null , null , null , null ) ; $ process -> run ( function ( $ type , $ buffer ) use ( $ out , $ err ) { if ( $ type == \ Symfony \ Component \ Process \ Process :: ERR ) { $ err -> error ( $ buffer ) ; } else { $ out -> info ( $ buffer ) ; } } ) ; }
start mission process
51,710
protected function setUserAndGroup ( ) { if ( ! is_null ( $ this -> user ) ) { if ( ! is_null ( $ this -> group ) ) { $ group_info = posix_getgrnam ( $ this -> user ) ; $ group_id = $ group_info [ 'gid' ] ; if ( ! posix_setgid ( $ group_id ) ) { throw new \ RuntimeException ( "set group failed" ) ; } } $ user_info = posix_getpwnam ( $ this -> user ) ; $ user_id = $ user_info [ "uid" ] ; if ( ! posix_setuid ( $ user_id ) ) { throw new \ RuntimeException ( "set user failed" ) ; } } }
set user and group if they are not null
51,711
public static function parseFile ( $ file ) { if ( ! file_exists ( $ file ) || ! is_readable ( $ file ) ) { $ message = "crontab config file is not exists or not readable" ; throw new \ RuntimeException ( $ message ) ; } $ tasks = array ( ) ; $ lines = file ( $ file ) ; foreach ( $ lines as $ line ) { $ job = new JobParse ( $ line ) ; $ tasks [ ] = $ job -> getTask ( ) ; } return $ tasks ; }
parse the system crontab service s config file
51,712
protected static function _parseCronNumbers ( $ s , $ min , $ max ) { $ result = array ( ) ; $ v = explode ( ',' , $ s ) ; foreach ( $ v as $ vv ) { $ vvv = explode ( '/' , $ vv ) ; $ step = empty ( $ vvv [ 1 ] ) ? 1 : $ vvv [ 1 ] ; $ vvvv = explode ( '-' , $ vvv [ 0 ] ) ; $ _min = count ( $ vvvv ) == 2 ? $ vvvv [ 0 ] : ( $ vvv [ 0 ] == '*' ? $ min : $ vvv [ 0 ] ) ; $ _max = count ( $ vvvv ) == 2 ? $ vvvv [ 1 ] : ( $ vvv [ 0 ] == '*' ? $ max : $ vvv [ 0 ] ) ; for ( $ i = $ _min ; $ i <= $ _max ; $ i += $ step ) { $ result [ $ i ] = intval ( $ i ) ; } } ksort ( $ result ) ; return $ result ; }
get a single cron style notation and parse it into numeric value
51,713
public function crontabCallback ( Crontab $ crontab , LoopInterface $ loop ) { $ loop -> addTimer ( 60 - time ( ) % 60 , function ( ) use ( $ crontab ) { $ pid = pcntl_fork ( ) ; if ( $ pid > 0 ) { return ; } elseif ( $ pid == 0 ) { $ crontab -> start ( time ( ) ) ; exit ( ) ; } else { $ this -> logger -> error ( "could not fork" ) ; exit ( ) ; } } ) ; }
start crontab every minute
51,714
public function processRecoverCallback ( ) { while ( ( $ pid = pcntl_waitpid ( 0 , $ status , WNOHANG ) ) > 0 ) { $ message = "process exit. pid:" . $ pid . ". exit code:" . $ status ; $ this -> logger -> info ( $ message ) ; } }
recover the sub processes
51,715
public function getByName ( $ name ) { if ( array_key_exists ( $ name , $ this -> tasks ) ) { return $ this -> tasks [ $ name ] ; } return false ; }
get task by name
51,716
final public static function memberBy ( $ property , $ value , $ isCaseSensitive = null ) { $ member = static :: memberByWithDefault ( $ property , $ value , null , $ isCaseSensitive ) ; if ( null === $ member ) { throw static :: createUndefinedMemberException ( get_called_class ( ) , $ property , $ value ) ; } return $ member ; }
Returns a single member by comparison with the result of an accessor method .
51,717
final public static function memberByWithDefault ( $ property , $ value , MultitonInterface $ default = null , $ isCaseSensitive = null ) { if ( null === $ isCaseSensitive ) { $ isCaseSensitive = true ; } if ( ! $ isCaseSensitive && is_scalar ( $ value ) ) { $ value = strtoupper ( strval ( $ value ) ) ; } return static :: memberByPredicateWithDefault ( function ( MultitonInterface $ member ) use ( $ property , $ value , $ isCaseSensitive ) { $ memberValue = $ member -> { $ property } ( ) ; if ( ! $ isCaseSensitive && is_scalar ( $ memberValue ) ) { $ memberValue = strtoupper ( strval ( $ memberValue ) ) ; } return $ memberValue === $ value ; } , $ default ) ; }
Returns a single member by comparison with the result of an accessor method . Additionally returns a default if no associated member is found .
51,718
final public static function memberByPredicate ( $ predicate ) { $ member = static :: memberByPredicateWithDefault ( $ predicate ) ; if ( null === $ member ) { throw static :: createUndefinedMemberException ( get_called_class ( ) , '<callback>' , '<callback>' ) ; } return $ member ; }
Returns a single member by predicate callback .
51,719
final public static function memberByPredicateWithDefault ( $ predicate , MultitonInterface $ default = null ) { foreach ( static :: members ( ) as $ member ) { if ( $ predicate ( $ member ) ) { return $ member ; } } return $ default ; }
Returns a single member by predicate callback . Additionally returns a default if no associated member is found .
51,720
final public static function members ( ) { $ class = get_called_class ( ) ; if ( ! array_key_exists ( $ class , self :: $ members ) ) { self :: $ members [ $ class ] = array ( ) ; static :: initializeMembers ( ) ; } return self :: $ members [ $ class ] ; }
Returns an array of all members in this multiton .
51,721
final public static function membersBy ( $ property , $ value , $ isCaseSensitive = null ) { if ( null === $ isCaseSensitive ) { $ isCaseSensitive = true ; } if ( ! $ isCaseSensitive && is_scalar ( $ value ) ) { $ value = strtoupper ( strval ( $ value ) ) ; } return static :: membersByPredicate ( function ( MultitonInterface $ member ) use ( $ property , $ value , $ isCaseSensitive ) { $ memberValue = $ member -> { $ property } ( ) ; if ( ! $ isCaseSensitive && is_scalar ( $ memberValue ) ) { $ memberValue = strtoupper ( strval ( $ memberValue ) ) ; } return $ memberValue === $ value ; } ) ; }
Returns a set of members by comparison with the result of an accessor method .
51,722
final public static function membersByPredicate ( $ predicate ) { $ members = array ( ) ; foreach ( static :: members ( ) as $ key => $ member ) { if ( $ predicate ( $ member ) ) { $ members [ $ key ] = $ member ; } } return $ members ; }
Returns a set of members by predicate callback .
51,723
protected static function createUndefinedMemberException ( $ className , $ property , $ value , NativeException $ previous = null ) { return new UndefinedMemberException ( $ className , $ property , $ value , $ previous ) ; }
Override this method in child classes to implement custom undefined member exceptions for a multiton class .
51,724
private static function registerMember ( MultitonInterface $ member ) { $ reflector = new ReflectionObject ( $ member ) ; $ parentClass = $ reflector -> getParentClass ( ) ; if ( ! $ parentClass -> isAbstract ( ) ) { throw new ExtendsConcreteException ( get_class ( $ member ) , $ parentClass -> getName ( ) ) ; } self :: $ members [ get_called_class ( ) ] [ $ member -> key ( ) ] = $ member ; }
Registers the supplied member .
51,725
final protected static function initializeMembers ( ) { $ reflector = new ReflectionClass ( get_called_class ( ) ) ; foreach ( $ reflector -> getReflectionConstants ( ) as $ constant ) { if ( $ constant -> isPublic ( ) ) { new static ( $ constant -> getName ( ) , $ constant -> getValue ( ) ) ; } } }
Initializes the members of this enumeration based upon its class constants .
51,726
function connect ( $ host , $ port = '' ) { if ( ! is_numeric ( $ port ) ) { $ port = 80 ; } $ this -> remote_host = $ host ; $ this -> remote_port = $ port ; }
Create server connection .
51,727
function set_login ( $ uname = '' , $ passwd = '' ) { if ( strlen ( $ uname ) > 0 ) { $ this -> remote_uname = $ uname ; } if ( strlen ( $ passwd ) > 0 ) { $ this -> remote_passwd = $ passwd ; } }
Specify a username and password .
51,728
protected function makeRequest ( $ resource ) { $ url = "{$this->api_url}/{$resource}" ; $ response = $ this -> guzzle -> get ( $ url , $ this -> getHeaders ( ) ) -> getBody ( ) ; return json_decode ( $ response , true ) ; }
Makes a request to the URL and returns a response .
51,729
public function getHoursLoggedFor ( $ startDate , $ endDate , $ project = null , $ branches = null ) { $ response = $ this -> summaries ( $ startDate , $ endDate , $ project , $ branches ) ; return $ this -> calculateHoursLogged ( $ response ) ; }
Calculates hours logged for a specific period . You can optionally specify a project .
51,730
public function getHoursLoggedForLast ( $ period , $ project = null , $ branches = null ) { $ endDate = date ( 'm/d/Y' ) ; $ startDate = date_format ( date_sub ( date_create ( $ endDate ) , date_interval_create_from_date_string ( $ period ) ) , 'm/d/Y' ) ; return $ this -> getHoursLoggedFor ( $ startDate , $ endDate , $ project , $ branches ) ; }
Calculates hours logged in last xy days months ... You can optionally specify a project .
51,731
public function getHoursLoggedForThisMonth ( $ project = null , $ branches = null ) { $ startDate = date ( 'm/01/Y' ) ; $ endDate = date ( 'm/d/Y' ) ; return $ this -> getHoursLoggedFor ( $ startDate , $ endDate , $ project , $ branches ) ; }
Calculates hours logged for this month . You can optionally specify a project .
51,732
public function getHoursLoggedForLastMonth ( $ project = null , $ branches = null ) { $ startDate = date_format ( date_sub ( date_create ( ) , date_interval_create_from_date_string ( '1 month' ) ) , 'm/01/Y' ) ; $ endDate = date_format ( date_sub ( date_create ( ) , date_interval_create_from_date_string ( '1 month' ) ) , 'm/t/Y' ) ; return $ this -> getHoursLoggedFor ( $ startDate , $ endDate , $ project , $ branches ) ; }
Calculates hours logged for last month . You can optionally specify a project .
51,733
protected function calculateHoursLogged ( $ response ) { $ totalSeconds = 0 ; foreach ( $ response [ 'data' ] as $ day ) { $ totalSeconds += $ day [ 'grand_total' ] [ 'total_seconds' ] ; } return ( int ) floor ( $ totalSeconds / 3600 ) ; }
Loops through response and sums seconds to calculate hours logged . Converts seconds to hours .
51,734
public static function getName ( $ value ) { $ key = array_search ( $ value , static :: toArray ( ) , true ) ; if ( $ key === false ) { static :: triggerUndefinedConstantError ( $ value ) ; } return $ key ; }
Get the name of the member that holds given value
51,735
public static function getValue ( $ member ) { $ member = ( string ) $ member ; if ( ! static :: isDefined ( $ member ) ) { static :: triggerUndefinedConstantError ( $ member ) ; } return static :: toArray ( ) [ $ member ] ; }
Get the value of a given member s name
51,736
final private static function getMemberInstance ( $ enumeration , $ member ) { if ( ! isset ( self :: $ instances [ $ enumeration ] ) || ! isset ( self :: $ instances [ $ enumeration ] [ $ member ] ) ) { self :: $ instances [ $ enumeration ] [ $ member ] = new $ enumeration ( $ member , static :: getValue ( $ member ) ) ; } return self :: $ instances [ $ enumeration ] [ $ member ] ; }
Factory for enumeration members instance representations
51,737
public function replace ( $ string ) { $ nestLevel = 1 ; do { $ originalString = $ string ; $ nestLevel ++ ; $ string = $ this -> _substitutor -> replace ( $ string ) ; } while ( ( $ originalString != $ string ) && ( $ nestLevel <= $ this -> _maxNestLevel ) ) ; return $ string ; }
Use StrSubstitutor class recursively
51,738
protected function toConfigArray ( $ source , $ nodeName ) { $ items = [ ] ; $ config = $ source -> getElementsByTagName ( $ nodeName ) ; foreach ( $ config as $ configNode ) { $ item = [ ] ; foreach ( $ configNode -> attributes as $ attribute ) { $ item [ $ attribute -> name ] = $ attribute -> value ; } $ items [ ] = $ item ; } return $ items ; }
Return config node converted to array
51,739
public function filter ( $ predicate ) { $ this -> iterator = Iterators :: filter ( $ this -> iterator , $ predicate ) ; return $ this ; }
Returns a fluent iterator returning elements of this fluent iterator that satisfy a predicate .
51,740
public static function underscoreToCamelCase ( $ string ) { $ words = explode ( '_' , $ string ) ; $ return = '' ; foreach ( $ words as $ word ) { $ return .= Strings :: uppercaseFirst ( trim ( $ word ) ) ; } return $ return ; }
Changes underscored string to the camel case .
51,741
public static function removePrefix ( $ string , $ prefix ) { if ( self :: startsWith ( $ string , $ prefix ) ) { return substr ( $ string , mb_strlen ( $ prefix ) ) ; } return $ string ; }
Returns a new string without the given prefix .
51,742
public static function removePrefixes ( $ string , array $ prefixes ) { return array_reduce ( $ prefixes , function ( $ string , $ prefix ) { return Strings :: removePrefix ( $ string , $ prefix ) ; } , $ string ) ; }
Removes prefixes defined in array from string .
51,743
public static function removeSuffix ( $ string , $ suffix ) { if ( self :: endsWith ( $ string , $ suffix ) ) { return mb_substr ( $ string , 0 , - mb_strlen ( $ suffix ) ) ; } return $ string ; }
Returns a new string without the given suffix .
51,744
public static function remove ( $ string , $ toRemove ) { $ string = is_int ( $ string ) ? "$string" : $ string ; $ toRemove = is_int ( $ toRemove ) ? "$toRemove" : $ toRemove ; if ( is_null ( $ string ) || is_null ( $ toRemove ) ) { return $ string ; } return str_replace ( $ toRemove , '' , $ string ) ; }
Removes all occurrences of a substring from string .
51,745
public static function appendIfMissing ( $ string , $ suffix ) { if ( Strings :: endsWith ( $ string , $ suffix ) ) { return $ string ; } return Strings :: appendSuffix ( $ string , $ suffix ) ; }
Adds suffix to the string if string does not end with the suffix already .
51,746
public static function prependIfMissing ( $ string , $ prefix ) { if ( Strings :: startsWith ( $ string , $ prefix ) ) { return $ string ; } return Strings :: appendPrefix ( $ string , $ prefix ) ; }
Adds prefix to the string if string does not start with the prefix already .
51,747
public static function tableize ( $ class ) { $ underscored = Strings :: camelCaseToUnderscore ( $ class ) ; $ parts = explode ( '_' , $ underscored ) ; $ suffix = Inflector :: pluralize ( array_pop ( $ parts ) ) ; $ parts [ ] = $ suffix ; return implode ( '_' , $ parts ) ; }
Converts a word into the format for an Ouzo table name . Converts ModelName to model_names .
51,748
public static function abbreviate ( $ string , $ maxWidth ) { if ( mb_strlen ( $ string ) > $ maxWidth ) { return mb_substr ( $ string , 0 , $ maxWidth ) . '...' ; } return $ string ; }
Abbreviate - abbreviates a string using ellipsis .
51,749
public static function sprintAssoc ( $ string , $ params ) { foreach ( $ params as $ key => $ value ) { $ string = preg_replace ( "/%{($key)}/" , $ value , $ string ) ; } return $ string ; }
Replace all occurrences of placeholder in string with values from associative array .
51,750
public static function sprintAssocDefault ( $ string , $ params , $ default = '' ) { foreach ( $ params as $ key => $ value ) { $ string = preg_replace ( "/%{($key)}/" , $ value , $ string ) ; } $ string = preg_replace ( "/%{\w*}/" , $ default , $ string ) ; return $ string ; }
Replace all occurrences of placeholder in string with values from associative array . When no value for placeholder is found in array a default empty value is used if not otherwise specified .
51,751
public static function substringBefore ( $ string , $ separator ) { $ pos = mb_strpos ( $ string , $ separator ) ; return $ pos !== false ? mb_substr ( $ string , 0 , $ pos ) : $ string ; }
Gets the substring before the first occurrence of a separator . The separator is not returned .
51,752
public static function substringAfter ( $ string , $ separator ) { $ pos = mb_strpos ( $ string , $ separator ) ; if ( $ pos === false ) { return $ string ; } return mb_substr ( $ string , $ pos + 1 , mb_strlen ( $ string ) ) ; }
Gets the substring after the first occurrence of a separator . The separator is not returned .
51,753
public static function first ( Iterator $ iterator ) { $ iterator -> rewind ( ) ; if ( ! $ iterator -> valid ( ) ) { throw new InvalidArgumentException ( "Iterator is empty" ) ; } return $ iterator -> current ( ) ; }
Returns the first element in iterator or throws an Exception if iterator is empty
51,754
public static function freeze ( $ date = null ) { self :: $ freeze = false ; self :: $ freezeDate = $ date ? new DateTime ( $ date ) : self :: now ( ) ; self :: $ freeze = true ; }
Freezes time to a specific point or current time if no time is given .
51,755
public static function now ( ) { $ date = new DateTime ( ) ; if ( self :: $ freeze ) { $ date -> setTimestamp ( self :: $ freezeDate -> getTimestamp ( ) ) ; $ date -> setTimezone ( self :: $ freezeDate -> getTimezone ( ) ) ; } return new Clock ( $ date ) ; }
Obtains a Clock set to the current time .
51,756
public static function move ( $ sourcePath , $ destinationPath ) { if ( ! self :: exists ( $ sourcePath ) ) { throw new FileNotFoundException ( 'Cannot find source file: ' . $ sourcePath ) ; } return rename ( $ sourcePath , $ destinationPath ) ; }
Moves file from the source to the destination throws FileNotFoundException if the source directory does not exist .
51,757
public static function convertUnitFileSize ( $ size ) { $ units = [ " B" , " KB" , " MB" , " GB" ] ; $ calculatedSize = $ size ; $ unit = Arrays :: first ( $ units ) ; if ( $ size ) { $ calculatedSize = round ( $ size / pow ( 1024 , ( $ i = ( int ) floor ( log ( $ size , 1024 ) ) ) ) , 2 ) ; $ unit = $ units [ $ i ] ; } return $ calculatedSize . $ unit ; }
Converts file size in bytes to a string with unit .
51,758
public static function getFilesRecursivelyWithSpecifiedExtension ( $ dir , $ extension ) { $ directory = new RecursiveDirectoryIterator ( $ dir ) ; $ iterator = new RecursiveIteratorIterator ( $ directory ) ; $ filter = new RegexIterator ( $ iterator , "/\.$extension$/i" , RecursiveRegexIterator :: GET_MATCH ) ; return array_keys ( iterator_to_array ( $ filter ) ) ; }
Returns all files from the given directory that have the given extension .
51,759
public static function checkWhetherFileContainsClass ( $ filePath ) { if ( ! self :: exists ( $ filePath ) ) { throw new FileNotFoundException ( 'Cannot find source file: ' . $ filePath ) ; } $ fp = fopen ( $ filePath , 'r' ) ; $ class = false ; $ buffer = '' ; $ i = 0 ; while ( ! $ class && ! feof ( $ fp ) ) { $ buffer .= fread ( $ fp , 512 ) ; $ tokens = token_get_all ( $ buffer ) ; if ( strpos ( $ buffer , '{' ) === false ) continue ; for ( ; $ i < count ( $ tokens ) ; $ i ++ ) { if ( $ tokens [ $ i ] [ 0 ] === T_CLASS ) { for ( $ j = $ i + 1 ; $ j < count ( $ tokens ) ; $ j ++ ) { if ( $ tokens [ $ j ] === '{' ) { $ class = $ tokens [ $ i + 2 ] [ 1 ] ; } } } } } return $ class ; }
Returns class name if file contains class or false if not throws FileNotFoundException when file does not exist
51,760
public function join ( array $ array ) { $ function = $ this -> _function ; $ valuesFunction = $ this -> _valuesFunction ; $ result = '' ; foreach ( $ array as $ key => $ value ) { if ( ! $ this -> _skipNulls || ( $ this -> _skipNulls && $ value ) ) { $ result .= ( $ function ? $ function ( $ key , $ value ) : ( $ valuesFunction ? $ valuesFunction ( $ value ) : $ value ) ) . $ this -> _separator ; } } return rtrim ( $ result , $ this -> _separator ) ; }
Returns a string containing array elements joined using the previously configured separator .
51,761
public static function pathToFullyQualifiedName ( $ string ) { $ parts = explode ( '/' , $ string ) ; $ namespace = '' ; foreach ( $ parts as $ part ) { $ namespace .= Strings :: underscoreToCamelCase ( $ part ) . '\\' ; } return rtrim ( $ namespace , '\\' ) ; }
Transforms path to class name with namespaces .
51,762
public static function recursive ( $ path ) { if ( is_dir ( $ path ) ) { $ iterator = new RecursiveIteratorIterator ( new RecursiveDirectoryIterator ( $ path ) , RecursiveIteratorIterator :: CHILD_FIRST ) ; foreach ( $ iterator as $ file ) { self :: _deleteFile ( $ file ) ; } rmdir ( $ path ) ; } }
Recursively deletes directories and files .
51,763
protected function getPropertyList ( $ path , $ prop = 'name' ) { return array_map ( function ( $ item ) use ( $ prop ) { return $ item [ $ prop ] ; } , $ this -> get ( $ path , [ ] ) ) ; }
Return the list of a specific property given a path
51,764
protected function getItemByProperty ( $ path , $ value , $ prop = 'name' ) { $ items = $ this -> get ( $ path , [ ] ) ; foreach ( $ items as $ item ) { if ( $ item [ $ prop ] !== $ value ) { continue ; } return $ item ; } throw new \ Exception ( sprintf ( 'Element with %s "%s" not found in %s list' , $ prop , $ value , $ path ) ) ; }
Return a configuration item given a property value
51,765
public static function toMap ( array $ elements , $ keyFunction , $ valueFunction = null ) { if ( $ valueFunction == null ) { $ valueFunction = Functions :: identity ( ) ; } $ keys = array_map ( $ keyFunction , $ elements ) ; $ values = array_map ( $ valueFunction , $ elements ) ; return empty ( $ keys ) ? [ ] : array_combine ( $ keys , $ values ) ; }
This method creates associative array using key and value functions on array elements .
51,766
public static function findKeyByValue ( array $ elements , $ value ) { if ( $ value === 0 ) { $ value = '0' ; } foreach ( $ elements as $ key => $ item ) { if ( $ item == $ value ) { return $ key ; } } return false ; }
This method returns a key for the given value .
51,767
public static function any ( array $ elements , $ predicate ) { foreach ( $ elements as $ element ) { if ( Functions :: call ( $ predicate , $ element ) ) { return true ; } } return false ; }
Returns true if at least one element in the array satisfies the predicate .
51,768
public static function filterByKeys ( array $ elements , $ predicate ) { $ allowedKeys = array_filter ( array_keys ( $ elements ) , $ predicate ) ; return self :: filterByAllowedKeys ( $ elements , $ allowedKeys ) ; }
Filters array by keys using the predicate .
51,769
public static function orderBy ( array $ elements , $ orderField ) { usort ( $ elements , function ( $ a , $ b ) use ( $ orderField ) { return $ a -> $ orderField < $ b -> $ orderField ? - 1 : 1 ; } ) ; return $ elements ; }
This method sorts elements in array using order field .
51,770
public static function mapKeys ( array $ elements , $ function ) { $ newArray = [ ] ; foreach ( $ elements as $ oldKey => $ value ) { $ newKey = Functions :: call ( $ function , $ oldKey ) ; $ newArray [ $ newKey ] = $ value ; } return $ newArray ; }
This method maps array keys using the function . Invokes the function for each key in the array . Creates a new array containing the keys returned by the function .
51,771
public static function setNestedValue ( array & $ array , array $ keys , $ value ) { $ current = & $ array ; foreach ( $ keys as $ key ) { if ( ! isset ( $ current [ $ key ] ) ) { $ current [ $ key ] = [ ] ; } $ current = & $ current [ $ key ] ; } $ current = $ value ; }
Setting nested value .
51,772
public static function removeNestedKey ( array & $ array , array $ keys , $ removeEmptyParents = false ) { $ key = array_shift ( $ keys ) ; if ( count ( $ keys ) == 0 ) { unset ( $ array [ $ key ] ) ; } elseif ( isset ( $ array [ $ key ] ) ) { self :: removeNestedKey ( $ array [ $ key ] , $ keys , $ removeEmptyParents ) ; if ( $ removeEmptyParents && empty ( $ array [ $ key ] ) ) { unset ( $ array [ $ key ] ) ; } } }
Removes nested keys in array .
51,773
public static function count ( array $ elements , $ predicate ) { $ count = 0 ; foreach ( $ elements as $ element ) { if ( Functions :: call ( $ predicate , $ element ) ) { $ count ++ ; } } return $ count ; }
Returns the number of elements for which the predicate returns true .
51,774
public static function mapEntries ( array $ elements , $ function ) { $ keys = array_keys ( $ elements ) ; $ values = array_values ( $ elements ) ; return array_combine ( $ keys , array_map ( $ function , $ keys , $ values ) ) ; }
This method maps array values using the function which takes key and value as parameters . Invokes the function for each value in the array . Creates a new array containing the values returned by the function .
51,775
public static function uniqueBy ( array $ elements , $ selector ) { return array_values ( self :: toMap ( $ elements , Functions :: extractExpression ( $ selector ) ) ) ; }
Removes duplicate values from an array . It uses the given expression to extract value that is compared .
51,776
public static function formatDate ( $ date , $ format = 'Y-m-d' ) { if ( ! $ date ) { return null ; } $ date = new DateTime ( $ date ) ; return $ date -> format ( $ format ) ; }
Returns formatted date .
51,777
public static function addInterval ( $ interval , $ format = self :: DEFAULT_TIME_FORMAT ) { $ date = Clock :: now ( ) -> toDateTime ( ) ; $ date -> add ( new DateInterval ( $ interval ) ) ; return $ date -> format ( $ format ) ; }
Adds interval to current time and returns a formatted date .
51,778
public static function modifyNow ( $ interval , $ format = self :: DEFAULT_TIME_FORMAT ) { return Clock :: now ( ) -> toDateTime ( ) -> modify ( $ interval ) -> format ( $ format ) ; }
Modifies the current time and returns a formatted date .
51,779
public static function modify ( $ dateAsString , $ interval , $ format = self :: DEFAULT_TIME_FORMAT ) { $ dateTime = new DateTime ( $ dateAsString ) ; return $ dateTime -> modify ( $ interval ) -> format ( $ format ) ; }
Modifies the given date string and returns a formatted date .
51,780
public static function formatTimestamp ( $ timestamp , $ format = self :: DEFAULT_TIME_FORMAT , $ timezone = self :: DEFAULT_TIMEZONE ) { $ dateTime = new DateTime ( ) ; $ dateTime -> setTimestamp ( $ timestamp ) ; $ dateTime -> setTimezone ( new DateTimeZone ( $ timezone ) ) ; return $ dateTime -> format ( $ format ) ; }
Returns formatted Unix timestamp .
51,781
public static function join ( ) { $ args = Arrays :: filterNotBlank ( func_get_args ( ) ) ; return preg_replace ( '~[/\\\]+~' , DIRECTORY_SEPARATOR , implode ( DIRECTORY_SEPARATOR , $ args ) ) ; }
Returns a path created by placing DIRECTORY_SEPARATOR between each argument
51,782
public static function safeDecode ( $ string , $ asArray = false ) { if ( $ string === '' || $ string === null ) { $ string = json_encode ( null ) ; } return json_decode ( $ string , $ asArray ) ; }
Decodes a JSON string
51,783
public static function decode ( $ string , $ asArray = false ) { $ decoded = self :: safeDecode ( $ string , $ asArray ) ; if ( is_null ( $ decoded ) == false ) { return $ decoded ; } $ code = self :: lastError ( ) ; if ( $ code === JSON_ERROR_NONE ) { return $ decoded ; } throw new JsonDecodeException ( self :: lastErrorMessage ( ) , $ code ) ; }
Decodes a JSON string or throws JsonDecodeException on failure
51,784
function run ( ) { $ loader = new Twig_Loader_Filesystem ( $ this -> templateDir ) ; $ twig = new Twig_Environment ( $ loader ) ; $ GLOBALS [ 'PHPDocMD_classDefinitions' ] = $ this -> classDefinitions ; $ GLOBALS [ 'PHPDocMD_linkTemplate' ] = $ this -> linkTemplate ; $ filter = new Twig_SimpleFilter ( 'classLink' , [ 'PHPDocMd\\Generator' , 'classLink' ] ) ; $ twig -> addFilter ( $ filter ) ; foreach ( $ this -> classDefinitions as $ className => $ data ) { $ output = $ twig -> render ( 'class.twig' , $ data ) ; file_put_contents ( $ this -> outputDir . '/' . $ data [ 'fileName' ] , $ output ) ; } $ index = $ this -> createIndex ( ) ; $ index = $ twig -> render ( 'index.twig' , [ 'index' => $ index , 'classDefinitions' => $ this -> classDefinitions , ] ) ; file_put_contents ( $ this -> outputDir . '/' . $ this -> apiIndexFile , $ index ) ; }
Starts the generator .
51,785
protected function createIndex ( ) { $ tree = [ ] ; foreach ( $ this -> classDefinitions as $ className => $ classInfo ) { $ current = & $ tree ; foreach ( explode ( '\\' , $ className ) as $ part ) { if ( ! isset ( $ current [ $ part ] ) ) { $ current [ $ part ] = [ ] ; } $ current = & $ current [ $ part ] ; } } $ treeOutput = '' ; $ treeOutput = function ( $ item , $ fullString = '' , $ depth = 0 ) use ( & $ treeOutput ) { $ output = '' ; foreach ( $ item as $ name => $ subItems ) { $ fullName = $ name ; if ( $ fullString ) { $ fullName = $ fullString . '\\' . $ name ; } $ output .= str_repeat ( ' ' , $ depth * 4 ) . '* ' . Generator :: classLink ( $ fullName , $ name ) . "\n" ; $ output .= $ treeOutput ( $ subItems , $ fullName , $ depth + 1 ) ; } return $ output ; } ; return $ treeOutput ( $ tree ) ; }
Creates an index of classes and namespaces .
51,786
static function classLink ( $ className , $ label = null ) { $ classDefinitions = $ GLOBALS [ 'PHPDocMD_classDefinitions' ] ; $ linkTemplate = $ GLOBALS [ 'PHPDocMD_linkTemplate' ] ; $ returnedClasses = [ ] ; foreach ( explode ( '|' , $ className ) as $ oneClass ) { $ oneClass = trim ( $ oneClass , '\\ ' ) ; if ( ! $ label ) { $ label = $ oneClass ; } if ( ! isset ( $ classDefinitions [ $ oneClass ] ) ) { $ returnedClasses [ ] = $ oneClass ; } else { $ link = str_replace ( '\\' , '-' , $ oneClass ) ; $ link = strtr ( $ linkTemplate , [ '%c' => $ link ] ) ; $ returnedClasses [ ] = sprintf ( "[%s](%s)" , $ label , $ link ) ; } } return implode ( '|' , $ returnedClasses ) ; }
This is a twig template function .
51,787
protected function getClassDefinitions ( SimpleXmlElement $ xml ) { $ classNames = [ ] ; foreach ( $ xml -> xpath ( 'file/class|file/interface' ) as $ class ) { $ className = ( string ) $ class -> full_name ; $ className = ltrim ( $ className , '\\' ) ; $ fileName = str_replace ( '\\' , '-' , $ className ) . '.md' ; $ implements = [ ] ; if ( isset ( $ class -> implements ) ) { foreach ( $ class -> implements as $ interface ) { $ implements [ ] = ltrim ( ( string ) $ interface , '\\' ) ; } } $ extends = [ ] ; if ( isset ( $ class -> extends ) ) { foreach ( $ class -> extends as $ parent ) { $ extends [ ] = ltrim ( ( string ) $ parent , '\\' ) ; } } $ classNames [ $ className ] = [ 'fileName' => $ fileName , 'className' => $ className , 'shortClass' => ( string ) $ class -> name , 'namespace' => ( string ) $ class [ 'namespace' ] , 'description' => ( string ) $ class -> docblock -> description , 'longDescription' => ( string ) $ class -> docblock -> { 'long-description' } , 'implements' => $ implements , 'extends' => $ extends , 'isClass' => $ class -> getName ( ) === 'class' , 'isInterface' => $ class -> getName ( ) === 'interface' , 'abstract' => ( string ) $ class [ 'abstract' ] == 'true' , 'deprecated' => count ( $ class -> xpath ( 'docblock/tag[@name="deprecated"]' ) ) > 0 , 'methods' => $ this -> parseMethods ( $ class ) , 'properties' => $ this -> parseProperties ( $ class ) , 'constants' => $ this -> parseConstants ( $ class ) , ] ; } $ this -> classDefinitions = $ classNames ; }
Gets all classes and interfaces from the file and puts them in an easy to use array .
51,788
protected function parseMethods ( SimpleXMLElement $ class ) { $ methods = [ ] ; $ className = ( string ) $ class -> full_name ; $ className = ltrim ( $ className , '\\' ) ; foreach ( $ class -> method as $ method ) { $ methodName = ( string ) $ method -> name ; $ return = $ method -> xpath ( 'docblock/tag[@name="return"]' ) ; if ( count ( $ return ) ) { $ return = ( string ) $ return [ 0 ] [ 'type' ] ; } else { $ return = 'mixed' ; } $ arguments = [ ] ; foreach ( $ method -> argument as $ argument ) { $ nArgument = [ 'type' => ( string ) $ argument -> type , 'name' => ( string ) $ argument -> name ] ; $ tags = $ method -> xpath ( sprintf ( 'docblock/tag[@name="param" and @variable="%s"]' , $ nArgument [ 'name' ] ) ) ; if ( count ( $ tags ) ) { $ tag = $ tags [ 0 ] ; if ( ( string ) $ tag [ 'type' ] ) { $ nArgument [ 'type' ] = ( string ) $ tag [ 'type' ] ; } if ( ( string ) $ tag [ 'description' ] ) { $ nArgument [ 'description' ] = ( string ) $ tag [ 'description' ] ; } if ( ( string ) $ tag [ 'variable' ] ) { $ nArgument [ 'name' ] = ( string ) $ tag [ 'variable' ] ; } } $ arguments [ ] = $ nArgument ; } $ argumentStr = implode ( ', ' , array_map ( function ( $ argument ) { $ return = $ argument [ 'name' ] ; if ( $ argument [ 'type' ] ) { $ return = $ argument [ 'type' ] . ' ' . $ return ; } return $ return ; } , $ arguments ) ) ; $ signature = sprintf ( '%s %s::%s(%s)' , $ return , $ className , $ methodName , $ argumentStr ) ; $ methods [ $ methodName ] = [ 'name' => $ methodName , 'description' => ( string ) $ method -> docblock -> description . "\n\n" . ( string ) $ method -> docblock -> { 'long-description' } , 'visibility' => ( string ) $ method [ 'visibility' ] , 'abstract' => ( ( string ) $ method [ 'abstract' ] ) == "true" , 'static' => ( ( string ) $ method [ 'static' ] ) == "true" , 'deprecated' => count ( $ class -> xpath ( 'docblock/tag[@name="deprecated"]' ) ) > 0 , 'signature' => $ signature , 'arguments' => $ arguments , 'definedBy' => $ className , ] ; } return $ methods ; }
Parses all the method information for a single class or interface .
51,789
protected function parseProperties ( SimpleXMLElement $ class ) { $ properties = [ ] ; $ className = ( string ) $ class -> full_name ; $ className = ltrim ( $ className , '\\' ) ; foreach ( $ class -> property as $ xProperty ) { $ type = 'mixed' ; $ propName = ( string ) $ xProperty -> name ; $ default = ( string ) $ xProperty -> default ; $ xVar = $ xProperty -> xpath ( 'docblock/tag[@name="var"]' ) ; if ( count ( $ xVar ) ) { $ type = $ xVar [ 0 ] -> type ; } $ visibility = ( string ) $ xProperty [ 'visibility' ] ; $ signature = sprintf ( '%s %s %s' , $ visibility , $ type , $ propName ) ; if ( $ default ) { $ signature .= ' = ' . $ default ; } $ properties [ $ propName ] = [ 'name' => $ propName , 'type' => $ type , 'default' => $ default , 'description' => ( string ) $ xProperty -> docblock -> description . "\n\n" . ( string ) $ xProperty -> docblock -> { 'long-description' } , 'visibility' => $ visibility , 'static' => ( ( string ) $ xProperty [ 'static' ] ) == 'true' , 'signature' => $ signature , 'deprecated' => count ( $ class -> xpath ( 'docblock/tag[@name="deprecated"]' ) ) > 0 , 'definedBy' => $ className , ] ; } return $ properties ; }
Parses all property information for a single class or interface .
51,790
protected function parseConstants ( SimpleXMLElement $ class ) { $ constants = [ ] ; $ className = ( string ) $ class -> full_name ; $ className = ltrim ( $ className , '\\' ) ; foreach ( $ class -> constant as $ xConstant ) { $ name = ( string ) $ xConstant -> name ; $ value = ( string ) $ xConstant -> value ; $ signature = sprintf ( 'const %s = %s' , $ name , $ value ) ; $ constants [ $ name ] = [ 'name' => $ name , 'description' => ( string ) $ xConstant -> docblock -> description . "\n\n" . ( string ) $ xConstant -> docblock -> { 'long-description' } , 'signature' => $ signature , 'value' => $ value , 'deprecated' => count ( $ class -> xpath ( 'docblock/tag[@name="deprecated"]' ) ) > 0 , 'definedBy' => $ className , ] ; } return $ constants ; }
Parses all constant information for a single class or interface .
51,791
protected function expandMethods ( $ className ) { $ class = $ this -> classDefinitions [ $ className ] ; $ newMethods = [ ] ; foreach ( array_merge ( $ class [ 'extends' ] , $ class [ 'implements' ] ) as $ extends ) { if ( ! isset ( $ this -> classDefinitions [ $ extends ] ) ) { continue ; } foreach ( $ this -> classDefinitions [ $ extends ] [ 'methods' ] as $ methodName => $ methodInfo ) { if ( ! isset ( $ class [ $ methodName ] ) ) { $ newMethods [ $ methodName ] = $ methodInfo ; } } $ newMethods = array_merge ( $ newMethods , $ this -> expandMethods ( $ extends ) ) ; } $ this -> classDefinitions [ $ className ] [ 'methods' ] = array_merge ( $ this -> classDefinitions [ $ className ] [ 'methods' ] , $ newMethods ) ; return $ newMethods ; }
This method goes through all the class definitions and adds non - overridden method information from parent classes .
51,792
protected function expandProperties ( $ className ) { $ class = $ this -> classDefinitions [ $ className ] ; $ newProperties = [ ] ; foreach ( array_merge ( $ class [ 'implements' ] , $ class [ 'extends' ] ) as $ extends ) { if ( ! isset ( $ this -> classDefinitions [ $ extends ] ) ) { continue ; } foreach ( $ this -> classDefinitions [ $ extends ] [ 'properties' ] as $ propertyName => $ propertyInfo ) { if ( $ propertyInfo [ 'visibility' ] === 'private' ) { continue ; } if ( ! isset ( $ class [ $ propertyName ] ) ) { $ newProperties [ $ propertyName ] = $ propertyInfo ; } } $ newProperties = array_merge ( $ newProperties , $ this -> expandProperties ( $ extends ) ) ; } $ this -> classDefinitions [ $ className ] [ 'properties' ] += $ newProperties ; return $ newProperties ; }
This method goes through all the class definitions and adds non - overridden property information from parent classes .
51,793
public function create ( ) { $ template = $ this -> template -> where ( 'active' , 1 ) -> where ( 'type' , 'admin' ) -> first ( ) ; $ templates = $ this -> template -> where ( 'active' , 1 ) -> where ( 'type' , 'default' ) -> get ( ) ; $ pageViews = $ this -> template -> getPageViews ( ) ; return view ( 'chuckcms::backend.pages.create' , compact ( 'template' , 'templates' , 'page' , 'pageViews' ) ) ; }
Show the dashboard - > page create .
51,794
public function delete ( Request $ request ) { $ this -> validate ( request ( ) , [ 'page_id' => 'required' , ] ) ; $ status = $ this -> page -> deleteById ( $ request -> get ( 'page_id' ) ) ; return $ status ; }
Delete the page and pageblocks .
51,795
public function builderIndex ( $ page_id ) { $ page = $ this -> page -> getByIdWithBlocks ( $ page_id ) ; $ template = $ this -> template -> where ( 'id' , $ page -> template_id ) -> where ( 'type' , 'default' ) -> first ( ) ; $ pageblocks = $ this -> pageBlockRepository -> getRenderedByPageBlocks ( $ this -> pageblock -> getAllByPageId ( $ page -> id ) ) ; $ block_dir = array_slice ( scandir ( 'chuckbe/' . $ template -> slug . '/blocks' ) , 2 ) ; $ blocks = $ this -> dirToArray ( $ template -> path . '/blocks' ) ; return view ( 'chuckcms::backend.pages.pagebuilder.index' , compact ( 'template' , 'page' , 'pageblocks' , 'blocks' ) ) ; }
Show the dashboard - > page edit page builder .
51,796
public function builderRaw ( $ page_id ) { $ page = $ this -> page -> getByIdWithBlocks ( $ page_id ) ; $ template = $ this -> template -> where ( 'id' , $ page -> template_id ) -> where ( 'type' , 'default' ) -> first ( ) ; $ pageblocks = $ this -> pageBlockRepository -> getRenderedByPageBlocks ( $ this -> pageblock -> getAllByPageId ( $ page -> id ) ) ; return view ( 'chuckcms::backend.pages.pagebuilder.core' , compact ( 'template' , 'page' , 'pageblocks' ) ) ; }
Return the raw page - ready for the builder
51,797
public function show ( Request $ request ) { $ pb = $ this -> pageblock -> where ( 'id' , $ request -> get ( 'pageblock_id' ) ) -> first ( ) ; $ pageblock = $ this -> pageBlockRepository -> getRenderedByPageBlock ( $ pageblock ) ; return $ pageblock ; }
Get rendered pageblock html as a string .
51,798
public function moveUp ( Request $ request ) { $ pageblock = $ this -> pageBlockRepository -> moveUpById ( $ request -> get ( 'pageblock_id' ) ) ; return $ pageblock ; }
Move the resource one place up .
51,799
public function moveDown ( Request $ request ) { $ pageblock = $ this -> pageBlockRepository -> moveDownById ( $ request -> get ( 'pageblock_id' ) ) ; return $ pageblock ; }
Move the resource one place down .