idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
58,700
private function where ( $ where ) { if ( is_array ( $ where ) && ! empty ( $ where ) ) { $ wherefields = array ( ) ; foreach ( $ where as $ field => $ value ) { $ wherefields [ ] = $ this -> formatValues ( $ field , $ value ) ; } if ( ! empty ( $ wherefields ) ) { return " WHERE " . implode ( ' AND ' , $ wherefields ) ; } } return false ; }
This outputs the SQL where query based on a given array
58,701
private function orderBy ( $ order ) { if ( is_array ( $ order ) && ! empty ( array_filter ( $ order ) ) ) { $ string = array ( ) ; foreach ( $ order as $ fieldorder => $ fieldvalue ) { if ( ! empty ( $ fieldorder ) && ! empty ( $ fieldvalue ) ) { $ string [ ] = sprintf ( "`%s` %s" , SafeString :: makeSafe ( $ fieldorder ) , strtoupper ( SafeString :: makeSafe ( $ fieldvalue ) ) ) ; } elseif ( $ fieldvalue === 'RAND()' ) { $ string [ ] = $ fieldvalue ; } } return sprintf ( " ORDER BY %s" , implode ( ", " , $ string ) ) ; } elseif ( $ order == 'RAND()' ) { return " ORDER BY RAND()" ; } return false ; }
Sets the order sting for the SQL query based on an array or string
58,702
private function fields ( $ records , $ insert = false ) { $ fields = array ( ) ; foreach ( $ records as $ field => $ value ) { if ( $ insert === true ) { $ fields [ ] = sprintf ( "`%s`" , SafeString :: makeSafe ( $ field ) ) ; $ this -> prepare [ ] = '?' ; } else { $ fields [ ] = sprintf ( "`%s` = ?" , SafeString :: makeSafe ( $ field ) ) ; } $ this -> values [ ] = $ value ; } return implode ( ', ' , $ fields ) ; }
Build the field list for the query
58,703
private function limit ( $ limit = 0 ) { if ( is_array ( $ limit ) && ! empty ( array_filter ( $ limit ) ) ) { foreach ( $ limit as $ start => $ end ) { return " LIMIT " . intval ( $ start ) . ", " . intval ( $ end ) ; } } elseif ( ( int ) $ limit > 0 ) { return " LIMIT " . intval ( $ limit ) ; } return false ; }
Returns the limit SQL for the current query as a string
58,704
public function setCache ( $ key , $ value ) { if ( $ this -> cacheEnabled ) { $ this -> cacheObj -> save ( $ key , $ value ) ; } }
Set the cache with a key and value
58,705
public function getCache ( $ key ) { if ( $ this -> modified === true || ! $ this -> cacheEnabled ) { return false ; } else { $ this -> cacheValue = $ this -> cacheObj -> fetch ( $ key ) ; return $ this -> cacheValue ; } }
Get the results for a given key
58,706
protected function formatValues ( $ field , $ value ) { if ( ! is_array ( $ value ) && Operators :: isOperatorValid ( $ value ) && ! Operators :: isOperatorPrepared ( $ value ) ) { return sprintf ( "`%s` %s" , SafeString :: makeSafe ( $ field ) , Operators :: getOperatorFormat ( $ value ) ) ; } elseif ( is_array ( $ value ) ) { $ keys = [ ] ; if ( ! is_array ( array_values ( $ value ) [ 0 ] ) ) { $ this -> values [ ] = ( isset ( $ value [ 1 ] ) ? $ value [ 1 ] : array_values ( $ value ) [ 0 ] ) ; $ operator = ( isset ( $ value [ 0 ] ) ? $ value [ 0 ] : key ( $ value ) ) ; } else { foreach ( array_values ( $ value ) [ 0 ] as $ op => $ array_value ) { $ this -> values [ ] = $ array_value ; $ keys [ ] = '?' ; } $ operator = key ( $ value ) ; } return sprintf ( "`%s` %s" , SafeString :: makeSafe ( $ field ) , sprintf ( Operators :: getOperatorFormat ( $ operator ) , implode ( $ keys , ', ' ) ) ) ; } $ this -> values [ ] = $ value ; return sprintf ( "`%s` = ?" , SafeString :: makeSafe ( $ field ) ) ; }
Format the where queries and set the prepared values
58,707
protected function bindValues ( $ values ) { if ( is_array ( $ values ) ) { foreach ( $ values as $ i => $ value ) { if ( is_numeric ( $ value ) && intval ( $ value ) == $ value && $ value [ 0 ] != 0 ) { $ type = PDO :: PARAM_INT ; $ value = intval ( $ value ) ; } elseif ( is_null ( $ value ) || $ value === 'NULL' ) { $ type = PDO :: PARAM_NULL ; $ value = NULL ; } elseif ( is_bool ( $ value ) ) { $ type = PDO :: PARAM_BOOL ; } else { $ type = PDO :: PARAM_STR ; } $ this -> query -> bindValue ( intval ( $ i + 1 ) , $ value , $ type ) ; } } }
Band values to use in the query
58,708
public function check ( ExerciseInterface $ exercise , Input $ input ) { if ( ! $ exercise instanceof ComposerExerciseCheck ) { throw new \ InvalidArgumentException ; } if ( ! file_exists ( sprintf ( '%s/composer.json' , dirname ( $ input -> getArgument ( 'program' ) ) ) ) ) { return new Failure ( $ this -> getName ( ) , 'No composer.json file found' ) ; } if ( ! file_exists ( sprintf ( '%s/composer.lock' , dirname ( $ input -> getArgument ( 'program' ) ) ) ) ) { return new Failure ( $ this -> getName ( ) , 'No composer.lock file found' ) ; } if ( ! file_exists ( sprintf ( '%s/vendor' , dirname ( $ input -> getArgument ( 'program' ) ) ) ) ) { return new Failure ( $ this -> getName ( ) , 'No vendor folder found' ) ; } $ lockFile = new LockFileParser ( sprintf ( '%s/composer.lock' , dirname ( $ input -> getArgument ( 'program' ) ) ) ) ; $ missingPackages = array_filter ( $ exercise -> getRequiredPackages ( ) , function ( $ package ) use ( $ lockFile ) { return ! $ lockFile -> hasInstalledPackage ( $ package ) ; } ) ; if ( count ( $ missingPackages ) > 0 ) { return new Failure ( $ this -> getName ( ) , sprintf ( 'Lockfile doesn\'t include the following packages at any version: "%s"' , implode ( '", "' , $ missingPackages ) ) ) ; } return new Success ( $ this -> getName ( ) ) ; }
This check parses the composer . lock file and checks that the student installed a set of required packages . If they did not a failure is returned otherwise a success is returned .
58,709
public function run ( ) { $ container = $ this -> getContainer ( ) ; foreach ( $ this -> exercises as $ exercise ) { if ( false === $ container -> has ( $ exercise ) ) { throw new \ RuntimeException ( sprintf ( 'No DI config found for exercise: "%s". Register a factory.' , $ exercise ) ) ; } } $ checkRepository = $ container -> get ( CheckRepository :: class ) ; foreach ( $ this -> checks as $ check ) { if ( false === $ container -> has ( $ check ) ) { throw new \ RuntimeException ( sprintf ( 'No DI config found for check: "%s". Register a factory.' , $ check ) ) ; } $ checkRepository -> registerCheck ( $ container -> get ( $ check ) ) ; } if ( ! empty ( $ this -> results ) ) { $ resultFactory = $ container -> get ( ResultRendererFactory :: class ) ; foreach ( $ this -> results as $ result ) { $ resultFactory -> registerRenderer ( $ result [ 'resultClass' ] , $ result [ 'resultRendererClass' ] ) ; } } try { $ exitCode = $ container -> get ( CommandRouter :: class ) -> route ( ) ; } catch ( MissingArgumentException $ e ) { $ container -> get ( OutputInterface :: class ) -> printError ( sprintf ( 'Argument%s: "%s" %s missing!' , count ( $ e -> getMissingArguments ( ) ) > 1 ? 's' : '' , implode ( '", "' , $ e -> getMissingArguments ( ) ) , count ( $ e -> getMissingArguments ( ) ) > 1 ? 'are' : 'is' ) ) ; return 1 ; } catch ( \ RuntimeException $ e ) { $ container -> get ( OutputInterface :: class ) -> printError ( sprintf ( '%s' , $ e -> getMessage ( ) ) ) ; return 1 ; } return $ exitCode ; }
Executes the framework invoking the specified command . The return value is the exit code . 0 for success anything else is a failure .
58,710
protected function determineType ( ) { if ( in_array ( $ this -> group , static :: $ linkGroups ) ) { return 'link' ; } if ( in_array ( $ this -> extension , static :: $ pictureExtensions ) ) { return 'picture' ; } if ( in_array ( $ this -> extension , static :: $ videoExtensions ) ) { return 'video' ; } return 'document' ; }
Tries to determine type by extention or group
58,711
protected function doMatch ( $ actual ) { if ( $ actual instanceof Traversable ) { return $ this -> matchTraversable ( $ actual ) ; } if ( is_array ( $ actual ) ) { return array_search ( $ this -> expected , $ actual , true ) !== false ; } if ( is_string ( $ actual ) ) { return strpos ( $ actual , $ this -> expected ) !== false ; } throw new InvalidArgumentException ( 'Inclusion matcher requires a string or array' ) ; }
Matches if an array or string contains the expected value .
58,712
public function check ( ExerciseInterface $ exercise , Input $ input ) { if ( file_exists ( $ input -> getArgument ( 'program' ) ) ) { return Success :: fromCheck ( $ this ) ; } return Failure :: fromCheckAndReason ( $ this , sprintf ( 'File: "%s" does not exist' , $ input -> getArgument ( 'program' ) ) ) ; }
Simply check that the file exists .
58,713
public static function getFuzzyDistance ( string $ term , $ mode ) : int { if ( self :: MODE_1 === $ mode ) { return 1 ; } if ( self :: MODE_2 === $ mode ) { return 2 ; } if ( strlen ( $ term ) < 3 ) { return 1 ; } return 2 ; }
Returns distance for given mode .
58,714
public static function getFuzzyTerms ( string $ term , $ mode ) : array { $ distance = self :: getFuzzyDistance ( $ term , $ mode ) ; if ( 1 === $ distance ) { return self :: generateFuzzyTerms ( $ term ) ; } return self :: generateFuzzyTermsTwice ( $ term ) ; }
Returns fuzzy terms .
58,715
private static function generateFuzzyTermsTwice ( string $ term ) : array { $ terms = [ ] ; foreach ( self :: generateFuzzyTerms ( $ term ) as $ term ) { $ terms [ ] = $ term ; $ terms = array_merge ( $ terms , self :: generateFuzzyTerms ( $ term ) ) ; } return $ terms ; }
Generates fuzzy terms twice .
58,716
private static function generateFuzzyTerms ( string $ term ) : array { $ terms = [ $ term . '_' ] ; for ( $ i = 0 ; $ i < strlen ( $ term ) ; ++ $ i ) { $ terms [ ] = substr ( $ term , 0 , $ i ) . '_' . substr ( $ term , $ i ) ; $ terms [ ] = substr ( $ term , 0 , $ i ) . substr ( $ term , $ i + 1 ) ; $ terms [ ] = substr ( $ term , 0 , $ i ) . '_' . substr ( $ term , $ i + 1 ) ; } return $ terms ; }
Generates fuzzy terms .
58,717
public function pushParser ( Useragent \ ParserInterface $ parser ) { $ this -> parser = $ parser ; if ( $ this -> ua ) { $ this -> setUA ( $ this -> ua ) ; } }
Set the useragent
58,718
public function getSetter ( $ apiPropertyName ) { $ property = $ this -> getProperty ( $ apiPropertyName ) ; return 'set' . str_replace ( ' ' , '' , ucwords ( str_replace ( '_' , ' ' , $ property ) ) ) ; }
gets the setter for a api property name
58,719
protected function getValues ( $ apiPropertyName ) { $ mapping = $ this -> getMapping ( ) ; return array_key_exists ( $ apiPropertyName , $ mapping ) ? $ mapping [ $ apiPropertyName ] : array ( ) ; }
get mapping information of a api property
58,720
protected function xmlDeserialize ( $ xml ) { $ array = [ ] ; if ( ! $ xml instanceof SimpleXMLElement ) { $ xml = new SimpleXMLElement ( $ xml ) ; } foreach ( $ xml -> children ( ) as $ key => $ child ) { $ value = ( string ) $ child ; $ _children = $ this -> xmlDeserialize ( $ child ) ; $ _push = ( $ _hasChild = ( count ( $ _children ) > 0 ) ) ? $ _children : $ value ; if ( $ _hasChild && ! empty ( $ value ) && $ value !== '' ) { $ _push [ ] = $ value ; } $ array [ $ key ] = $ _push ; } return $ array ; }
Seserializes XML to an array
58,721
public static function fromCheckAndCodeParseFailure ( CheckInterface $ check , ParseErrorException $ e , $ file ) { return new static ( $ check -> getName ( ) , sprintf ( 'File: "%s" could not be parsed. Error: "%s"' , $ file , $ e -> getMessage ( ) ) ) ; }
Static constructor to create from a PhpParser \ Error exception . Many checks will need to parse the student s solution so this serves as a helper to create a consistent failure .
58,722
public function render ( $ markdown ) { $ ast = $ this -> docParser -> parse ( $ markdown ) ; return $ this -> cliRenderer -> renderBlock ( $ ast ) ; }
Expects a string of markdown and returns a string which has been formatted for displaying on the console .
58,723
public function isInstanceOf ( $ object , $ class , $ message = '' ) { $ this -> assertion -> setActual ( $ object ) ; return $ this -> assertion -> is -> instanceof ( $ class , $ message ) ; }
Perform an instanceof assertion .
58,724
public function notInstanceOf ( $ object , $ class , $ message = '' ) { $ this -> assertion -> setActual ( $ object ) ; return $ this -> assertion -> is -> not -> instanceof ( $ class , $ message ) ; }
Perform a negated instanceof assertion .
58,725
public function property ( $ object , $ property , $ message = '' ) { $ this -> assertion -> setActual ( $ object ) ; return $ this -> assertion -> to -> have -> property ( $ property , null , $ message ) ; }
Perform a property assertion .
58,726
public function notDeepProperty ( $ object , $ property , $ message = '' ) { $ this -> assertion -> setActual ( $ object ) ; return $ this -> assertion -> to -> not -> have -> deep -> property ( $ property , null , $ message ) ; }
Perform a negated deep property assertion .
58,727
public function propertyVal ( $ object , $ property , $ value , $ message = '' ) { $ this -> assertion -> setActual ( $ object ) ; return $ this -> assertion -> to -> have -> property ( $ property , $ value , $ message ) ; }
Perform a property value assertion .
58,728
public function propertyNotVal ( $ object , $ property , $ value , $ message = '' ) { $ this -> assertion -> setActual ( $ object ) ; return $ this -> assertion -> to -> not -> have -> property ( $ property , $ value , $ message ) ; }
Perform a negated property value assertion .
58,729
public function deepPropertyVal ( $ object , $ property , $ value , $ message = '' ) { $ this -> assertion -> setActual ( $ object ) ; return $ this -> assertion -> to -> have -> deep -> property ( $ property , $ value , $ message ) ; }
Perform a deep property value assertion .
58,730
public function deepPropertyNotVal ( $ object , $ property , $ value , $ message = '' ) { $ this -> assertion -> setActual ( $ object ) ; return $ this -> assertion -> to -> not -> have -> deep -> property ( $ property , $ value , $ message ) ; }
Perform a negated deep property value assertion .
58,731
public function verify ( Input $ input ) { $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'cli.verify.start' , $ this -> exercise , $ input ) ) ; $ result = new CliResult ( array_map ( function ( array $ args ) use ( $ input ) { return $ this -> doVerify ( $ args , $ input ) ; } , $ this -> preserveOldArgFormat ( $ this -> exercise -> getArgs ( ) ) ) ) ; $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'cli.verify.finish' , $ this -> exercise , $ input ) ) ; return $ result ; }
Verifies a solution by invoking PHP from the CLI passing the arguments gathered from the exercise as command line arguments to PHP .
58,732
private function preserveOldArgFormat ( array $ args ) { if ( isset ( $ args [ 0 ] ) && ! is_array ( $ args [ 0 ] ) ) { $ args = [ $ args ] ; } elseif ( empty ( $ args ) ) { $ args = [ [ ] ] ; } return $ args ; }
BC - getArgs only returned 1 set of args in v1 instead of multiple sets of args in v2
58,733
public function run ( Input $ input , OutputInterface $ output ) { $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'cli.run.start' , $ this -> exercise , $ input ) ) ; $ success = true ; foreach ( $ this -> preserveOldArgFormat ( $ this -> exercise -> getArgs ( ) ) as $ i => $ args ) { $ event = $ this -> eventDispatcher -> dispatch ( new CliExecuteEvent ( 'cli.run.student-execute.pre' , new ArrayObject ( $ args ) ) ) ; $ args = $ event -> getArgs ( ) ; if ( count ( $ args ) ) { $ glue = max ( array_map ( 'strlen' , $ args -> getArrayCopy ( ) ) ) > 30 ? "\n" : ', ' ; $ output -> writeTitle ( 'Arguments' ) ; $ output -> write ( implode ( $ glue , $ args -> getArrayCopy ( ) ) ) ; $ output -> emptyLine ( ) ; } $ output -> writeTitle ( "Output" ) ; $ process = $ this -> getPhpProcess ( $ input -> getArgument ( 'program' ) , $ args ) ; $ process -> start ( ) ; $ this -> eventDispatcher -> dispatch ( new CliExecuteEvent ( 'cli.run.student.executing' , $ args , [ 'output' => $ output ] ) ) ; $ process -> wait ( function ( $ outputType , $ outputBuffer ) use ( $ output ) { $ output -> write ( $ outputBuffer ) ; } ) ; $ output -> emptyLine ( ) ; if ( ! $ process -> isSuccessful ( ) ) { $ success = false ; } $ output -> lineBreak ( ) ; } $ this -> eventDispatcher -> dispatch ( new ExerciseRunnerEvent ( 'cli.run.finish' , $ this -> exercise , $ input ) ) ; return $ success ; }
Runs a student s solution by invoking PHP from the CLI passing the arguments gathered from the exercise as command line arguments to PHP .
58,734
public function dispatch ( EventInterface $ event ) { if ( array_key_exists ( $ event -> getName ( ) , $ this -> listeners ) ) { foreach ( $ this -> listeners [ $ event -> getName ( ) ] as $ listener ) { $ listener ( $ event ) ; } } return $ event ; }
Dispatch an event . Can be any event object which implements PhpSchool \ PhpWorkshop \ Event \ EventInterface .
58,735
public function insertVerifier ( $ eventName , callable $ verifier ) { $ this -> attachListener ( $ eventName , function ( EventInterface $ event ) use ( $ verifier ) { $ result = $ verifier ( $ event ) ; if ( $ result instanceof ResultInterface ) { $ this -> resultAggregator -> add ( $ result ) ; } else { } } ) ; }
Insert a verifier callback which will execute at the given event name much like normal listeners . A verifier should return an object which implements PhpSchool \ PhpWorkshop \ Result \ FailureInterface or PhpSchool \ PhpWorkshop \ Result \ SuccessInterface . This result object will be added to the result aggregator .
58,736
private function findNearestCommand ( $ commandName , array $ commands ) { $ distances = [ ] ; foreach ( array_keys ( $ commands ) as $ command ) { $ distances [ $ command ] = levenshtein ( $ commandName , $ command ) ; } $ distances = array_filter ( array_unique ( $ distances ) , function ( $ distance ) { return $ distance <= 3 ; } ) ; if ( empty ( $ distances ) ) { return false ; } return array_search ( min ( $ distances ) , $ distances ) ; }
Get the closest command to the one typed but only if there is 3 or less characters different
58,737
public function generateUrl ( $ call , array $ params = array ( ) ) { $ url = $ this -> baseUrl . '/' . $ this -> version . '/' . $ call ; if ( count ( $ params ) > 0 ) { $ queryString = http_build_query ( $ params , null , '&' ) ; $ queryString = preg_replace ( '/%5B[0-9]+%5D/simU' , '%5B%5D' , $ queryString ) ; $ url .= '?' . $ queryString ; } return $ url ; }
generates a url for an api request
58,738
public function call ( $ call , array $ params = array ( ) ) { $ startTime = microtime ( true ) ; if ( ! array_key_exists ( 'culture' , $ params ) ) { $ params [ 'culture' ] = $ this -> culture ; } $ url = $ this -> generateUrl ( $ call , $ params ) ; $ this -> logger -> debug ( 'call start' , array ( 'url' => $ url , ) ) ; $ key = $ this -> cache -> generateCacheKey ( $ url ) ; $ content = $ this -> cache -> get ( $ key ) ; if ( $ content !== false ) { $ this -> logger -> debug ( 'call end' , array ( 'url' => $ url , 'cache' => true , 'time' => microtime ( true ) - $ startTime , 'response' => $ content , ) ) ; return $ content ; } $ request = $ this -> createRequest ( $ url ) ; if ( ! ini_get ( 'open_basedir' ) && filter_var ( ini_get ( 'safe_mode' ) , FILTER_VALIDATE_BOOLEAN ) === false ) { $ request -> setOption ( CURLOPT_FOLLOWLOCATION , true ) ; } $ response = $ request -> get ( ) ; if ( $ request -> getError ( ) ) { $ this -> throwError ( 'The Api call returned an error: "' . $ request -> getError ( ) . '"' ) ; } if ( $ request -> getStatusCode ( ) == 401 ) { $ this -> throwError ( 'Bad Username / Password ' . $ request -> getStatusCode ( ) , '\Justimmo\Exception\AuthenticationException' ) ; } if ( $ request -> getStatusCode ( ) == 404 ) { $ this -> throwError ( 'Api call not found: ' . $ request -> getStatusCode ( ) , '\Justimmo\Exception\NotFoundException' ) ; } if ( $ request -> getStatusCode ( ) >= 400 && $ request -> getStatusCode ( ) < 500 ) { $ exception = new InvalidRequestException ( 'The Api call returned status code ' . $ request -> getStatusCode ( ) ) ; $ exception -> setResponse ( $ request -> getContent ( ) ) ; $ this -> logger -> error ( $ exception -> getMessage ( ) ) ; throw $ exception ; } if ( $ request -> getStatusCode ( ) != 200 ) { $ this -> throwError ( 'The Api call returned status code ' . $ request -> getStatusCode ( ) , '\Justimmo\Exception\StatusCodeException' ) ; } $ this -> cache -> set ( $ key , $ response ) ; $ this -> logger -> debug ( 'call end' , array ( 'url' => $ url , 'cache' => false , 'time' => microtime ( true ) - $ startTime , 'response' => $ response , ) ) ; return $ response ; }
Makes a call to the justimmo api
58,739
public function setLanguage ( Event $ event ) { $ app = $ event -> data ; foreach ( $ this -> handlers as $ handler ) { $ intersection = array_intersect ( $ this -> languages , $ handler -> getLanguages ( ) ) ; if ( ! empty ( $ intersection ) ) { Yii :: $ app -> language = current ( $ intersection ) ; break ; } } $ app -> trigger ( self :: EVENT_AFTER_SETTING_LANGUAGE ) ; }
Sets the application language .
58,740
protected function getImageInstance ( ) { try { $ imageInstance = $ this -> ImageManager -> make ( $ this -> path ) ; } catch ( NotReadableException $ e ) { $ message = __d ( 'thumber' , 'Unable to read image from file `{0}`' , rtr ( $ this -> path ) ) ; if ( $ e -> getMessage ( ) == 'Unsupported image type. GD driver is only able to decode JPG, PNG, GIF or WebP files.' ) { $ message = __d ( 'thumber' , 'Image type `{0}` is not supported by this driver' , mime_content_type ( $ this -> path ) ) ; } throw new RuntimeException ( $ message ) ; } return $ imageInstance ; }
Gets an Image instance
58,741
public function getUrl ( $ fullBase = true ) { is_true_or_fail ( ! empty ( $ this -> target ) , __d ( 'thumber' , 'Missing path of the generated thumbnail. Probably the `{0}` method has not been invoked' , 'save()' ) , InvalidArgumentException :: class ) ; return Router :: url ( [ '_name' => 'thumb' , base64_encode ( basename ( $ this -> target ) ) ] , $ fullBase ) ; }
Builds and returns the url for the generated thumbnail
58,742
public function crop ( $ width = null , $ heigth = null , array $ options = [ ] ) { $ heigth = $ heigth ? : $ width ; $ width = $ width ? : $ heigth ; $ options += [ 'x' => null , 'y' => null ] ; $ this -> arguments [ ] = [ __FUNCTION__ , $ width , $ heigth , $ options ] ; $ this -> callbacks [ ] = function ( Image $ imageInstance ) use ( $ width , $ heigth , $ options ) { return $ imageInstance -> crop ( $ width , $ heigth , $ options [ 'x' ] , $ options [ 'y' ] ) ; } ; return $ this ; }
Crops the image cutting out a rectangular part of the image .
58,743
public function fit ( $ width = null , $ heigth = null , array $ options = [ ] ) { $ heigth = $ heigth ? : $ width ; $ width = $ width ? : $ heigth ; $ options += [ 'position' => 'center' , 'upsize' => true ] ; $ this -> arguments [ ] = [ __FUNCTION__ , $ width , $ heigth , $ options ] ; $ this -> callbacks [ ] = function ( Image $ imageInstance ) use ( $ width , $ heigth , $ options ) { return $ imageInstance -> fit ( $ width , $ heigth , function ( Constraint $ constraint ) use ( $ options ) { if ( $ options [ 'upsize' ] ) { $ constraint -> upsize ( ) ; } } , $ options [ 'position' ] ) ; } ; return $ this ; }
Resizes the image combining cropping and resizing to format image in a smart way . It will find the best fitting aspect ratio on the current image automatically cut it out and resize it to the given dimension
58,744
public function resizeCanvas ( $ width , $ heigth = null , array $ options = [ ] ) { $ options += [ 'anchor' => 'center' , 'relative' => false , 'bgcolor' => '#ffffff' ] ; $ this -> arguments [ ] = [ __FUNCTION__ , $ width , $ heigth , $ options ] ; $ this -> callbacks [ ] = function ( Image $ imageInstance ) use ( $ width , $ heigth , $ options ) { return $ imageInstance -> resizeCanvas ( $ width , $ heigth , $ options [ 'anchor' ] , $ options [ 'relative' ] , $ options [ 'bgcolor' ] ) ; } ; return $ this ; }
Resizes the boundaries of the current image to given width and height . An anchor can be defined to determine from what point of the image the resizing is going to happen . Set the mode to relative to add or subtract the given width or height to the actual image dimensions . You can also pass a background color for the emerging area of the image
58,745
public function save ( array $ options = [ ] ) { is_true_or_fail ( $ this -> callbacks , __d ( 'thumber' , 'No valid method called before the `{0}` method' , __FUNCTION__ ) , RuntimeException :: class ) ; $ options = $ this -> getDefaultSaveOptions ( $ options ) ; $ target = $ options [ 'target' ] ; if ( ! $ target ) { $ this -> arguments [ ] = [ $ this -> driver , $ options [ 'format' ] , $ options [ 'quality' ] ] ; $ target = sprintf ( '%s_%s.%s' , md5 ( $ this -> path ) , md5 ( serialize ( $ this -> arguments ) ) , $ options [ 'format' ] ) ; } else { $ optionsFromTarget = $ this -> getDefaultSaveOptions ( [ ] , $ target ) ; $ options [ 'format' ] = $ optionsFromTarget [ 'format' ] ; } $ target = Folder :: isAbsolute ( $ target ) ? $ target : $ this -> getPath ( $ target ) ; $ File = new File ( $ target ) ; if ( ! $ File -> exists ( ) ) { $ imageInstance = $ this -> getImageInstance ( ) ; foreach ( $ this -> callbacks as $ callback ) { call_user_func ( $ callback , $ imageInstance ) ; } $ content = $ imageInstance -> encode ( $ options [ 'format' ] , $ options [ 'quality' ] ) ; $ imageInstance -> destroy ( ) ; is_true_or_fail ( $ File -> write ( $ content ) , __d ( 'thumber' , 'Unable to create file `{0}`' , rtr ( $ target ) ) , RuntimeException :: class ) ; $ File -> close ( ) ; } $ this -> arguments = $ this -> callbacks = [ ] ; return $ this -> target = $ target ; }
Saves the thumbnail and returns its path
58,746
public function xpath ( ) { if ( ! isset ( $ this -> xpath ) ) { $ this -> xpath = new \ DOMXPath ( $ this ) ; } return $ this -> xpath ; }
Creates a DOMXPath to query this document .
58,747
protected function runUrlMethod ( $ name , $ path , array $ params = [ ] , array $ options = [ ] ) { $ name = $ this -> isUrlMethod ( $ name ) ? substr ( $ name , 0 , - 3 ) : $ name ; $ params += [ 'format' => 'jpg' , 'height' => null , 'width' => null ] ; $ options += [ 'fullBase' => true ] ; $ thumber = new ThumbCreator ( $ path ) ; is_true_or_fail ( method_exists ( $ thumber , $ name ) , __d ( 'thumber' , 'Method `{0}::{1}()` does not exist' , get_class ( $ this ) , $ name ) , RuntimeException :: class ) ; $ thumber -> $ name ( $ params [ 'width' ] , $ params [ 'height' ] ) -> save ( $ params ) ; return $ thumber -> getUrl ( $ options [ 'fullBase' ] ) ; }
Runs an Url method and returns the url generated by the method
58,748
public function add ( array $ data ) { $ defaults = array ( "description" => null , "price" => null , "discount" => null , "qty" => 1 , "unit" => null ) ; $ merged = array_merge ( $ defaults , $ data ) ; $ line = $ this -> create ( $ this -> invoiceHandle ) ; if ( isset ( $ merged [ 'product' ] ) ) { $ this -> product ( $ line , $ merged [ 'product' ] ) ; unset ( $ merged [ 'product' ] ) ; } return $ this -> update ( $ data , $ line ) ; }
Add Invoice line
58,749
public function update ( array $ data , $ line ) { if ( is_integer ( $ line ) ) { $ line = array ( 'Id' => $ line ) ; } foreach ( $ data as $ name => $ value ) { if ( is_null ( $ value ) ) continue ; switch ( strtolower ( $ name ) ) { case 'description' : $ this -> description ( $ line , $ value ) ; break ; case 'price' : $ this -> price ( $ line , $ value ) ; break ; case 'discount' : $ this -> discount ( $ line , $ value ) ; break ; case 'qty' : $ this -> qty ( $ line , $ value ) ; break ; case 'unit' : $ this -> unit ( $ line , $ value ) ; break ; } } return $ this -> getArrayFromHandles ( array ( 'CurrentInvoiceLineHandle' => $ line ) ) ; }
Update Invoice Line with data
58,750
public function product ( $ invoiceLineHandle , $ product ) { $ products = new Product ( $ this -> client_raw ) ; $ productHandle = $ products -> getHandle ( $ product ) ; $ this -> client -> CurrentInvoiceLine_SetProduct ( array ( 'currentInvoiceLineHandle' => $ invoiceLineHandle , 'valueHandle' => $ productHandle ) ) ; return true ; }
Set Invoice Line product by product number
58,751
public function itemType ( ) { $ itemtype = $ this -> getAttribute ( 'itemtype' ) ; if ( ! empty ( $ itemtype ) ) { return $ this -> tokenList ( $ itemtype ) ; } return NULL ; }
Retrieve this item s itemtypes .
58,752
public function properties ( ) { $ props = array ( ) ; if ( $ this -> itemScope ( ) ) { $ toTraverse = array ( $ this ) ; foreach ( $ this -> itemRef ( ) as $ itemref ) { $ children = $ this -> ownerDocument -> xpath ( ) -> query ( '//*[@id="' . $ itemref . '"]' ) ; foreach ( $ children as $ child ) { $ this -> traverse ( $ child , $ toTraverse , $ props , $ this ) ; } } while ( count ( $ toTraverse ) ) { $ this -> traverse ( $ toTraverse [ 0 ] , $ toTraverse , $ props , $ this ) ; } } return $ props ; }
Retrieve the properties
58,753
public function itemValue ( ) { $ itemprop = $ this -> itemProp ( ) ; if ( empty ( $ itemprop ) ) return null ; if ( $ this -> itemScope ( ) ) { return $ this ; } switch ( strtoupper ( $ this -> tagName ) ) { case 'META' : return $ this -> getAttribute ( 'content' ) ; case 'AUDIO' : case 'EMBED' : case 'IFRAME' : case 'IMG' : case 'SOURCE' : case 'TRACK' : case 'VIDEO' : return $ this -> getAttribute ( 'src' ) ; case 'A' : case 'AREA' : case 'LINK' : return $ this -> getAttribute ( 'href' ) ; case 'OBJECT' : return $ this -> getAttribute ( 'data' ) ; case 'DATA' : return $ this -> getAttribute ( 'value' ) ; case 'TIME' : $ datetime = $ this -> getAttribute ( 'datetime' ) ; if ( ! empty ( $ datetime ) ) return $ datetime ; default : return $ this -> textContent ; } }
Retrieve the element s value determined by the element type .
58,754
protected function traverse ( $ node , & $ toTraverse , & $ props , $ root ) { foreach ( $ toTraverse as $ i => $ elem ) { if ( $ elem -> isSameNode ( $ node ) ) { unset ( $ toTraverse [ $ i ] ) ; } } if ( ! $ root -> isSameNode ( $ node ) ) { $ names = $ node -> itemProp ( ) ; if ( count ( $ names ) ) { $ props [ ] = $ node ; } if ( $ node -> itemScope ( ) ) { return ; } } if ( isset ( $ node ) ) { $ children = $ this -> ownerDocument -> xpath ( ) -> query ( $ node -> getNodePath ( ) . '/*' ) ; foreach ( $ children as $ child ) { $ this -> traverse ( $ child , $ toTraverse , $ props , $ root ) ; } } }
Traverse the tree .
58,755
protected function handle ( $ result , $ httpCode ) { $ codes = explode ( "," , static :: ACCEPTED_CODES ) ; if ( ! in_array ( $ httpCode , $ codes ) ) { if ( $ error = json_decode ( $ result , true ) ) { $ error = $ error [ 'error' ] ; } else { $ error = $ result ; } throw new \ Clickatell \ ClickatellException ( $ error ) ; } else { return json_decode ( $ result , true ) ; } }
Handle CURL response from Clickatell APIs
58,756
protected function curl ( $ uri , $ data ) { $ data = $ data ? ( array ) $ data : $ data ; $ headers = [ 'Content-Type: application/json' , 'Accept: application/json' , 'Authorization: ' . $ this -> apiToken ] ; $ endpoint = static :: API_URL . "/" . $ uri ; $ curlInfo = curl_version ( ) ; $ ch = curl_init ( ) ; curl_setopt ( $ ch , CURLOPT_URL , $ endpoint ) ; curl_setopt ( $ ch , CURLOPT_HEADER , 0 ) ; curl_setopt ( $ ch , CURLOPT_RETURNTRANSFER , true ) ; curl_setopt ( $ ch , CURLOPT_HTTPHEADER , $ headers ) ; curl_setopt ( $ ch , CURLOPT_USERAGENT , static :: AGENT . ' curl/' . $ curlInfo [ 'version' ] . ' PHP/' . phpversion ( ) ) ; if ( $ data ) { curl_setopt ( $ ch , CURLOPT_POST , 1 ) ; curl_setopt ( $ ch , CURLOPT_POSTFIELDS , json_encode ( $ data ) ) ; } $ result = curl_exec ( $ ch ) ; $ httpCode = curl_getinfo ( $ ch , CURLINFO_HTTP_CODE ) ; return $ this -> handle ( $ result , $ httpCode ) ; }
Abstract CURL usage .
58,757
protected function getErrorMessage ( $ name , $ params = [ ] ) { if ( $ this -> simpleErrorMessage ) { $ name = 'message' ; } if ( isset ( $ this -> $ name ) ) { return [ $ this -> $ name , $ params ] ; } $ this -> $ name = Yii :: t ( 'kdn/yii2/validators/domain' , $ this -> getDefaultErrorMessages ( ) [ $ name ] ) ; return [ $ this -> $ name , $ params ] ; }
Get error message by name .
58,758
protected function getDefaultErrorMessages ( ) { $ messages = [ 'message' => '{attribute} is invalid.' , 'messageDNS' => 'DNS record corresponding to {attribute} not found.' , 'messageLabelNumberMin' => '{attribute} should consist of at least {labelNumberMin, number} labels separated by ' . '{labelNumberMin, plural, =2{dot} other{dots}}.' , 'messageLabelTooShort' => 'Each label of {attribute} should contain at least 1 character.' , 'messageNotString' => '{attribute} must be a string.' , 'messageTooShort' => '{attribute} should contain at least 1 character.' , ] ; if ( $ this -> enableIDN ) { $ messages [ 'messageLabelStartEnd' ] = 'Each label of {attribute} should start and end with letter or number.' . ' The rightmost label of {attribute} should start with letter.' ; $ messages [ 'messageLabelTooLong' ] = 'Label of {attribute} is too long.' ; $ messages [ 'messageTooLong' ] = '{attribute} is too long.' ; if ( $ this -> allowUnderscore ) { $ messages [ 'messageInvalidCharacter' ] = 'Each label of {attribute} can consist of only letters, numbers, hyphens and underscores.' ; } else { $ messages [ 'messageInvalidCharacter' ] = 'Each label of {attribute} can consist of only letters, numbers and hyphens.' ; } } else { $ messages [ 'messageLabelStartEnd' ] = 'Each label of {attribute} should start and end with latin letter or number.' . ' The rightmost label of {attribute} should start with latin letter.' ; $ messages [ 'messageLabelTooLong' ] = 'Each label of {attribute} should contain at most 63 characters.' ; $ messages [ 'messageTooLong' ] = '{attribute} should contain at most 253 characters.' ; if ( $ this -> allowUnderscore ) { $ messages [ 'messageInvalidCharacter' ] = 'Each label of {attribute} can consist of only latin letters, numbers, hyphens and underscores.' ; } else { $ messages [ 'messageInvalidCharacter' ] = 'Each label of {attribute} can consist of only latin letters, numbers and hyphens.' ; } } return $ messages ; }
Get default error messages .
58,759
public function dir ( ) { $ this -> _name = sys_get_temp_dir ( ) . DIRECTORY_SEPARATOR . uniqid ( $ this -> _prefix ) ; if ( ! mkdir ( $ this -> _name ) ) { throw new \ Exception ( 'Cannot create temporary directory' ) ; } return $ this ; }
Creates temporary directory
58,760
public function product ( $ orderLineHandle , $ product ) { $ products = new Product ( $ this -> client_raw ) ; $ productHandle = $ products -> getHandle ( $ product ) ; $ this -> client -> OrderLine_SetProduct ( array ( 'orderLineHandle' => $ orderLineHandle , 'valueHandle' => $ productHandle ) ) ; return true ; }
Set Order Line product by product number
58,761
public function add ( array $ data ) { $ defaults = array ( "description" => null , "price" => null , "discount" => null , "qty" => 1 , "unit" => null ) ; $ merged = array_merge ( $ defaults , $ data ) ; $ line = $ this -> create ( $ this -> quotationHandle ) ; if ( isset ( $ merged [ 'product' ] ) ) { $ this -> product ( $ line , $ merged [ 'product' ] ) ; unset ( $ merged [ 'product' ] ) ; } foreach ( $ merged as $ name => $ value ) { if ( is_null ( $ value ) ) continue ; switch ( $ name ) { case 'description' : $ this -> description ( $ line , $ value ) ; break ; case 'price' : $ this -> price ( $ line , $ value ) ; break ; case 'discount' : $ this -> discount ( $ line , $ value ) ; break ; case 'qty' : $ this -> qty ( $ line , $ value ) ; break ; case 'unit' : $ this -> unit ( $ line , $ value ) ; break ; } } }
Create new Quotation line from data
58,762
public function product ( $ QuotationLineHandle , $ product ) { $ products = new Product ( $ this -> client_raw ) ; $ productHandle = $ products -> getHandle ( $ product ) ; $ this -> client -> QuotationLine_SetProduct ( array ( 'quotationLineHandle' => $ QuotationLineHandle , 'valueHandle' => $ productHandle ) ) ; return true ; }
Set Quotation Line product by product number
58,763
public function all ( ) { $ handles = $ this -> client -> DebtorContact_GetAll ( ) -> DebtorContact_GetAllResult -> DebtorContactHandle ; return $ this -> getArrayFromHandles ( $ handles ) ; }
Get all Contacts
58,764
public function search ( $ name ) { $ handles = $ this -> client -> DebtorContact_FindByName ( array ( 'name' => $ name ) ) -> DebtorContact_FindByNameResult -> DebtorContactHandle ; return $ this -> getArrayFromHandles ( $ handles ) ; }
Search contact by full name
58,765
public function update ( array $ data , $ id ) { if ( ! is_integer ( $ id ) ) throw new Exception ( "ID must be a integer" ) ; $ handle = array ( 'Id' => $ id ) ; foreach ( $ data as $ field => $ value ) { switch ( strtolower ( $ field ) ) { case 'name' : $ this -> client -> debtorContact_SetName ( array ( 'debtorContactHandle' => $ handle , 'value' => $ value ) ) ; break ; case 'email' : $ this -> client -> debtorContact_SetEmail ( array ( 'debtorContactHandle' => $ handle , 'value' => $ value ) ) ; break ; case 'phone' : $ this -> client -> DebtorContact_SetTelephoneNumber ( array ( 'debtorContactHandle' => $ handle , 'value' => $ value ) ) ; break ; case 'invoice' : $ this -> client -> debtorContact_SetIsToReceiveEmailCopyOfInvoice ( array ( 'debtorContactHandle' => $ handle , 'value' => ! ! $ value ) ) ; break ; case 'order' : $ this -> client -> debtorContact_SetIsToReceiveEmailCopyOfOrder ( array ( 'debtorContactHandle' => $ handle , 'value' => ! ! $ value ) ) ; break ; case 'comment' : $ this -> client -> debtorContact_SetComments ( array ( 'debtorContactHandle' => $ handle , 'value' => $ value ) ) ; break ; } } return $ this -> getArrayFromHandles ( $ handle ) ; }
Update an existion Contact by Contact ID
58,766
public function create ( array $ data , $ debtor ) { $ debtors = new Debtor ( $ this -> client_raw ) ; $ debtorHandle = $ debtors -> getHandle ( $ debtor ) ; $ id = $ this -> client -> DebtorContact_Create ( array ( 'debtorHandle' => $ debtorHandle , 'name' => $ data [ 'name' ] ) ) -> DebtorContact_CreateResult ; return $ this -> update ( $ id -> Id , $ data ) ; }
Create a new Contact from data array
58,767
public function delete ( $ id ) { $ data = $ this -> findById ( $ id ) ; $ this -> client -> DebtorContact_Delete ( array ( "debtorContactHandle" => $ data -> Handle ) ) ; return true ; }
Delete a Contact by ID
58,768
public function execute ( Arguments $ args , ConsoleIo $ io ) { try { $ count = $ this -> ThumbManager -> clearAll ( ) ; } catch ( Exception $ e ) { $ io -> err ( __d ( 'thumber' , 'Error deleting thumbnails' ) ) ; $ this -> abort ( ) ; } $ io -> verbose ( __d ( 'thumber' , 'Thumbnails deleted: {0}' , $ count ) ) ; return null ; }
Clears all thumbnails
58,769
protected function createAclFromConfig ( array $ config ) { $ aclConfig = [ ] ; $ denyByDefault = false ; if ( array_key_exists ( 'deny_by_default' , $ config ) ) { $ denyByDefault = $ aclConfig [ 'deny_by_default' ] = ( bool ) $ config [ 'deny_by_default' ] ; unset ( $ config [ 'deny_by_default' ] ) ; } foreach ( $ config as $ controllerService => $ privileges ) { $ this -> createAclConfigFromPrivileges ( $ controllerService , $ privileges , $ aclConfig , $ denyByDefault ) ; } return AclFactory :: factory ( $ aclConfig ) ; }
Generate the ACL instance based on the zf - mvc - auth authorization configuration
58,770
protected function createAclConfigFromPrivileges ( $ controllerService , array $ privileges , & $ aclConfig , $ denyByDefault ) { $ controllerService = strtr ( $ controllerService , '-' , '\\' ) ; if ( isset ( $ privileges [ 'actions' ] ) ) { foreach ( $ privileges [ 'actions' ] as $ action => $ methods ) { $ action = lcfirst ( $ action ) ; $ aclConfig [ ] = [ 'resource' => sprintf ( '%s::%s' , $ controllerService , $ action ) , 'privileges' => $ this -> createPrivilegesFromMethods ( $ methods , $ denyByDefault ) , ] ; } } if ( isset ( $ privileges [ 'collection' ] ) ) { $ aclConfig [ ] = [ 'resource' => sprintf ( '%s::collection' , $ controllerService ) , 'privileges' => $ this -> createPrivilegesFromMethods ( $ privileges [ 'collection' ] , $ denyByDefault ) , ] ; } if ( isset ( $ privileges [ 'entity' ] ) ) { $ aclConfig [ ] = [ 'resource' => sprintf ( '%s::entity' , $ controllerService ) , 'privileges' => $ this -> createPrivilegesFromMethods ( $ privileges [ 'entity' ] , $ denyByDefault ) , ] ; } }
Creates ACL configuration based on the privileges configured
58,771
protected function createPrivilegesFromMethods ( array $ methods , $ denyByDefault ) { $ privileges = [ ] ; if ( isset ( $ methods [ 'default' ] ) && $ methods [ 'default' ] ) { $ privileges = $ this -> httpMethods ; unset ( $ methods [ 'default' ] ) ; } foreach ( $ methods as $ method => $ flag ) { if ( ( $ denyByDefault && $ flag ) || ( ! $ denyByDefault && ! $ flag ) ) { if ( isset ( $ privileges [ $ method ] ) ) { unset ( $ privileges [ $ method ] ) ; } continue ; } $ privileges [ $ method ] = true ; } if ( empty ( $ privileges ) ) { return null ; } return array_keys ( $ privileges ) ; }
Create the list of HTTP methods defining privileges
58,772
private function getConfigFromContainer ( ContainerInterface $ container ) { if ( ! $ container -> has ( 'config' ) ) { return [ ] ; } $ config = $ container -> get ( 'config' ) ; if ( ! isset ( $ config [ 'zf-mvc-auth' ] [ 'authorization' ] ) ) { return [ ] ; } return $ config [ 'zf-mvc-auth' ] [ 'authorization' ] ; }
Retrieve configuration from the container .
58,773
public static function clearTextConcat ( $ value ) { if ( is_string ( $ value ) ) { return trim ( preg_replace ( '/\s+/s' , ' ' , $ value ) ) ; } if ( is_array ( $ value ) ) { $ result = [ ] ; foreach ( $ value as $ val ) { $ result [ ] = self :: clearTextConcat ( $ val ) ; } return implode ( ' ' , array_filter ( $ result , 'strlen' ) ) ; } return null ; }
Recursive clears all text in array
58,774
public static function factory ( array $ config ) { $ denyByDefault = false ; if ( array_key_exists ( 'deny_by_default' , $ config ) ) { $ denyByDefault = ( bool ) $ config [ 'deny_by_default' ] ; unset ( $ config [ 'deny_by_default' ] ) ; } $ acl = new AclAuthorization ; $ acl -> addRole ( 'guest' ) ; $ acl -> allow ( ) ; $ grant = 'deny' ; if ( $ denyByDefault ) { $ acl -> deny ( 'guest' , null , null ) ; $ grant = 'allow' ; } if ( ! empty ( $ config ) ) { return self :: injectGrants ( $ acl , $ grant , $ config ) ; } return $ acl ; }
Create and return an AclAuthorization instance populated with provided privileges .
58,775
private static function injectGrants ( AclAuthorization $ acl , $ grantType , array $ rules ) { foreach ( $ rules as $ set ) { if ( ! is_array ( $ set ) || ! isset ( $ set [ 'resource' ] ) ) { continue ; } self :: injectGrant ( $ acl , $ grantType , $ set ) ; } return $ acl ; }
Inject the ACL with the grants specified in the collection of rules .
58,776
private static function injectGrant ( AclAuthorization $ acl , $ grantType , array $ ruleSet ) { $ resource = $ ruleSet [ 'resource' ] ; $ acl -> addResource ( $ ruleSet [ 'resource' ] ) ; $ privileges = isset ( $ ruleSet [ 'privileges' ] ) ? $ ruleSet [ 'privileges' ] : null ; if ( null === $ privileges ) { return ; } $ acl -> $ grantType ( 'guest' , $ resource , $ privileges ) ; }
Inject the ACL with the grant specified by a single rule set .
58,777
public function setOptions ( array $ options ) { foreach ( $ options as $ k => $ v ) { $ this -> _options [ $ k ] = $ v ; } return $ this ; }
Setter for CURL Options Warning! setoptions clears all previously setted options and post data
58,778
public function setPostData ( $ postData ) { if ( is_null ( $ postData ) ) { unset ( $ this -> _options [ CURLOPT_POST ] ) ; unset ( $ this -> _options [ CURLOPT_POSTFIELDS ] ) ; } else { $ this -> _options [ CURLOPT_POST ] = true ; $ this -> _options [ CURLOPT_POSTFIELDS ] = $ postData ; } return $ this ; }
Adds post data to options
58,779
protected static function curl_multi_exec ( $ urls ) { $ nodes = [ ] ; foreach ( $ urls as $ url ) { $ ch = curl_init ( ) ; $ nodes [ ] = [ 'ch' => $ ch , 'url' => $ url ] ; curl_setopt_array ( $ ch , $ url -> getOptions ( ) ) ; } $ mh = curl_multi_init ( ) ; foreach ( $ nodes as $ node ) { curl_multi_add_handle ( $ mh , $ node [ 'ch' ] ) ; } do { curl_multi_exec ( $ mh , $ running ) ; curl_multi_select ( $ mh ) ; } while ( $ running > 0 ) ; foreach ( $ nodes as $ node ) { $ url = $ node [ 'url' ] ; $ ch = $ node [ 'ch' ] ; $ url -> _content = curl_multi_getcontent ( $ ch ) ; $ url -> _errorCode = curl_errno ( $ ch ) ; if ( ! empty ( $ url -> _errorCode ) ) { $ url -> _errorMessage = curl_error ( $ ch ) ; } $ url -> _info = curl_getinfo ( $ ch ) ; } foreach ( $ nodes as $ node ) { curl_multi_remove_handle ( $ mh , $ node [ 'ch' ] ) ; } curl_multi_close ( $ mh ) ; }
Executes parallels curls
58,780
public static function getIpAddress ( ) { if ( isset ( $ _SERVER [ 'HTTP_CLIENT_IP' ] ) && self :: validateIp ( $ _SERVER [ 'HTTP_CLIENT_IP' ] ) ) { return $ _SERVER [ 'HTTP_CLIENT_IP' ] ; } if ( isset ( $ _SERVER [ 'HTTP_X_FORWARDED_FOR' ] ) ) { if ( strpos ( $ _SERVER [ 'HTTP_X_FORWARDED_FOR' ] , ',' ) !== false ) { $ iplist = explode ( ',' , $ _SERVER [ 'HTTP_X_FORWARDED_FOR' ] ) ; foreach ( $ iplist as $ ip ) { if ( self :: validateIp ( $ ip ) ) { return $ ip ; } } } else { if ( self :: validateIp ( $ _SERVER [ 'HTTP_X_FORWARDED_FOR' ] ) ) { return $ _SERVER [ 'HTTP_X_FORWARDED_FOR' ] ; } } } if ( isset ( $ _SERVER [ 'HTTP_X_FORWARDED' ] ) && self :: validateIp ( $ _SERVER [ 'HTTP_X_FORWARDED' ] ) ) { return $ _SERVER [ 'HTTP_X_FORWARDED' ] ; } if ( isset ( $ _SERVER [ 'HTTP_X_CLUSTER_CLIENT_IP' ] ) && self :: validateIp ( $ _SERVER [ 'HTTP_X_CLUSTER_CLIENT_IP' ] ) ) { return $ _SERVER [ 'HTTP_X_CLUSTER_CLIENT_IP' ] ; } if ( isset ( $ _SERVER [ 'HTTP_FORWARDED_FOR' ] ) && self :: validateIp ( $ _SERVER [ 'HTTP_FORWARDED_FOR' ] ) ) { return $ _SERVER [ 'HTTP_FORWARDED_FOR' ] ; } if ( isset ( $ _SERVER [ 'HTTP_FORWARDED' ] ) && self :: validateIp ( $ _SERVER [ 'HTTP_FORWARDED' ] ) ) { return $ _SERVER [ 'HTTP_FORWARDED' ] ; } return isset ( $ _SERVER [ 'REMOTE_ADDR' ] ) ? $ _SERVER [ 'REMOTE_ADDR' ] : 'unknown' ; }
Retrieves the best guess of the client s actual IP address . Takes into account numerous HTTP proxy headers due to variations in how different ISPs handle IP addresses in headers between hops .
58,781
public function getDependencyConfig ( ) { return [ 'aliases' => [ MvcAuthAuthorizationInterface :: class => Authorization \ AclAuthorization :: class , ] , 'factories' => [ Authorization \ AuthorizationListener :: class => Authorization \ AuthorizationListenerFactory :: class , Authorization \ AclAuthorization :: class => Factory \ AclAuthorizationFactory :: class , ] , ] ; }
Provide dependency configuration for this component .
58,782
protected function _clear ( $ filenames ) { $ count = 0 ; foreach ( $ filenames as $ filename ) { if ( ! ( new File ( $ this -> getPath ( $ filename ) ) ) -> delete ( ) ) { return false ; } $ count ++ ; } return $ count ; }
Internal method to clear thumbnails
58,783
protected function _find ( $ regexpPattern = null , $ sort = false ) { $ regexpPattern = $ regexpPattern ? : sprintf ( '[\d\w]{32}_[\d\w]{32}\.(%s)' , implode ( '|' , self :: $ supportedFormats ) ) ; return ( new Folder ( $ this -> getPath ( ) ) ) -> find ( $ regexpPattern , $ sort ) ; }
Internal method to find thumbnails
58,784
public function get ( $ path , $ sort = false ) { $ regexpPattern = sprintf ( '%s_[\d\w]{32}\.(%s)' , md5 ( $ this -> resolveFilePath ( $ path ) ) , implode ( '|' , self :: $ supportedFormats ) ) ; return $ this -> _find ( $ regexpPattern , $ sort ) ; }
Gets all thumbnails that have been generated from an image path
58,785
protected function getPath ( $ file = null ) { $ path = Configure :: readOrFail ( 'Thumber.target' ) ; return $ file ? $ path . DS . $ file : $ path ; }
Gets a path for a thumbnail .
58,786
protected function resolveFilePath ( $ path ) { if ( is_url ( $ path ) ) { return $ path ; } if ( ! Folder :: isAbsolute ( $ path ) ) { $ pluginSplit = pluginSplit ( $ path ) ; $ path = WWW_ROOT . 'img' . DS . $ path ; if ( ! empty ( $ pluginSplit [ 0 ] ) && in_array ( $ pluginSplit [ 0 ] , CorePlugin :: loaded ( ) ) ) { $ path = CorePlugin :: path ( $ pluginSplit [ 0 ] ) . 'webroot' . DS . 'img' . DS . $ pluginSplit [ 1 ] ; } } is_readable_or_fail ( $ path ) ; return $ path ; }
Internal method to resolve a partial path returning a full path
58,787
public function obj ( ) { $ result = new \ stdClass ( ) ; $ result -> items = array ( ) ; foreach ( $ this -> dom -> getItems ( ) as $ item ) { array_push ( $ result -> items , $ this -> getObject ( $ item , array ( ) ) ) ; } return $ result ; }
Retrieve microdata as a PHP object .
58,788
protected function getObject ( $ item , $ memory ) { $ result = new \ stdClass ( ) ; $ result -> properties = array ( ) ; if ( $ itemtype = $ item -> itemType ( ) ) { $ result -> type = $ itemtype ; } if ( $ itemid = $ item -> itemid ( ) ) { $ result -> id = $ itemid ; } foreach ( $ item -> properties ( ) as $ elem ) { if ( $ elem -> itemScope ( ) ) { foreach ( $ memory as $ memory_item ) { if ( $ memory_item === $ elem ) { $ value = 'ERROR' ; } } if ( ! isset ( $ value ) ) { $ memory [ ] = $ item ; $ value = $ this -> getObject ( $ elem , $ memory ) ; array_pop ( $ memory ) ; } } else { $ value = $ elem -> itemValue ( ) ; } foreach ( $ elem -> itemProp ( ) as $ prop ) { $ result -> properties [ $ prop ] [ ] = $ value ; } $ value = NULL ; } return $ result ; }
Helper function .
58,789
protected function registerCalculator ( ) { $ this -> app -> singleton ( TextSizeCalculatorInterface :: class , function ( ) { $ path = __DIR__ . '/../resources/fonts/DejaVuSans.ttf' ; return new GDTextSizeCalculator ( realpath ( $ path ) ? : $ path ) ; } ) ; $ this -> app -> singleton ( 'badger.calculator' , TextSizeCalculatorInterface :: class ) ; }
Register the calculator class .
58,790
protected function registerBadger ( ) { $ this -> app -> singleton ( Badger :: class , function ( Container $ app ) { $ calculator = $ app -> make ( 'badger.calculator' ) ; $ path = realpath ( $ raw = __DIR__ . '/../resources/templates' ) ? : $ raw ; $ renderers = [ new PlasticRender ( $ calculator , $ path ) , new PlasticFlatRender ( $ calculator , $ path ) , new FlatSquareRender ( $ calculator , $ path ) , new SocialRender ( $ calculator , $ path ) , ] ; return new Badger ( $ renderers ) ; } ) ; $ this -> app -> singleton ( 'badger' , Badger :: class ) ; }
Register the badger class .
58,791
public function addExecutor ( ExecutorInterface $ executor ) { $ action = $ executor -> getName ( ) ; if ( $ this -> hasExecutor ( $ action ) ) { throw new \ InvalidArgumentException ( sprintf ( 'There is already an executor registered for action "%s".' , $ action ) ) ; } $ this -> executors [ $ action ] = $ executor ; }
Add an executor .
58,792
public function getExecutor ( $ action ) { if ( ! $ this -> hasExecutor ( $ action ) ) { throw new \ OutOfBoundsException ( sprintf ( 'There is no executor registered for action "%s".' , $ action ) ) ; } return $ this -> executors [ $ action ] ; }
Returns a registered executor for given action .
58,793
public function addForObject ( $ action , $ object , $ delay = null , $ priority = null , $ ttr = null ) { $ executor = $ this -> getExecutor ( $ action ) ; if ( ! $ executor instanceof ObjectPayloadInterface ) { throw new \ LogicException ( sprintf ( 'The executor for action "%s" cannot be used for objects. Implement the ObjectPayloadInterface in class "%s" to enable this.' , $ action , get_class ( $ executor ) ) ) ; } if ( ! $ executor -> supportsObject ( $ object ) ) { throw new \ InvalidArgumentException ( sprintf ( 'The executor for action "%s" does not support %s objects' , $ action , get_class ( $ object ) ) ) ; } $ payload = $ executor -> getObjectPayload ( $ object ) ; return $ this -> add ( $ action , $ payload , $ delay , $ priority , $ ttr ) ; }
Adds a job to the queue for an object .
58,794
public function reschedule ( Job $ job , \ DateTime $ date , $ priority = PheanstalkInterface :: DEFAULT_PRIORITY ) { if ( $ date < new \ DateTime ( ) ) { throw new \ InvalidArgumentException ( sprintf ( 'You cannot reschedule a job in the past (got %s, and the current date is %s)' , $ date -> format ( DATE_ISO8601 ) , date ( DATE_ISO8601 ) ) ) ; } $ this -> pheanstalk -> release ( $ job , $ priority , $ date -> getTimestamp ( ) - time ( ) ) ; $ this -> logJob ( $ job -> getId ( ) , sprintf ( 'Rescheduled job for %s' , $ date -> format ( 'Y-m-d H:i:s' ) ) ) ; }
Reschedules a job .
58,795
public function delete ( Job $ job ) { $ this -> pheanstalk -> delete ( $ job ) ; $ this -> logJob ( $ job -> getId ( ) , 'Job deleted' ) ; }
Permanently deletes a job .
58,796
public function execute ( $ action , array $ payload ) { $ executor = $ this -> getExecutor ( $ action ) ; $ event = new ExecutionEvent ( $ executor , $ action , $ payload ) ; $ this -> dispatcher -> dispatch ( WorkerEvents :: PRE_EXECUTE_ACTION , $ event ) ; try { $ resolver = $ this -> getPayloadResolver ( $ executor ) ; $ payload = $ resolver -> resolve ( $ event -> getPayload ( ) ) ; } catch ( ExceptionInterface $ exception ) { $ this -> logger -> error ( sprintf ( 'Payload %s for "%s" is invalid: %s' , json_encode ( $ payload , JSON_UNESCAPED_SLASHES ) , $ action , $ exception -> getMessage ( ) ) ) ; return false ; } $ result = $ executor -> execute ( $ payload ) ; $ event -> setResult ( $ result ) ; $ this -> dispatcher -> dispatch ( WorkerEvents :: POST_EXECUTE_ACTION , $ event ) ; return $ event -> getResult ( ) ; }
Executes an action with a specific payload .
58,797
protected function getPayloadResolver ( ExecutorInterface $ executor ) { $ key = $ executor -> getName ( ) ; if ( ! array_key_exists ( $ key , $ this -> resolvers ) ) { $ resolver = new OptionsResolver ( ) ; $ executor -> configurePayload ( $ resolver ) ; $ this -> resolvers [ $ key ] = $ resolver ; } return $ this -> resolvers [ $ key ] ; }
Returns a cached version of the payload resolver for an executor .
58,798
protected function instantiateLocator ( ) { if ( empty ( $ this -> config [ 'locator class' ] ) ) { $ this -> locator = new Locators ; return ; } $ class = $ this -> config [ 'locator class' ] ; $ this -> locator = new $ class ; }
Function to instantiate the Locator Class In case of a custom Template path to the custom Template Locator could be passed in Acceptance . suite . yml file
58,799
public function doAdministratorLogin ( $ user = null , $ password = null , $ useSnapshot = true ) { if ( is_null ( $ user ) ) { $ user = $ this -> config [ 'username' ] ; } if ( is_null ( $ password ) ) { $ password = $ this -> config [ 'password' ] ; } $ this -> debug ( 'I open Joomla Administrator Login Page' ) ; $ this -> amOnPage ( $ this -> locator -> adminLoginPageUrl ) ; if ( $ useSnapshot && $ this -> loadSessionSnapshot ( $ user ) ) { return ; } $ this -> waitForElement ( $ this -> locator -> adminLoginUserName , TIMEOUT ) ; $ this -> debug ( 'Fill Username Text Field' ) ; $ this -> fillField ( $ this -> locator -> adminLoginUserName , $ user ) ; $ this -> debug ( 'Fill Password Text Field' ) ; $ this -> fillField ( $ this -> locator -> adminLoginPassword , $ password ) ; $ this -> debug ( 'I click Login button' ) ; $ this -> click ( $ this -> locator -> adminLoginButton ) ; $ this -> debug ( 'I wait to see Administrator Control Panel' ) ; $ this -> waitForText ( $ this -> locator -> adminControlPanelText , 4 , $ this -> locator -> controlPanelLocator ) ; if ( $ useSnapshot ) { $ this -> saveSessionSnapshot ( $ user ) ; } }
Function to Do Admin Login In Joomla!