idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
27,000
private function getRoot ( NumberBase $ source , NumberBase $ target ) { if ( $ source -> hasStringConflict ( ) || $ target -> hasStringConflict ( ) ) { throw new InvalidNumberBaseException ( 'Number bases do not support string presentation' ) ; } $ root = $ source -> findCommonRadixRoot ( $ target ) ; if ( $ root === false ) { throw new InvalidNumberBaseException ( 'No common root exists between number bases' ) ; } return $ root ; }
Determines the common root for the number bases .
27,001
private function buildConversionTable ( ) { if ( $ this -> source -> getRadix ( ) > $ this -> target -> getRadix ( ) ) { return $ this -> createTable ( $ this -> source -> getDigitList ( ) , $ this -> target -> getDigitList ( ) ) ; } return array_flip ( $ this -> createTable ( $ this -> target -> getDigitList ( ) , $ this -> source -> getDigitList ( ) ) ) ; }
Creates string replacement table between source base and target base .
27,002
private function createTable ( $ source , $ target ) { $ last = count ( $ target ) - 1 ; $ size = ( int ) log ( count ( $ source ) , count ( $ target ) ) ; $ number = array_fill ( 0 , $ size , $ target [ 0 ] ) ; $ next = array_fill ( 0 , $ size , 0 ) ; $ limit = count ( $ source ) ; $ table = [ $ source [ 0 ] => implode ( '' , $ number ) ] ; for ( $ i = 1 ; $ i < $ limit ; $ i ++ ) { for ( $ j = $ size - 1 ; $ next [ $ j ] === $ last ; $ j -- ) { $ number [ $ j ] = $ target [ 0 ] ; $ next [ $ j ] = 0 ; } $ number [ $ j ] = $ target [ ++ $ next [ $ j ] ] ; $ table [ $ source [ $ i ] ] = implode ( '' , $ number ) ; } return $ table ; }
Creates a conversion table between two lists of digits .
27,003
private function convert ( array $ number , $ fractions = false ) { if ( ! isset ( $ this -> conversionTable ) ) { return $ this -> targetConverter -> replace ( $ this -> sourceConverter -> replace ( $ number , $ fractions ) , $ fractions ) ; } return $ this -> replace ( $ number , $ fractions ) ; }
Converts the digits from source base to target base .
27,004
private function replace ( array $ number , $ fractions = false ) { return $ this -> zeroTrim ( $ this -> target -> splitString ( strtr ( implode ( '' , $ this -> zeroPad ( $ this -> source -> canonizeDigits ( $ number ) , $ fractions ) ) , $ this -> conversionTable ) ) , $ fractions ) ; }
Replace digits using string replacement .
27,005
private function zeroPad ( array $ number , $ right ) { $ log = ( int ) log ( $ this -> target -> getRadix ( ) , $ this -> source -> getRadix ( ) ) ; if ( $ log > 1 && count ( $ number ) % $ log ) { $ pad = count ( $ number ) + ( $ log - count ( $ number ) % $ log ) ; $ number = array_pad ( $ number , $ right ? $ pad : - $ pad , $ this -> source -> getDigit ( 0 ) ) ; } return $ number ; }
Pads the digits to correct count for string replacement .
27,006
private function zeroTrim ( array $ number , $ right ) { $ zero = $ this -> target -> getDigit ( 0 ) ; while ( ( $ right ? end ( $ number ) : reset ( $ number ) ) === $ zero ) { unset ( $ number [ key ( $ number ) ] ) ; } return empty ( $ number ) ? [ $ zero ] : array_values ( $ number ) ; }
Trims extraneous zeroes from the digit list .
27,007
public function initialize ( ) { $ modules = $ this -> loader -> getModules ( ) ; if ( empty ( $ modules ) ) { throw new RuntimeException ( 'No modules found. Initialization halted' ) ; } else { $ this -> loadAll ( $ modules ) ; $ this -> modules = $ modules ; $ this -> validateCoreModuleNames ( ) ; } }
Initializes the module manager
27,008
private function getCoreBag ( ) { static $ coreBag = null ; if ( is_null ( $ coreBag ) ) { $ coreBag = new CoreBag ( $ this -> getLoadedModuleNames ( ) , $ this -> coreModules ) ; } return $ coreBag ; }
Returns core bag instance
27,009
private function validateCoreModuleNames ( ) { if ( ! empty ( $ this -> coreModules ) ) { $ coreBag = $ this -> getCoreBag ( ) ; if ( ! $ coreBag -> hasAllCoreModules ( ) ) { throw new LogicException ( sprintf ( 'The framework can not start without defined core modules: %s' , implode ( ', ' , $ coreBag -> getMissingCoreModules ( ) ) ) ) ; } } }
Validates core modules on demand
27,010
public function getModule ( $ name ) { if ( $ this -> isLoaded ( $ name ) ) { return $ this -> loaded [ $ name ] ; } else { return $ this -> loadModuleByName ( $ name ) ; } }
Returns module instance by its name
27,011
public function getUnloadedModules ( array $ modules ) { $ unloaded = array ( ) ; foreach ( $ modules as $ module ) { if ( ! $ this -> isLoaded ( $ module ) ) { array_push ( $ unloaded , $ module ) ; } } return $ unloaded ; }
Returns a collection of unloaded modules
27,012
private function prepareRoutes ( $ module , array $ routes ) { $ result = array ( ) ; foreach ( $ routes as $ uriTemplate => $ options ) { if ( isset ( $ options [ 'controller' ] ) ) { $ options [ 'controller' ] = sprintf ( '%s:%s' , $ this -> grabModuleName ( $ module ) , $ options [ 'controller' ] ) ; } $ result [ $ uriTemplate ] = $ options ; } return $ result ; }
Prepends module name to each route
27,013
private function loadModuleByName ( $ name ) { if ( ! $ this -> nameValid ( $ name ) ) { throw new LogicException ( sprintf ( 'Invalid module name "%s" is being processed. Module name must start from a capital letter and contain only alphabetic characters' , $ name ) ) ; } $ moduleNamespace = sprintf ( '%s\%s' , $ name , self :: MODULE_CONFIG_FILE ) ; if ( ! class_exists ( $ moduleNamespace ) ) { return false ; } $ pathProvider = new PathProvider ( $ this -> appConfig -> getModulesDir ( ) , $ name ) ; $ sl = new ServiceLocator ( ) ; $ sl -> registerArray ( $ this -> services ) ; $ module = new $ moduleNamespace ( $ this , $ sl , $ this -> appConfig , $ pathProvider , $ name ) ; if ( method_exists ( $ module , 'getRoutes' ) ) { $ this -> appendRoutes ( $ this -> prepareRoutes ( $ moduleNamespace , $ module -> getRoutes ( ) ) ) ; } $ this -> loaded [ $ name ] = $ module ; return $ module ; }
Loads a module by its name
27,014
public function removeFromCacheDir ( $ module ) { $ path = $ this -> appConfig -> getModuleCacheDir ( $ module ) ; return $ this -> performRemoval ( $ path ) ; }
Removes module data from cache directory
27,015
public function removeFromUploadsDir ( $ module ) { $ path = $ this -> appConfig -> getModuleUploadsDir ( $ module ) ; return $ this -> performRemoval ( $ path ) ; }
Removes module data from uploading directory
27,016
public function removeFromFileSysem ( $ module ) { if ( $ this -> isCoreModule ( $ module ) ) { throw new LogicException ( sprintf ( 'Trying to remove core module "%s". This is not allowed by design' , $ module ) ) ; } $ path = sprintf ( '%s/%s' , $ this -> appConfig -> getModulesDir ( ) , $ module ) ; return $ this -> performRemoval ( $ path ) ; }
Removes a module from file system
27,017
public function loadAllTranslations ( $ language ) { foreach ( $ this -> loaded as $ module ) { $ this -> loadModuleTranslation ( $ module , $ language ) ; } }
Loads module translations
27,018
private function loadModuleTranslation ( AbstractModule $ module , $ language ) { if ( method_exists ( $ module , 'getTranslations' ) ) { $ translations = $ module -> getTranslations ( $ language ) ; if ( is_array ( $ translations ) ) { foreach ( $ translations as $ string => $ translation ) { $ this -> translations [ $ string ] = $ translation ; } return true ; } } return false ; }
Loads translation message for particular module
27,019
static public function createInDirectory ( $ dir ) { if ( ! is_dir ( $ dir ) || ! is_writable ( $ dir ) ) { throw new \ InvalidArgumentException ( "Directory to load build number from is not writable or does not exist: " . $ dir ) ; } $ buildFile = $ dir . DIRECTORY_SEPARATOR . "azure_build_number.yml" ; if ( ! file_exists ( $ buildFile ) ) { file_put_contents ( $ buildFile , "parameters:\n azure_build: 0" ) ; } return new self ( $ buildFile ) ; }
Create a new Build Number inside a directory .
27,020
protected function findUnit ( $ unitName , $ validUnits = null ) { $ units = $ this -> getUnits ( ) ; $ nunits = count ( $ units ) ; for ( $ i = 0 ; $ i < $ nunits ; $ i ++ ) { if ( ( $ validUnits != null ) && ( ! array_search ( $ units [ $ i ] [ 'name' ] , $ validUnits ) ) ) { continue ; } if ( ( $ units [ $ i ] [ 'name' ] == $ unitName ) || ( $ this -> aliasMatch ( $ units [ $ i ] , $ unitName ) ) ) { return $ i ; } } throw new \ InvalidArgumentException ( sprintf ( 'Invalid unit "%s" for type "%s"' , $ unitName , $ this -> getType ( ) ) ) ; }
Encuentra un nombre de unidad o un alias
27,021
public function invoke ( FilterableServiceInterface $ service , $ perPageCount , array $ parameters = array ( ) ) { $ page = $ this -> getPageNumber ( ) ; $ sort = $ this -> getSortingColumn ( ) ; $ desc = $ this -> getDesc ( ) ; $ records = $ service -> filter ( $ this -> getData ( ) , $ page , $ perPageCount , $ sort , $ desc , $ parameters ) ; if ( method_exists ( $ service , 'getPaginator' ) ) { $ paginator = $ service -> getPaginator ( ) ; if ( $ paginator instanceof PaginatorInterface ) { $ paginator -> setUrl ( $ this -> getPaginationUrl ( $ page , $ sort , $ desc ) ) ; } } return $ records ; }
Invokes a filter
27,022
private function getPaginationUrl ( $ page , $ sort , $ desc ) { $ placeholder = '(:var)' ; $ data = array ( self :: FILTER_PARAM_PAGE => $ placeholder , self :: FILTER_PARAM_DESC => $ desc , self :: FILTER_PARAM_SORT => $ sort ) ; return self :: createUrl ( array_merge ( $ this -> input , $ data ) , $ this -> route ) ; }
Returns pagination URL
27,023
private function getData ( ) { if ( isset ( $ this -> input [ self :: FILTER_PARAM_NS ] ) ) { $ data = $ this -> input [ self :: FILTER_PARAM_NS ] ; } else { $ data = array ( ) ; } return new InputDecorator ( $ data ) ; }
Returns data to be supplied to user - defined filtering method
27,024
protected function performSearch ( ) { $ filename = self :: CONFIG_FILENAME . '.yml' ; $ directories = array_filter ( explode ( '/' , getcwd ( ) ) ) ; $ count = count ( $ directories ) ; for ( $ offset = 0 ; $ offset < $ count ; ++ $ offset ) { $ next_path = '/' . implode ( '/' , array_slice ( $ directories , 0 , $ count - $ offset ) ) ; if ( file_exists ( "{$next_path}/{$filename}" ) ) { $ this -> projectXPath = "{$next_path}/{$filename}" ; break ; } } }
Perform search for the Project - X configuration .
27,025
public function decide ( GameState $ state ) : GameState { if ( ! $ state -> getNextPlayer ( ) -> equals ( $ this -> objectivePlayer ) ) { throw new BadMethodCallException ( 'It is not this players turn' ) ; } if ( empty ( $ state -> getPossibleMoves ( ) ) ) { throw new RuntimeException ( 'There are no possible moves' ) ; } $ rootNode = new DecisionNode ( $ this -> objectivePlayer , $ state , $ this -> maxDepth , NodeType :: MAX ( ) , AlphaBeta :: initial ( ) ) ; $ moveWithEvaluation = $ rootNode -> traverseGameTree ( ) ; $ this -> analytics = $ moveWithEvaluation -> analytics ; if ( $ moveWithEvaluation -> move === null ) { throw new LogicException ( 'Could not find move even though there are moves. Is the maxdepth parameter correct?' ) ; } return $ moveWithEvaluation -> move ; }
Evaluate possible decisions and take the best one
27,026
public function request ( $ method , $ url , array $ data = array ( ) , array $ extra = array ( ) ) { switch ( strtoupper ( $ method ) ) { case 'POST' : return $ this -> post ( $ url , $ data , $ extra ) ; case 'GET' : return $ this -> get ( $ url , $ data , $ extra ) ; case 'PATCH' : return $ this -> patch ( $ url , $ data , $ extra ) ; case 'HEAD' : return $ this -> head ( $ url , $ data , $ extra ) ; case 'PUT' : return $ this -> put ( $ url , $ data , $ extra ) ; case 'DELETE' : return $ this -> delete ( $ url , $ data , $ extra ) ; default : throw new UnexpectedValueException ( sprintf ( 'Unsupported or unknown HTTP method provided "%s"' , $ method ) ) ; } }
Performs a HTTP request
27,027
public function get ( $ url , array $ data = array ( ) , array $ extra = array ( ) ) { if ( ! empty ( $ data ) ) { $ url = $ url . '?' . http_build_query ( $ data ) ; } $ curl = new Curl ( array ( CURLOPT_URL => $ url , CURLOPT_RETURNTRANSFER => true , CURLOPT_HEADER => false ) , $ extra ) ; return $ curl -> exec ( ) ; }
Performs HTTP GET request
27,028
public function post ( $ url , $ data = array ( ) , array $ extra = array ( ) ) { $ curl = new Curl ( array ( CURLOPT_URL => $ url , CURLOPT_RETURNTRANSFER => true , CURLOPT_HEADER => false , CURLOPT_POST => count ( $ data ) , CURLOPT_POSTFIELDS => http_build_query ( $ data ) ) , $ extra ) ; return $ curl -> exec ( ) ; }
Performs HTTP POST request
27,029
public function delete ( $ url , array $ data = array ( ) , array $ extra = array ( ) ) { $ curl = new Curl ( array ( CURLOPT_URL => $ url , CURLOPT_RETURNTRANSFER => true , CURLOPT_CUSTOMREQUEST => 'DELETE' , CURLOPT_POSTFIELDS => http_build_query ( $ data ) ) , $ extra ) ; return $ curl -> exec ( ) ; }
Performs HTTP DELETE request
27,030
public function head ( $ url , array $ data = array ( ) , array $ extra = array ( ) ) { if ( ! empty ( $ data ) ) { $ url = $ url . '?' . http_build_query ( $ data ) ; } $ curl = new Curl ( array ( CURLOPT_URL => $ url , CURLOPT_RETURNTRANSFER => true , CURLOPT_NOBODY => true , CURLOPT_POSTFIELDS => http_build_query ( $ data ) ) , $ extra ) ; return $ curl -> exec ( ) ; }
Performs HTTP HEAD request
27,031
public static function loadJsonFromFile ( $ filePath ) { if ( ! file_exists ( $ filePath ) ) { throw new \ RuntimeException ( "File '{$filePath}' doesn't exist" ) ; } $ content = json_decode ( file_get_contents ( $ filePath ) ) ; if ( json_last_error ( ) !== JSON_ERROR_NONE ) { throw new JsonDecodeException ( sprintf ( 'Cannot decode JSON from file "%s" (error: %s)' , $ filePath , static :: lastJsonErrorMessage ( ) ) ) ; } return $ content ; }
Returns the JSON - decoded content of a file .
27,032
public static function getUniqueToken ( int $ length = 40 ) : string { $ token = '' ; $ codeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ; $ codeAlphabet .= 'abcdefghijklmnopqrstuvwxyz' ; $ codeAlphabet .= '0123456789' ; $ max = strlen ( $ codeAlphabet ) ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ token .= $ codeAlphabet [ self :: getSecureRandomInt ( 0 , $ max - 1 ) ] ; } return $ token ; }
Generate a unique token
27,033
public function decode ( ) { $ this -> data = str_replace ( ' ' , '+' , $ this -> data ) ; $ this -> data = base64_decode ( $ this -> data ) ; return $ this ; }
Base 64 encode the data ready for transit
27,034
private function simplexor ( ) { $ KeyList = array ( ) ; $ output = "" ; for ( $ i = 0 ; $ i < strlen ( $ this -> hash ) ; $ i ++ ) { $ KeyList [ $ i ] = ord ( substr ( $ this -> hash , $ i , 1 ) ) ; } for ( $ i = 0 ; $ i < strlen ( $ this -> data ) ; $ i ++ ) { $ output .= chr ( ord ( substr ( $ this -> data , $ i , 1 ) ) ^ ( $ KeyList [ $ i % strlen ( $ this -> hash ) ] ) ) ; } return $ output ; }
SimpleXor encryption algorithm
27,035
public function get ( ) { foreach ( $ this -> page_template_files as $ name => $ page_template_path ) { if ( isset ( $ this -> wrappers [ $ name ] ) ) { continue ; } if ( ! isset ( $ this -> wrapper_files [ $ name ] ) ) { continue ; } $ label = $ this -> _get_template_label ( $ page_template_path ) ; if ( ! $ label ) { continue ; } $ this -> wrappers [ $ name ] = translate ( $ label , wp_get_theme ( get_template ( ) ) -> get ( 'TextDomain' ) ) ; } return $ this -> wrappers ; }
Return available wrapper templates name
27,036
protected function _get_wrapper_files ( ) { $ wrapper_files = [ ] ; foreach ( WP_View_Controller \ Helper \ config ( 'layout' ) as $ wrapper_dir ) { foreach ( glob ( get_theme_file_path ( $ wrapper_dir . '/*' ) ) as $ wrapper_path ) { $ name = basename ( $ wrapper_path , '.php' ) ; if ( 'blank' === $ name || 'blank-fluid' === $ name ) { continue ; } if ( isset ( $ wrapper_files [ $ name ] ) ) { continue ; } $ wrapper_files [ $ name ] = $ wrapper_path ; } } return $ wrapper_files ; }
Return wrapper templates path
27,037
protected function _get_page_template_files ( ) { $ page_template_files = [ ] ; foreach ( WP_View_Controller \ Helper \ config ( 'page-templates' ) as $ page_template_dir ) { foreach ( glob ( get_theme_file_path ( $ page_template_dir . '/*' ) ) as $ page_template_path ) { $ name = basename ( $ page_template_path , '.php' ) ; if ( 'blank' === $ name || 'blank-fluid' === $ name ) { continue ; } if ( isset ( $ page_template_files [ $ name ] ) ) { continue ; } $ page_template_files [ $ name ] = $ page_template_path ; } } return $ page_template_files ; }
Return page templates path
27,038
final protected function getImageInfo ( $ file ) { $ image = getimagesize ( $ file ) ; if ( $ image !== false ) { return array ( 'width' => $ image [ 0 ] , 'height' => $ image [ 1 ] , 'type' => $ image [ 2 ] , 'mime' => $ image [ 'mime' ] , 'bits' => isset ( $ image [ 'bits' ] ) ? $ image [ 'bits' ] : null ) ; } else { return false ; } }
Returns image info
27,039
final protected function createImageFromFile ( $ file , $ type ) { switch ( $ type ) { case \ IMAGETYPE_GIF : return imagecreatefromgif ( $ file ) ; case \ IMAGETYPE_JPEG : return imagecreatefromjpeg ( $ file ) ; case \ IMAGETYPE_PNG : return imagecreatefrompng ( $ file ) ; default : throw new LogicException ( sprintf ( 'Can not create image from "%s"' , $ file ) ) ; } }
Loads an image into the memory from a file - system or URL
27,040
final protected function load ( $ file ) { $ info = $ this -> getImageInfo ( $ file ) ; if ( $ info !== false ) { $ this -> image = $ this -> createImageFromFile ( $ file , $ info [ 'type' ] ) ; $ this -> width = $ info [ 'width' ] ; $ this -> height = $ info [ 'height' ] ; $ this -> type = $ info [ 'type' ] ; $ this -> mime = $ info [ 'mime' ] ; $ this -> requiredMemorySpace = $ info [ 'width' ] * $ info [ 'height' ] * $ info [ 'bits' ] ; return true ; } else { return false ; } }
Loads the image into the memory
27,041
final public function save ( $ path , $ quality = 75 , $ type = null ) { if ( $ type === null ) { $ type = $ this -> type ; } switch ( $ type ) { case \ IMAGETYPE_GIF : $ result = imagegif ( $ this -> image , $ path ) ; break ; case \ IMAGETYPE_JPEG : $ result = imagejpeg ( $ this -> image , $ path , $ quality ) ; break ; case \ IMAGETYPE_PNG : $ result = imagepng ( $ this -> image , $ path , 9 ) ; break ; default : throw new LogicException ( sprintf ( 'Can not save image format (%s) to %s' , $ type , $ path ) ) ; } $ this -> done ( ) ; return $ result ; }
Saves an image to a file
27,042
final public function render ( $ quality = 75 ) { header ( "Content-type: " . image_type_to_mime_type ( $ this -> type ) ) ; switch ( $ this -> type ) { case \ IMAGETYPE_GIF : imagegif ( $ this -> image , null ) ; break ; case \ IMAGETYPE_JPEG : imagejpeg ( $ this -> image , null , $ quality ) ; break ; case \ IMAGETYPE_PNG : imagepng ( $ this -> image , null , 9 ) ; break ; default : throw new LogicException ( sprintf ( 'Can not create image from "%s"' , $ this -> file ) ) ; } $ this -> done ( ) ; exit ( 1 ) ; }
Renders the image in a browser directly
27,043
public function githubAuth ( ) { if ( $ this -> hasAuth ( ) ) { $ this -> io ( ) -> warning ( 'A personal GitHub access token has already been setup.' ) ; return ; } $ this -> io ( ) -> note ( "A personal GitHub access token is required.\n\n" . 'If you need help setting up a access token follow the GitHub guide:' . ' https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/' ) ; $ user = $ this -> ask ( 'GitHub username:' ) ; $ pass = $ this -> askHidden ( 'GitHub token (hidden):' ) ; $ status = $ this -> gitHubUserAuth ( ) -> setUser ( $ user ) -> setToken ( $ pass ) -> save ( ) ; if ( ! $ status ) { $ this -> io ( ) -> success ( "You've successfully added your personal GitHub access token." ) ; } }
Authenticate GitHub user .
27,044
public function githubIssueStart ( ) { $ listings = $ this -> getIssueListing ( ) ; $ issue = $ this -> doAsk ( new ChoiceQuestion ( 'Select GitHub issue:' , $ listings ) ) ; $ user = $ this -> getUser ( ) ; $ number = array_search ( $ issue , $ listings ) ; $ this -> taskGitHubIssueAssignees ( $ this -> getToken ( ) ) -> setAccount ( $ this -> getAccount ( ) ) -> setRepository ( $ this -> getRepository ( ) ) -> number ( $ number ) -> addAssignee ( $ user ) -> run ( ) ; $ this -> say ( sprintf ( 'GH-%d issue was assigned to %s on GitHub.' , $ number , $ user ) ) ; if ( $ this -> ask ( 'Create Git branch? (yes/no) [no] ' ) ) { $ branch = $ this -> normailizeBranchName ( "$number-$issue" ) ; $ command = $ this -> hasGitFlow ( ) ? "flow feature start '$branch'" : "checkout -b '$branch'" ; $ this -> taskGitStack ( ) -> stopOnFail ( ) -> exec ( $ command ) -> run ( ) ; } }
Start working a GitHub issue .
27,045
public function githubLighthouseStatus ( $ sha , $ opts = [ 'hostname' => null , 'protocol' => 'http' , 'performance' => false , 'performance-score' => 50 , 'accessibility' => false , 'accessibility-score' => 50 , 'best-practices' => false , 'best-practices-score' => 50 , 'progressive-web-app' => false , 'progressive-web-app-score' => 50 , ] ) { $ host = ProjectX :: getProjectConfig ( ) -> getHost ( ) ; $ protocol = $ opts [ 'protocol' ] ; $ hostname = isset ( $ opts [ 'hostname' ] ) ? $ opts [ 'hostname' ] : ( isset ( $ host [ 'name' ] ) ? $ host [ 'name' ] : 'localhost' ) ; $ url = "$protocol://$hostname" ; $ path = new \ SplFileInfo ( "/tmp/projectx-lighthouse-$sha.json" ) ; $ this -> taskGoogleLighthouse ( ) -> setUrl ( $ url ) -> chromeFlags ( [ '--headless' , '--no-sandbox' ] ) -> setOutput ( 'json' ) -> setOutputPath ( $ path ) -> run ( ) ; if ( ! file_exists ( $ path ) ) { throw new \ RuntimeException ( 'Unable to locate the Google lighthouse results.' ) ; } $ selected = array_filter ( [ 'performance' , 'accessibility' , 'best-practices' , 'progressive-web-app' ] , function ( $ key ) use ( $ opts ) { return $ opts [ $ key ] === true ; } ) ; $ report_data = $ this -> findLighthouseScoreReportData ( $ path , $ selected ) ; $ state = $ this -> determineLighthouseState ( $ report_data , $ opts ) ; $ this -> taskGitHubRepoStatusesCreate ( $ this -> getToken ( ) ) -> setAccount ( $ this -> getAccount ( ) ) -> setRepository ( $ this -> getRepository ( ) ) -> setSha ( $ sha ) -> setParamState ( $ state ) -> setParamDescription ( 'Google Lighthouse Tests' ) -> setParamContext ( 'project-x/lighthouse' ) -> run ( ) ; }
GitHub lighthouse status check .
27,046
protected function determineLighthouseState ( array $ values , array $ opts ) { $ state = 'success' ; foreach ( $ values as $ key => $ info ) { $ required_score = isset ( $ opts [ "$key-score" ] ) ? ( $ opts [ "$key-score" ] <= 100 ? $ opts [ "$key-score" ] : 100 ) : 50 ; if ( $ info [ 'score' ] < $ required_score && $ info [ 'score' ] !== $ required_score ) { return 'failure' ; } } return $ state ; }
Determine Google lighthouse state .
27,047
protected function findLighthouseScoreReportData ( \ SplFileInfo $ path , array $ selected ) { $ data = [ ] ; $ json = json_decode ( file_get_contents ( $ path ) , true ) ; foreach ( $ json [ 'reportCategories' ] as $ report ) { if ( ! isset ( $ report [ 'name' ] ) || ! isset ( $ report [ 'score' ] ) ) { continue ; } $ label = $ report [ 'name' ] ; $ key = Utility :: cleanString ( strtolower ( strtr ( $ label , ' ' , '_' ) ) , '/[^a-zA-Z\_]/' ) ; if ( ! in_array ( $ key , $ selected ) ) { continue ; } $ data [ $ key ] = [ 'name' => $ label , 'score' => round ( $ report [ 'score' ] ) ] ; } return $ data ; }
Find Google lighthouse score report data .
27,048
protected function outputGitHubIssues ( ) { $ issues = $ this -> taskGitHubIssueList ( $ this -> getToken ( ) , $ this -> getAccount ( ) , $ this -> getRepository ( ) ) -> run ( ) ; unset ( $ issues [ 'time' ] ) ; $ table = ( new Table ( $ this -> output ) ) -> setHeaders ( [ 'Issue' , 'Title' , 'State' , 'Assignee' , 'Labels' , 'Author' ] ) ; $ rows = [ ] ; foreach ( $ issues as $ issue ) { $ labels = isset ( $ issue [ 'labels' ] ) ? $ this -> formatLabelNames ( $ issue [ 'labels' ] ) : null ; $ assignee = isset ( $ issue [ 'assignee' ] [ 'login' ] ) ? $ issue [ 'assignee' ] [ 'login' ] : 'none' ; $ rows [ ] = [ $ issue [ 'number' ] , $ issue [ 'title' ] , $ issue [ 'state' ] , $ assignee , $ labels , $ issue [ 'user' ] [ 'login' ] , ] ; } $ table -> setRows ( $ rows ) ; $ table -> render ( ) ; return $ this ; }
Output GitHub issue table .
27,049
protected function getIssueListing ( ) { $ issues = $ this -> taskGitHubIssueList ( $ this -> getToken ( ) , $ this -> getAccount ( ) , $ this -> getRepository ( ) ) -> run ( ) ; $ listing = [ ] ; foreach ( $ issues as $ issue ) { if ( ! isset ( $ issue [ 'title' ] ) ) { continue ; } $ number = $ issue [ 'number' ] ; $ listing [ $ number ] = $ issue [ 'title' ] ; } return $ listing ; }
Get GitHub issue listing .
27,050
protected function formatLabelNames ( array $ labels ) { if ( empty ( $ labels ) ) { return ; } $ names = [ ] ; foreach ( $ labels as $ label ) { if ( ! isset ( $ label [ 'name' ] ) ) { continue ; } $ names [ ] = $ label [ 'name' ] ; } return implode ( ', ' , $ names ) ; }
Format GitHub labels .
27,051
public function addNamespaces ( array $ namespaces ) { foreach ( $ namespaces as $ prefix => $ baseDir ) { $ this -> addNamespace ( $ prefix , $ baseDir ) ; } }
Adds a collection to the stack
27,052
public static function init ( $ locale , $ environment , $ version ) { $ envFilename = Registry :: get ( 'applicationPath' ) . '/.env' ; if ( file_exists ( $ envFilename ) ) { $ env = Ini :: parse ( $ envFilename , true , $ locale . '-' . $ environment . '-' . $ version , 'common' , false ) ; $ env = self :: mergeEnvVariables ( $ env ) ; } else { $ env = new \ StdClass ( ) ; } self :: $ data = Ini :: bindArrayToObject ( $ env ) ; }
reads the . env file merges the environment on top of the optional . env file returns the merged config
27,053
static public function register ( BlobRestProxy $ proxy , $ name = 'azure' ) { stream_register_wrapper ( $ name , __CLASS__ ) ; self :: $ clients [ $ name ] = $ proxy ; }
Register the given blob rest proxy as client for a stream wrapper .
27,054
static public function getClient ( $ name ) { if ( ! isset ( self :: $ clients [ $ name ] ) ) { throw new BlobException ( "There is no client registered for stream type '" . $ name . "://" ) ; } return self :: $ clients [ $ name ] ; }
Get the client for an azure stream name .
27,055
private function getStorageClient ( $ path = '' ) { if ( $ this -> storageClient === null ) { $ url = explode ( ':' , $ path ) ; if ( ! $ url ) { throw new BlobException ( 'Could not parse path "' . $ path . '".' ) ; } $ this -> storageClient = self :: getClient ( $ url [ 0 ] ) ; if ( ! $ this -> storageClient ) { throw new BlobException ( 'No storage client registered for stream type "' . $ url [ 0 ] . '://".' ) ; } } return $ this -> storageClient ; }
Retrieve storage client for this stream type
27,056
public function stream_write ( $ data ) { if ( ! $ this -> temporaryFileHandle ) { return 0 ; } $ len = strlen ( $ data ) ; fwrite ( $ this -> temporaryFileHandle , $ data , $ len ) ; return $ len ; }
Write to the stream
27,057
public function url_stat ( $ path , $ flags ) { $ stat = array ( ) ; $ stat [ 'dev' ] = 0 ; $ stat [ 'ino' ] = 0 ; $ stat [ 'mode' ] = 0 ; $ stat [ 'nlink' ] = 0 ; $ stat [ 'uid' ] = 0 ; $ stat [ 'gid' ] = 0 ; $ stat [ 'rdev' ] = 0 ; $ stat [ 'size' ] = 0 ; $ stat [ 'atime' ] = 0 ; $ stat [ 'mtime' ] = 0 ; $ stat [ 'ctime' ] = 0 ; $ stat [ 'blksize' ] = 0 ; $ stat [ 'blocks' ] = 0 ; $ info = null ; try { $ metadata = $ this -> getStorageClient ( $ path ) -> getBlobProperties ( $ this -> getContainerName ( $ path ) , $ this -> getFileName ( $ path ) ) ; $ stat [ 'size' ] = $ metadata -> getProperties ( ) -> getContentLength ( ) ; $ lastmodified = $ metadata -> getProperties ( ) -> getLastModified ( ) -> format ( 'U' ) ; $ stat [ 'mtime' ] = $ lastmodified ; $ stat [ 'ctime' ] = $ lastmodified ; $ stat [ 'mode' ] = 0100000 ; return array_values ( $ stat ) + $ stat ; } catch ( Exception $ ex ) { return false ; } }
Return array of URL variables
27,058
public function dir_readdir ( ) { $ object = current ( $ this -> blobs ) ; if ( $ object !== false ) { next ( $ this -> blobs ) ; return $ object -> getName ( ) ; } return false ; }
Return the next filename in the directory
27,059
final public function init ( ) { $ this -> sourcePath = $ this -> getSourcePath ( ) ; $ this -> depends = [ CpAsset :: class ] ; $ this -> js = $ this -> getScripts ( ) ; $ this -> css = $ this -> getStylesheets ( ) ; parent :: init ( ) ; }
Initialize the source path and scripts
27,060
public function addRole ( $ name ) { $ namespaceUri = $ this -> dom -> lookupNamespaceUri ( $ this -> dom -> namespaceURI ) ; $ roleNode = $ this -> dom -> createElementNS ( $ namespaceUri , 'Role' ) ; $ roleNode -> setAttribute ( 'name' , $ name ) ; $ instancesNode = $ this -> dom -> createElementNS ( $ namespaceUri , 'Instances' ) ; $ instancesNode -> setAttribute ( 'count' , '2' ) ; $ configurationSettings = $ this -> dom -> createElementNS ( $ namespaceUri , 'ConfigurationSettings' ) ; $ roleNode -> appendChild ( $ instancesNode ) ; $ roleNode -> appendChild ( $ configurationSettings ) ; $ this -> dom -> documentElement -> appendChild ( $ roleNode ) ; $ this -> save ( ) ; }
Add a role to service configuration
27,061
public function copyForDeployment ( $ targetPath , $ development = true ) { $ dom = new \ DOMDocument ( '1.0' , 'UTF-8' ) ; $ dom -> loadXML ( $ this -> dom -> saveXML ( ) ) ; $ xpath = new \ DOMXpath ( $ dom ) ; $ xpath -> registerNamespace ( 'sc' , $ dom -> lookupNamespaceUri ( $ dom -> namespaceURI ) ) ; $ settings = $ xpath -> evaluate ( '//sc:ConfigurationSettings/sc:Setting[@name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"]' ) ; foreach ( $ settings as $ setting ) { if ( $ development ) { $ setting -> setAttribute ( 'value' , 'UseDevelopmentStorage=true' ) ; } else if ( strlen ( $ setting -> getAttribute ( 'value' ) ) === 0 ) { if ( $ this -> storage ) { $ setting -> setAttribute ( 'value' , sprintf ( 'DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s' , $ this -> storage [ 'accountName' ] , $ this -> storage [ 'accountKey' ] ) ) ; } else { throw new \ RuntimeException ( <<<EXCServiceConfiguration.csdef: Missing value for'Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString'.You have to modify the app/azure/ServiceConfiguration.csdef to containa value for the diagnostics connection string or better configure'windows_azure_distribution.diagnostics.accountName' and'windows_azure_distribution.diagnostics.accountKey' in yourapp/config/config.ymlIf you don't want to enable diagnostics you should delete theconnection string elements from ServiceConfiguration.csdef file.EXC ) ; } } } $ dom -> save ( $ targetPath . '/ServiceConfiguration.cscfg' ) ; }
Copy ServiceConfiguration over to build directory given with target path and modify some of the settings to point to development settings .
27,062
public function setConfigurationSetting ( $ roleName , $ name , $ value ) { $ namespaceUri = $ this -> dom -> lookupNamespaceUri ( $ this -> dom -> namespaceURI ) ; $ xpath = new \ DOMXpath ( $ this -> dom ) ; $ xpath -> registerNamespace ( 'sc' , $ namespaceUri ) ; $ xpathExpression = '//sc:Role[@name="' . $ roleName . '"]//sc:ConfigurationSettings//sc:Setting[@name="' . $ name . '"]' ; $ settingList = $ xpath -> evaluate ( $ xpathExpression ) ; if ( $ settingList -> length == 1 ) { $ settingNode = $ settingList -> item ( 0 ) ; } else { $ settingNode = $ this -> dom -> createElementNS ( $ namespaceUri , 'Setting' ) ; $ settingNode -> setAttribute ( 'name' , $ name ) ; $ configSettingList = $ xpath -> evaluate ( '//sc:Role[@name="' . $ roleName . '"]/sc:ConfigurationSettings' ) ; if ( $ configSettingList -> length == 0 ) { throw new \ RuntimeException ( "Cannot find <ConfigurationSettings /> in Role '" . $ roleName . "'." ) ; } $ configSettings = $ configSettingList -> item ( 0 ) ; $ configSettings -> appendChild ( $ settingNode ) ; } $ settingNode -> setAttribute ( 'value' , $ value ) ; $ this -> save ( ) ; }
Add a configuration setting to the ServiceConfiguration . cscfg
27,063
public function addCertificate ( $ roleName , RemoteDesktopCertificate $ certificate ) { $ namespaceUri = $ this -> dom -> lookupNamespaceUri ( $ this -> dom -> namespaceURI ) ; $ xpath = new \ DOMXpath ( $ this -> dom ) ; $ xpath -> registerNamespace ( 'sc' , $ namespaceUri ) ; $ xpathExpression = '//sc:Role[@name="' . $ roleName . '"]//sc:Certificates' ; $ certificateList = $ xpath -> evaluate ( $ xpathExpression ) ; if ( $ certificateList -> length == 1 ) { $ certificatesNode = $ certificateList -> item ( 0 ) ; $ certificateNodeToDelete = null ; foreach ( $ certificatesNode -> childNodes as $ certificateNode ) { if ( ! $ certificateNode instanceof \ DOMElement ) { continue ; } if ( 'Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption' == $ certificateNode -> getAttribute ( 'name' ) ) { $ certificateNodeToDelete = $ certificateNode ; } } if ( ! is_null ( $ certificateNodeToDelete ) ) { $ certificatesNode -> removeChild ( $ certificateNodeToDelete ) ; } } else { $ certificatesNode = $ this -> dom -> createElementNS ( $ namespaceUri , 'Certificates' ) ; $ roleNodeList = $ xpath -> evaluate ( '//sc:Role[@name="' . $ roleName . '"]' ) ; if ( $ roleNodeList -> length == 0 ) { throw new \ RuntimeException ( "No Role found with name '" . $ roleName . "'." ) ; } $ roleNode = $ roleNodeList -> item ( 0 ) ; $ roleNode -> appendChild ( $ certificatesNode ) ; } $ certificateNode = $ this -> dom -> createElementNS ( $ namespaceUri , 'Certificate' ) ; $ certificateNode -> setAttribute ( 'name' , 'Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption' ) ; $ certificateNode -> setAttribute ( 'thumbprint' , $ certificate -> getThumbprint ( ) ) ; $ certificateNode -> setAttribute ( 'thumbprintAlgorithm' , 'sha1' ) ; $ certificatesNode -> appendChild ( $ certificateNode ) ; $ this -> save ( ) ; }
Add Certificate to the Role
27,064
private function prepareStandaloneMode ( ) { $ param_path = nbCLICheckOption ( 'p' , 'path' , ':' , false ) ; if ( $ param_path && is_dir ( $ param_path ) ) { $ this -> mode = CNabuEngine :: ENGINE_MODE_STANDALONE ; $ this -> host_path = $ param_path ; } else { echo "Invalid host path provided for Standalone Engine Mode.\n" ; echo "Please revise your params and try again.\n" ; } }
Prepare Apache HTTP Server to run as Standalone mode .
27,065
private function prepareHostedMode ( ) { $ param_server = nbCLICheckOption ( 's' , 'server' , ':' , false ) ; if ( strlen ( $ param_server ) === 0 ) { $ param_server = self :: DEFAULT_HOSTED_KEY ; $ this -> mode = CNabuEngine :: ENGINE_MODE_HOSTED ; $ this -> server_key = $ param_server ; } else { echo "Invalid server key provided for Hosted Engine Mode.\n" ; echo "Please revise your options and try again.\n" ; } }
Prepare Apache HTTP Server to run as Hosted mode .
27,066
private function prepareClusteredMode ( ) { $ param_server = nbCLICheckOption ( 's' , 'server' , ':' , false ) ; if ( strlen ( $ param_server ) === 0 ) { echo "Missed --server or -s option.\n" ; echo "Please revise your options and try again.\n" ; } else { $ this -> mode = CNabuEngine :: ENGINE_MODE_CLUSTERED ; $ this -> server_key = $ param_server ; } }
Prepare Apache HTTP Server to run as Cluster mode .
27,067
private function runStandalone ( ) { $ nb_server = new CNabuBuiltInServer ( ) ; $ nb_server -> setVirtualHostsPath ( $ this -> host_path ) ; $ nb_site = new CNabuBuiltInSite ( ) ; $ nb_site -> setBasePath ( '' ) ; $ nb_site -> setUseFramework ( 'T' ) ; $ apache_server = new CApacheHTTPServer ( $ nb_server , $ nb_site ) ; if ( $ apache_server -> locateApacheServer ( ) ) { $ this -> displayServerConfig ( $ apache_server ) ; if ( $ this -> checkHostFolders ( $ this -> host_path ) ) { $ apache_server -> createStandaloneConfiguration ( ) ; } } }
Runs the Apache HTTP Server as Standalone mode .
27,068
private function runHosted ( ) { $ nb_server = CNabuServer :: findByKey ( $ this -> server_key ) ; $ apache_server = new CApacheHTTPServer ( $ nb_server ) ; if ( $ apache_server -> locateApacheServer ( ) ) { $ this -> displayServerConfig ( $ apache_server ) ; $ apache_server -> createHostedConfiguration ( ) ; } }
Runs the Apache HTTP Server as Hosted mode .
27,069
private function runClustered ( ) { $ nb_server = CNabuServer :: findByKey ( $ this -> server_key ) ; if ( ! is_object ( $ nb_server ) ) { throw new ENabuCoreException ( ENabuCoreException :: ERROR_SERVER_NOT_FOUND , array ( $ this -> server_key , '*' , '*' ) ) ; } $ apache_server = new CApacheHTTPServer ( $ nb_server ) ; if ( $ apache_server -> locateApacheServer ( ) ) { $ this -> displayServerConfig ( $ apache_server ) ; $ apache_server -> createClusteredConfiguration ( ) ; } }
Runs the Apache HTTP Server as Clustered mode .
27,070
private function checkHostFolders ( string $ path ) : bool { echo "Checking folders of host...\n" ; $ retval = $ this -> checkFolder ( $ path , 'private' ) || $ this -> checkFolder ( $ path , 'httpdocs' ) || $ this -> checkFolder ( $ path , 'httpsdocs' ) || $ this -> checkFolder ( $ path , 'phputils' ) || $ this -> checkFolder ( $ path , 'templates' ) ; echo "OK\n" ; return $ retval ; }
Check if Host Folders exists .
27,071
private function checkFolder ( string $ path , string $ folder , bool $ create = false ) : bool { $ retval = false ; $ target = $ path . ( is_string ( $ folder ) && strlen ( $ folder ) > 0 ? DIRECTORY_SEPARATOR . $ folder : '' ) ; echo " ... checking folder $target ..." ; if ( is_dir ( $ target ) ) { echo "EXISTS\n" ; $ retval = true ; } elseif ( $ create ) { if ( $ retval = mkdir ( $ target ) ) { echo "CREATED\n" ; } else { echo "ERROR\n" ; } } else { echo "NOT PRESENT\n" ; } return $ retval ; }
Check if a folder exists inside a path .
27,072
protected function alterService ( DockerService $ service ) { if ( $ this -> internal ) { $ links = [ ] ; $ name = $ this -> getName ( ) ; $ host = ProjectX :: getProjectConfig ( ) -> getHost ( ) ; if ( isset ( $ host [ 'name' ] ) ) { $ links [ ] = "traefik.{$name}.frontend.rule=Host:{$host['name']}" ; } $ service -> setNetworks ( [ 'internal' , DockerEngineType :: TRAEFIK_NETWORK ] ) -> setLabels ( array_merge ( [ 'traefik.enable=true' , "traefik.{$name}.frontend.backend={$name}" , "traefik.{$name}.port={$this->ports()[0]}" , 'traefik.docker.network=' . DockerEngineType :: TRAEFIK_NETWORK , ] , $ links ) ) ; } else { $ service -> setPorts ( $ this -> getPorts ( ) ) ; } return $ service ; }
Alter the service object .
27,073
protected function createSourceExtractors ( InputInterface $ input , OutputInterface $ output , $ config , CacheInterface $ cachePool ) { $ extractors = [ ] ; foreach ( [ 'bower' => AuthorExtractor \ BowerAuthorExtractor :: class , 'composer' => AuthorExtractor \ ComposerAuthorExtractor :: class , 'packages' => AuthorExtractor \ NodeAuthorExtractor :: class , 'php-files' => AuthorExtractor \ PhpDocAuthorExtractor :: class , ] as $ option => $ class ) { if ( $ input -> getOption ( $ option ) ) { $ extractors [ $ option ] = new $ class ( $ config , $ output , $ cachePool ) ; } } return $ extractors ; }
Create all source extractors as specified on the command line .
27,074
private function handleExtractors ( $ extractors , AuthorExtractor $ reference , AuthorListComparator $ comparator ) { $ failed = false ; foreach ( $ extractors as $ extractor ) { $ failed = ! $ comparator -> compare ( $ extractor , $ reference ) || $ failed ; } return $ failed ; }
Process the given extractors .
27,075
private function enableDeprecatedNoProgressBar ( InputInterface $ input ) { if ( ! $ input -> getOption ( 'no-progress-bar' ) ) { return ; } @ trigger_error ( 'The command option --no-progress-bar is deprecated since 1.4 and where removed in 2.0. Use --no-progress instead.' , E_USER_DEPRECATED ) ; $ input -> setOption ( 'no-progress' , true ) ; }
Enable the deprecated no progress bar option .
27,076
private function createGitAuthorExtractor ( $ scope , Config $ config , $ error , $ cache , GitRepository $ git ) { if ( $ scope === 'project' ) { return new GitProjectAuthorExtractor ( $ config , $ error , $ cache ) ; } else { $ extractor = new GitAuthorExtractor ( $ config , $ error , $ cache ) ; $ extractor -> collectFilesWithCommits ( $ git ) ; return $ extractor ; } }
Create git author extractor for demanded scope .
27,077
private static function generateRandomString ( $ length = 10 ) { $ characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ; $ string = '' ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ string .= $ characters [ rand ( 0 , strlen ( $ characters ) - 1 ) ] ; } return $ string ; }
Generate a random string that we can use for the code by default
27,078
public function AddLink ( ) { $ link = Controller :: join_links ( Director :: absoluteBaseURL ( ) , ShoppingCart :: config ( ) -> url_segment , "usediscount" , $ this -> Code ) ; return $ link ; }
Return a URL that allows this code to be added to a cart automatically
27,079
protected function addFlashMessage ( $ type , $ transKey , $ transOpts = array ( ) , $ domain = 'messages' ) { $ this -> get ( 'session' ) -> getFlashBag ( ) -> add ( $ type , $ this -> get ( 'translator' ) -> trans ( $ transKey , $ transOpts , $ domain ) ) ; }
Ajout le message flash dans la session .
27,080
private function hasValidExtension ( $ filename ) { $ extension = mb_strtolower ( pathinfo ( $ filename , \ PATHINFO_EXTENSION ) , 'UTF-8' ) ; foreach ( $ this -> extensions as & $ expected ) { $ expected = mb_strtolower ( $ expected , 'UTF-8' ) ; } return in_array ( $ extension , $ this -> extensions ) ; }
Whether an extension belongs in collection
27,081
public static function paginateChoices ( AjaxChoiceLoaderInterface $ choiceLoader , array $ choices ) { list ( $ startTo , $ endTo ) = static :: getRangeValues ( $ choiceLoader ) ; if ( \ is_array ( current ( $ choices ) ) ) { return static :: paginateGroupChoices ( $ choices , $ startTo , $ endTo ) ; } return static :: paginateSimpleChoices ( $ choices , $ startTo , $ endTo ) ; }
Paginate the flatten choices .
27,082
protected static function getRangeValues ( AjaxChoiceLoaderInterface $ choiceLoader ) { $ startTo = ( $ choiceLoader -> getPageNumber ( ) - 1 ) * $ choiceLoader -> getPageSize ( ) ; $ startTo = $ startTo < 0 ? 0 : $ startTo ; $ endTo = $ startTo + $ choiceLoader -> getPageSize ( ) ; if ( 0 >= $ choiceLoader -> getPageSize ( ) ) { $ endTo = $ choiceLoader -> getSize ( ) ; } if ( $ endTo > $ choiceLoader -> getSize ( ) ) { $ endTo = $ choiceLoader -> getSize ( ) ; } return [ $ startTo , $ endTo ] ; }
Gets range values .
27,083
protected static function paginateSimpleChoices ( array $ choices , $ startTo , $ endTo ) { $ paginatedChoices = [ ] ; $ index = 0 ; foreach ( $ choices as $ key => $ choice ) { if ( $ index >= $ startTo && $ index < $ endTo ) { $ paginatedChoices [ $ key ] = $ choice ; } ++ $ index ; } return $ paginatedChoices ; }
Paginate the flatten simple choices .
27,084
protected static function paginateGroupChoices ( array $ choices , $ startTo , $ endTo ) { $ paginatedChoices = [ ] ; $ index = 0 ; foreach ( $ choices as $ groupName => $ groupChoices ) { foreach ( $ groupChoices as $ key => $ choice ) { if ( $ index >= $ startTo && $ index < $ endTo ) { $ paginatedChoices [ $ groupName ] [ $ key ] = $ choice ; } ++ $ index ; } } return $ paginatedChoices ; }
Paginate the flatten group choices .
27,085
public function isCircularReference ( object $ object ) : bool { $ objectHashId = spl_object_hash ( $ object ) ; if ( isset ( $ this -> circularReferenceHashTable [ $ objectHashId ] ) ) { return true ; } $ this -> circularReferenceHashTable [ $ objectHashId ] = true ; return false ; }
Checks if the input object indicates that we ve hit a circular reference
27,086
protected function ensureFileExists ( $ path ) { if ( file_exists ( $ path ) === false ) { @ mkdir ( dirname ( $ path ) , 0777 , true ) ; touch ( $ path ) ; } }
Create the language file if one does not exist .
27,087
public static function getByBookId ( Bookboon $ bookboon , string $ bookId ) : BookboonResponse { if ( Entity :: isValidUUID ( $ bookId ) === false ) { throw new BadUUIDException ( ) ; } $ bResponse = $ bookboon -> rawRequest ( "/books/$bookId/review" ) ; $ bResponse -> setEntityStore ( new EntityStore ( Review :: getEntitiesFromArray ( $ bResponse -> getReturnArray ( ) ) ) ) ; return $ bResponse ; }
Get Reviews for specified Book .
27,088
public function submit ( Bookboon $ bookboon , string $ bookId ) : void { if ( Entity :: isValidUUID ( $ bookId ) ) { $ bookboon -> rawRequest ( "/books/$bookId/review" , $ this -> getData ( ) , ClientInterface :: HTTP_POST ) ; } }
submit a book review helper method .
27,089
public function initialize ( stdClass $ schema , Uri $ uri ) { $ this -> registerSchema ( $ schema , $ uri ) ; $ this -> stack = [ [ $ uri , $ schema ] ] ; }
Initializes the resolver with a root schema on which resolutions will be based .
27,090
public function resolve ( stdClass $ reference ) { $ baseUri = $ this -> getCurrentUri ( ) ; $ uri = new Uri ( $ reference -> { '$ref' } ) ; if ( ! $ uri -> isAbsolute ( ) ) { $ uri -> resolveAgainst ( $ baseUri ) ; } $ identifier = $ uri -> getPrimaryResourceIdentifier ( ) ; if ( ! isset ( $ this -> schemas [ $ identifier ] ) ) { $ schema = $ this -> fetchSchemaAt ( $ identifier ) ; $ this -> registerSchema ( $ schema , $ uri ) ; } else { $ schema = $ this -> schemas [ $ identifier ] ; } $ resolved = $ this -> resolvePointer ( $ schema , $ uri ) ; if ( $ resolved === $ reference ) { throw new SelfReferencingPointerException ( ) ; } if ( ! is_object ( $ resolved ) ) { throw new InvalidPointerTargetException ( [ $ uri -> getRawUri ( ) ] ) ; } return [ $ uri , $ resolved ] ; }
Resolves a schema reference according to the JSON Reference specification draft . Returns an array containing the resolved URI and the resolved schema .
27,091
private function registerSchema ( stdClass $ schema , Uri $ uri ) { if ( ! isset ( $ this -> schemas [ $ uri -> getPrimaryResourceIdentifier ( ) ] ) ) { $ this -> schemas [ $ uri -> getPrimaryResourceIdentifier ( ) ] = $ schema ; } }
Caches a schema reference for future use .
27,092
private function fetchSchemaAt ( $ uri ) { if ( $ hook = $ this -> preFetchHook ) { $ uri = $ hook ( $ uri ) ; } set_error_handler ( function ( $ severity , $ error ) use ( $ uri ) { restore_error_handler ( ) ; throw new UnfetchableUriException ( [ $ uri , $ error , $ severity ] ) ; } ) ; $ content = file_get_contents ( $ uri ) ; restore_error_handler ( ) ; $ schema = json_decode ( $ content ) ; if ( json_last_error ( ) !== JSON_ERROR_NONE ) { throw new JsonDecodeException ( sprintf ( 'Cannot decode JSON from URI "%s" (error: %s)' , $ uri , Utils :: lastJsonErrorMessage ( ) ) ) ; } if ( ! is_object ( $ schema ) ) { throw new InvalidRemoteSchemaException ( [ $ uri ] ) ; } return $ schema ; }
Fetches a remote schema and ensures it is valid .
27,093
private function resolvePointer ( stdClass $ schema , Uri $ pointerUri ) { $ segments = $ pointerUri -> getPointerSegments ( ) ; $ pointer = $ pointerUri -> getRawPointer ( ) ; $ currentNode = $ schema ; for ( $ i = 0 , $ max = count ( $ segments ) ; $ i < $ max ; ++ $ i ) { if ( is_object ( $ currentNode ) ) { if ( property_exists ( $ currentNode , $ segments [ $ i ] ) ) { $ currentNode = $ currentNode -> { $ segments [ $ i ] } ; continue ; } throw new UnresolvedPointerPropertyException ( [ $ segments [ $ i ] , $ i , $ pointer ] ) ; } if ( is_array ( $ currentNode ) ) { if ( ! preg_match ( '/^\d+$/' , $ segments [ $ i ] ) ) { throw new InvalidPointerIndexException ( [ $ segments [ $ i ] , $ i , $ pointer ] ) ; } if ( ! isset ( $ currentNode [ $ index = ( int ) $ segments [ $ i ] ] ) ) { throw new UnresolvedPointerIndexException ( [ $ segments [ $ i ] , $ i , $ pointer ] ) ; } $ currentNode = $ currentNode [ $ index ] ; continue ; } throw new InvalidSegmentTypeException ( [ $ i , $ pointer ] ) ; } return $ currentNode ; }
Resolves a JSON pointer according to RFC 6901 .
27,094
public function guessCountQuery ( $ column , $ alias ) { return str_replace ( $ this -> selected , $ this -> createFunction ( 'COUNT' , array ( $ column ) , $ alias ) , $ this -> getQueryString ( ) ) ; }
Guesses count query
27,095
public function isFilterable ( $ state , $ target ) { if ( $ state === true && empty ( $ target ) && $ target !== '0' ) { return false ; } if ( $ state == true && ( $ target == '%%' || $ target == '%' ) ) { return false ; } if ( $ state == true && $ target == '0' ) { return true ; } if ( is_array ( $ target ) && empty ( $ target ) ) { return false ; } $ result = false ; if ( $ state === false ) { $ result = true ; } else { if ( is_string ( $ target ) && $ target != '0' && ! empty ( $ target ) ) { $ result = true ; } if ( is_array ( $ target ) ) { if ( empty ( $ target ) ) { $ result = false ; } else { $ count = 0 ; foreach ( $ target as $ value ) { if ( ! empty ( $ value ) ) { $ count ++ ; } } if ( $ count == count ( $ target ) ) { $ result = true ; } } } } return $ result ; }
Checks whether it s worth filtering
27,096
private function createFunction ( $ func , array $ arguments = array ( ) , $ alias = null ) { foreach ( $ arguments as $ index => $ argument ) { if ( $ argument instanceof RawSqlFragmentInterface ) { $ item = $ argument -> getFragment ( ) ; } else { $ item = $ this -> quote ( $ argument ) ; } $ arguments [ $ index ] = $ item ; } $ fragment = sprintf ( ' %s(%s) ' , $ func , implode ( ', ' , $ arguments ) ) ; if ( ! is_null ( $ alias ) ) { $ fragment .= sprintf ( ' AS %s ' , $ this -> quote ( $ alias ) ) ; } if ( $ this -> hasFunctionCall === true ) { $ this -> append ( ', ' ) ; } $ this -> hasFunctionCall = true ; return $ fragment ; }
Generates SQL function fragment
27,097
private function needsQuoting ( $ target ) { $ isSqlFunction = strpos ( $ target , '(' ) !== false || strpos ( $ target , ')' ) !== false ; $ isColumn = strpos ( $ target , '.' ) !== false ; $ hasQuotes = strpos ( $ target , '`' ) !== false ; return ! ( is_numeric ( $ target ) || $ isColumn || $ isSqlFunction || $ hasQuotes ) ; }
Checks whether it s worth applying a wrapper for a target
27,098
private function quote ( $ target ) { $ wrapper = function ( $ column ) { return sprintf ( '`%s`' , $ column ) ; } ; if ( is_array ( $ target ) ) { foreach ( $ target as & $ column ) { $ column = $ this -> needsQuoting ( $ column ) ? $ wrapper ( $ column ) : $ column ; } } else if ( is_scalar ( $ target ) ) { $ target = $ this -> needsQuoting ( $ target ) ? $ wrapper ( $ target ) : $ target ; } else { throw new InvalidArgumentException ( sprintf ( 'Unknown type for wrapping supplied "%s"' , gettype ( $ target ) ) ) ; } return $ target ; }
Wraps a string into back - ticks
27,099
public function insert ( $ table , array $ data , $ ignore = false ) { if ( empty ( $ data ) ) { throw new LogicException ( 'You have not provided a data to be inserted' ) ; } $ keys = array ( ) ; $ values = array_values ( $ data ) ; foreach ( array_keys ( $ data ) as $ key ) { $ keys [ ] = $ this -> quote ( $ key ) ; } if ( $ ignore === true ) { $ ignore = 'IGNORE' ; } else { $ ignore = '' ; } $ this -> append ( sprintf ( 'INSERT %s INTO %s (%s) VALUES (%s)' , $ ignore , $ this -> quote ( $ table ) , implode ( ', ' , $ keys ) , implode ( ', ' , $ values ) ) ) ; return $ this ; }
Builds INSERT query This regular insert query for most cases . It s not aware of ON DUPLICATE KEY