idx
int64
0
60.3k
question
stringlengths
99
4.85k
target
stringlengths
5
718
1,900
public function create ( ) { $ this -> validate ( ) ; $ claims = $ this -> processOptions ( ) ; $ claims [ 'd' ] = $ this -> data ; $ claims [ 'v' ] = 0 ; $ claims [ 'iat' ] = time ( ) ; try { $ token = JWT :: encode ( $ claims , $ this -> secret , 'HS256' ) ; } catch ( \ Exception $ e ) { throw new TokenException ( $ ...
Creates the token .
1,901
private function processOptions ( ) { $ claims = [ ] ; foreach ( $ this -> options as $ name => $ value ) { switch ( $ name ) { case 'expires' : if ( $ value instanceof \ DateTime ) { $ claims [ 'exp' ] = $ value -> getTimestamp ( ) ; } break ; case 'notBefore' : if ( $ value instanceof \ DateTime ) { $ claims [ 'nbf' ...
Parses provided options into a claims array .
1,902
private function validate ( ) { if ( false === $ this -> options [ 'admin' ] && ! array_key_exists ( 'uid' , $ this -> data ) ) { throw new TokenException ( 'No uid provided in data and admin option not set.' ) ; } if ( array_key_exists ( 'uid' , $ this -> data ) ) { $ this -> validateUid ( $ this -> data [ 'uid' ] ) ;...
Validates the combination of data and options .
1,903
private function validateUid ( $ uid ) { if ( ! is_string ( $ uid ) ) { throw new TokenException ( sprintf ( 'The uid must be a string, %s given.' , gettype ( $ uid ) ) ) ; } $ uidSize = mb_strlen ( $ uid , '8bit' ) ; if ( $ uidSize > static :: MAX_UID_SIZE ) { throw new TokenException ( sprintf ( 'The provided uid is ...
Validates an uid .
1,904
private function generateExceptionResponse ( $ request , Exception $ e ) { $ formatters = $ this -> config [ 'formatters' ] ; $ responseFactoryClass = $ this -> config [ 'response_factory' ] ; $ response = $ responseFactoryClass :: make ( $ e ) ; foreach ( $ formatters as $ exceptionType => $ formatter ) { if ( ! ( $ e...
Generate exception response
1,905
public function user ( ) { $ userClassName = Config :: get ( 'auth.model' ) ; if ( is_null ( $ userClassName ) ) { $ userClassName = Config :: get ( 'auth.providers.users.model' ) ; } return $ this -> belongsTo ( $ userClassName ) ; }
Rating belongs to a user .
1,906
protected function injectRequiredKeys ( RootPackageInterface $ rootPackage ) { if ( ! isset ( $ this -> package [ 'license' ] ) && \ count ( $ rootPackage -> getLicense ( ) ) > 0 ) { $ license = current ( $ rootPackage -> getLicense ( ) ) ; if ( 'proprietary' === $ license ) { if ( ! isset ( $ this -> package [ 'privat...
Inject the required keys for asset package defined in root composer package .
1,907
protected function orderPackages ( $ section ) { if ( isset ( $ this -> package [ $ section ] ) && \ is_array ( $ this -> package [ $ section ] ) ) { ksort ( $ this -> package [ $ section ] , SORT_STRING ) ; } }
Order the packages section .
1,908
protected function restoreLockData ( ) { $ this -> composer -> getLocker ( ) -> setLockData ( $ this -> getLockValue ( 'packages' , array ( ) ) , $ this -> getLockValue ( 'packages-dev' ) , $ this -> getLockValue ( 'platform' , array ( ) ) , $ this -> getLockValue ( 'platform-dev' , array ( ) ) , $ this -> getLockValue...
Restore the data of lock file .
1,909
protected function restorePreviousLockFile ( ) { $ config = $ this -> composer -> getConfig ( ) ; list ( $ preferSource , $ preferDist ) = ConsoleUtil :: getPreferredInstallOptions ( $ config , $ this -> input ) ; $ optimize = $ this -> input -> getOption ( 'optimize-autoloader' ) || $ config -> get ( 'optimize-autoloa...
Restore the PHP dependencies with the previous lock file .
1,910
private function getLockValue ( $ key , $ default = null ) { return isset ( $ this -> lock [ $ key ] ) ? $ this -> lock [ $ key ] : $ default ; }
Get the lock value .
1,911
private function getInstaller ( ) { return null !== $ this -> installer ? $ this -> installer : Installer :: create ( $ this -> io , $ this -> composer ) ; }
Get the installer .
1,912
public static function getArrayKeys ( $ content ) { preg_match_all ( self :: ARRAY_KEYS_REGEX , trim ( $ content ) , $ matches ) ; return ! empty ( $ matches ) ? $ matches [ 1 ] : array ( ) ; }
Get the list of keys to be retained with an array representation if they are empty .
1,913
public static function getIndent ( $ content ) { $ indent = self :: DEFAULT_INDENT ; preg_match ( self :: INDENT_REGEX , trim ( $ content ) , $ matches ) ; if ( ! empty ( $ matches ) ) { $ indent = \ strlen ( $ matches [ 1 ] ) ; } return $ indent ; }
Get the indent of file .
1,914
public static function format ( $ json , array $ arrayKeys = array ( ) , $ indent = self :: DEFAULT_INDENT , $ formatJson = true ) { if ( $ formatJson ) { $ json = ComposerJsonFormatter :: format ( $ json , true , true ) ; } if ( 4 !== $ indent ) { $ json = str_replace ( ' ' , sprintf ( '%' . $ indent . 's' , '' ) ,...
Format the data in JSON .
1,915
private static function replaceArrayByMap ( $ json , array $ arrayKeys ) { preg_match_all ( self :: ARRAY_KEYS_REGEX , $ json , $ matches , PREG_SET_ORDER ) ; foreach ( $ matches as $ match ) { if ( ! \ in_array ( $ match [ 1 ] , $ arrayKeys , true ) ) { $ replace = str_replace ( '[]' , '{}' , $ match [ 0 ] ) ; $ json ...
Replace the empty array by empty map .
1,916
private static function getConfigBase ( Composer $ composer , $ io = null ) { $ globalPackageConfig = self :: getGlobalConfig ( $ composer , 'composer' , $ io ) ; $ globalConfig = self :: getGlobalConfig ( $ composer , 'config' , $ io ) ; $ packageConfig = $ composer -> getPackage ( ) -> getConfig ( ) ; $ packageConfig...
Get the base of data .
1,917
public static function validateVersion ( $ requiredVersion , $ composerVersion ) { if ( false === strpos ( $ composerVersion , '@' ) && ! version_compare ( $ composerVersion , $ requiredVersion , '>=' ) ) { $ msg = 'Foxy requires the Composer\'s minimum version "%s", current version is "%s"' ; throw new RuntimeExceptio...
Validate the composer version .
1,918
public static function loadLockPackages ( array $ lockData ) { $ loader = new ArrayLoader ( ) ; $ lockData = static :: loadLockPackage ( $ loader , $ lockData ) ; $ lockData = static :: loadLockPackage ( $ loader , $ lockData , true ) ; $ lockData = static :: convertLockAlias ( $ lockData ) ; return $ lockData ; }
Load all packages in the lock data of locker .
1,919
public static function loadLockPackage ( ArrayLoader $ loader , array $ lockData , $ dev = false ) { $ key = $ dev ? 'packages-dev' : 'packages' ; if ( isset ( $ lockData [ $ key ] ) ) { foreach ( $ lockData [ $ key ] as $ i => $ package ) { $ package = $ loader -> load ( $ package ) ; $ lockData [ $ key ] [ $ i ] = $ ...
Load the packages in the packages section of the locker load data .
1,920
public static function convertLockAlias ( array $ lockData ) { if ( isset ( $ lockData [ 'aliases' ] ) ) { $ aliases = array ( ) ; foreach ( $ lockData [ 'aliases' ] as $ i => $ config ) { $ aliases [ $ config [ 'package' ] ] [ $ config [ 'version' ] ] = array ( 'alias' => $ config [ 'alias' ] , 'alias_normalized' => $...
Convert the package aliases of the locker load data .
1,921
private function parseOriginalContent ( ) { $ content = $ this -> exists ( ) ? file_get_contents ( $ this -> getPath ( ) ) : '' ; $ this -> arrayKeys = JsonFormatter :: getArrayKeys ( $ content ) ; $ this -> indent = JsonFormatter :: getIndent ( $ content ) ; }
Parse the original content .
1,922
public static function getInput ( IOInterface $ io ) { $ ref = new \ ReflectionClass ( $ io ) ; if ( $ ref -> hasProperty ( 'input' ) ) { $ prop = $ ref -> getProperty ( 'input' ) ; $ prop -> setAccessible ( true ) ; $ input = $ prop -> getValue ( $ io ) ; if ( $ input instanceof InputInterface ) { return $ input ; } }...
Get the console input .
1,923
public function getArray ( $ key , array $ default = array ( ) ) { $ value = $ this -> get ( $ key , null ) ; return null !== $ value ? ( array ) $ value : ( array ) $ default ; }
Get the array config value .
1,924
public function get ( $ key , $ default = null ) { if ( \ array_key_exists ( $ key , $ this -> cacheEnv ) ) { return $ this -> cacheEnv [ $ key ] ; } $ envKey = $ this -> convertEnvKey ( $ key ) ; $ envValue = getenv ( $ envKey ) ; if ( false !== $ envValue ) { return $ this -> cacheEnv [ $ key ] = $ this -> convertEnv...
Get the config value .
1,925
private function getDefaultValue ( $ key , $ default = null ) { $ value = null === $ default && \ array_key_exists ( $ key , $ this -> defaults ) ? $ this -> defaults [ $ key ] : $ default ; return $ this -> getByManager ( $ key , $ value , $ default ) ; }
Get the configured default value or custom default value .
1,926
private function getByManager ( $ key , $ value , $ default = null ) { if ( 0 === strpos ( $ key , 'manager-' ) && \ is_array ( $ value ) ) { $ manager = $ manager = $ this -> get ( 'manager' , '' ) ; $ value = \ array_key_exists ( $ manager , $ value ) ? $ value [ $ manager ] : $ default ; } return $ value ; }
Get the value defined by the manager name in the key .
1,927
protected function buildCommand ( $ defaultBin , $ action , $ command ) { $ bin = $ this -> config -> get ( 'manager-bin' , $ defaultBin ) ; $ bin = Platform :: isWindows ( ) ? str_replace ( '/' , '\\' , $ bin ) : $ bin ; $ gOptions = trim ( $ this -> config -> get ( 'manager-options' , '' ) ) ; $ options = trim ( $ th...
Build the command with binary and command options .
1,928
public static function getPath ( InstallationManager $ installationManager , AssetManagerInterface $ assetManager , PackageInterface $ package , array $ configPackages = array ( ) ) { $ path = null ; if ( static :: isAsset ( $ package , $ configPackages ) ) { $ installPath = $ installationManager -> getInstallPath ( $ ...
Get the path of asset file .
1,929
public static function isAsset ( PackageInterface $ package , array $ configPackages = array ( ) ) { $ projectConfig = self :: getProjectActivation ( $ package , $ configPackages ) ; $ enabled = false !== $ projectConfig ; return $ enabled && ( static :: hasExtraActivation ( $ package ) || static :: hasPluginDependency...
Check if the package is available for Foxy .
1,930
public static function hasExtraActivation ( PackageInterface $ package ) { $ extra = $ package -> getExtra ( ) ; return isset ( $ extra [ 'foxy' ] ) && true === $ extra [ 'foxy' ] ; }
Check if foxy is enabled in extra section of package .
1,931
public static function hasPluginDependency ( array $ requires ) { $ assets = false ; foreach ( $ requires as $ require ) { if ( 'foxy/foxy' === $ require -> getTarget ( ) ) { $ assets = true ; break ; } } return $ assets ; }
Check if the package contains assets .
1,932
public static function formatPackage ( PackageInterface $ package , $ packageName , array $ packageValue ) { $ packageValue [ 'name' ] = $ packageName ; if ( ! isset ( $ packageValue [ 'version' ] ) ) { $ extra = $ package -> getExtra ( ) ; $ version = $ package -> getPrettyVersion ( ) ; if ( 0 === strpos ( $ version ,...
Format the asset package .
1,933
private static function formatVersion ( $ version ) { $ version = str_replace ( array ( 'x' , 'X' , '*' ) , '0' , $ version ) ; $ exp = explode ( '.' , $ version ) ; if ( ( $ size = \ count ( $ exp ) ) < 3 ) { for ( $ i = $ size ; $ i < 3 ; ++ $ i ) { $ exp [ ] = '0' ; } } return $ exp [ 0 ] . '.' . $ exp [ 1 ] . '.' ....
Format the version for the asset package .
1,934
private static function getProjectActivation ( PackageInterface $ package , array $ configPackages ) { $ name = $ package -> getName ( ) ; $ value = null ; foreach ( $ configPackages as $ pattern => $ activation ) { if ( \ is_int ( $ pattern ) && \ is_string ( $ activation ) ) { $ pattern = $ activation ; $ activation ...
Get the activation of the package defined in the project config .
1,935
protected function getAssets ( Composer $ composer , $ assetDir , array $ packages ) { $ installationManager = $ composer -> getInstallationManager ( ) ; $ configPackages = $ this -> config -> getArray ( 'enable-packages' ) ; $ assets = array ( ) ; foreach ( $ packages as $ package ) { $ filename = AssetUtil :: getPath...
Get the package of asset dependencies .
1,936
protected function getMockPackagePath ( PackageInterface $ package , $ assetDir , $ filename ) { $ packageName = AssetUtil :: getName ( $ package ) ; $ packagePath = rtrim ( $ assetDir , '/' ) . '/' . $ package -> getName ( ) ; $ newFilename = $ packagePath . '/' . basename ( $ filename ) ; mkdir ( $ packagePath , 0777...
Get the path of the mock package .
1,937
public function solveAssets ( Event $ event ) { $ this -> solver -> setUpdatable ( false !== strpos ( $ event -> getName ( ) , 'update' ) ) ; $ this -> solver -> solve ( $ event -> getComposer ( ) , $ event -> getIO ( ) ) ; }
Solve the assets .
1,938
protected function getAssetManager ( IOInterface $ io , Config $ config , ProcessExecutor $ executor , Filesystem $ fs ) { $ manager = $ config -> get ( 'manager' ) ; foreach ( self :: $ assetManagers as $ class ) { $ am = new $ class ( $ io , $ config , $ executor , $ fs ) ; if ( $ am instanceof AssetManagerInterface ...
Get the asset manager .
1,939
public function typesAndWaits ( IncomingMessage $ matchingMessage , float $ seconds ) { $ this -> replies [ ] = [ 'message' => TypingIndicator :: create ( $ seconds ) , 'additionalParameters' => [ ] , ] ; }
Send a typing indicator and wait for the given amount of seconds .
1,940
public function messagesHandled ( ) { $ messages = $ this -> buildReply ( $ this -> replies ) ; $ this -> replies = [ ] ; Response :: create ( json_encode ( [ 'status' => $ this -> replyStatusCode , 'messages' => $ messages , ] ) , $ this -> replyStatusCode , [ 'Content-Type' => 'application/json' , 'Access-Control-All...
Send out message response .
1,941
protected function addAttachments ( $ incomingMessage ) { $ attachment = $ this -> event -> get ( 'attachment' ) ; if ( $ attachment === self :: ATTACHMENT_IMAGE ) { $ images = $ this -> files -> map ( function ( $ file ) { if ( $ file instanceof UploadedFile ) { $ path = $ file -> getRealPath ( ) ; } else { $ path = $...
Add potential attachments to the message object .
1,942
public function postMessageAction ( Request $ request ) { $ message = null ; $ form = $ this -> formFactory -> createNamed ( null , 'sonata_notification_api_form_message' , $ message , [ 'csrf_protection' => false , ] ) ; $ form -> handleRequest ( $ request ) ; if ( $ form -> isValid ( ) ) { $ message = $ form -> getDa...
Adds a message .
1,943
public function onEvent ( Event $ event = null ) { while ( ! empty ( $ this -> messages ) ) { $ message = array_shift ( $ this -> messages ) ; $ this -> handle ( $ message , $ this -> dispatcher ) ; } }
Listen on any event and handle the messages .
1,944
protected function setCurrent ( ) { if ( 0 === \ count ( $ this -> buffer ) ) { $ this -> bufferize ( $ this -> types ) ; } $ this -> current = array_pop ( $ this -> buffer ) ; }
Assign current pointer a message .
1,945
protected function bufferize ( $ types = [ ] ) { while ( true ) { $ this -> buffer = $ this -> findNextMessages ( $ types ) ; if ( \ count ( $ this -> buffer ) > 0 ) { break ; } usleep ( $ this -> pause ) ; } }
Fill the inner messages buffer .
1,946
protected function findNextMessages ( $ types ) { return $ this -> messageManager -> findByTypes ( $ types , MessageInterface :: STATE_OPEN , $ this -> batchSize ) ; }
Find open messages .
1,947
protected function findNextMessages ( $ types ) { return $ this -> messageManager -> findByAttempts ( $ this -> types , MessageInterface :: STATE_ERROR , $ this -> batchSize , $ this -> maxAttempts , $ this -> attemptDelay ) ; }
Find messages in error .
1,948
protected function formatMessage ( $ message , $ format = [ Console :: FG_RED , Console :: BOLD ] ) { $ stream = ( PHP_SAPI === 'cli' ) ? \ STDERR : \ STDOUT ; if ( $ this -> app -> controller instanceof Controller && $ this -> app -> controller -> isColorEnabled ( $ stream ) || $ this -> app instanceof Application && ...
Colorizes a message for console output .
1,949
public function actionLoad ( array $ fixturesInput = [ ] ) { if ( $ fixturesInput === [ ] ) { $ this -> stdout ( $ this -> getHelpSummary ( ) . "\n" ) ; $ helpCommand = Console :: ansiFormat ( 'yii help fixture' , [ Console :: FG_CYAN ] ) ; $ this -> stdout ( "Use $helpCommand to get usage info.\n" ) ; return ExitCode ...
Loads the specified fixture data .
1,950
public function actionUnload ( array $ fixturesInput = [ ] ) { $ filtered = $ this -> filterFixtures ( $ fixturesInput ) ; $ except = $ filtered [ 'except' ] ; if ( ! $ this -> needToApplyAll ( $ fixturesInput [ 0 ] ) ) { $ fixtures = $ filtered [ 'apply' ] ; $ foundFixtures = $ this -> findFixtures ( $ fixtures ) ; $ ...
Unloads the specified fixtures .
1,951
private function getFixturePath ( ) { try { return $ this -> app -> getAlias ( '@' . str_replace ( '\\' , '/' , $ this -> namespace ) ) ; } catch ( InvalidArgumentException $ e ) { throw new InvalidConfigException ( 'Invalid fixture namespace: "' . $ this -> namespace . '". Please, check your FixtureController::namespa...
Returns fixture path that determined on fixtures namespace .
1,952
public function actionIndex ( ) { $ caches = $ this -> findCaches ( ) ; if ( ! empty ( $ caches ) ) { $ this -> notifyCachesCanBeCleared ( $ caches ) ; } else { $ this -> notifyNoCachesFound ( ) ; } }
Lists the caches that can be cleared .
1,953
public function actionClear ( ) { $ cachesInput = func_get_args ( ) ; if ( empty ( $ cachesInput ) ) { throw new Exception ( 'You should specify cache components names' ) ; } $ caches = $ this -> findCaches ( $ cachesInput ) ; $ cachesInfo = [ ] ; $ foundCaches = array_keys ( $ caches ) ; $ notFoundCaches = array_diff ...
Clears given cache components . For example
1,954
public function actionClearSchema ( $ db = 'db' ) { $ connection = $ this -> app -> get ( $ db , false ) ; if ( $ connection === null ) { $ this -> stdout ( "Unknown component \"$db\".\n" , Console :: FG_RED ) ; return ExitCode :: UNSPECIFIED_ERROR ; } if ( ! $ connection instanceof \ Yiisoft \ Db \ Connection ) { $ th...
Clears DB schema cache for a given connection component .
1,955
private function notifyCachesCanBeCleared ( $ caches ) { $ this -> stdout ( "The following caches were found in the system:\n\n" , Console :: FG_YELLOW ) ; foreach ( $ caches as $ name => $ class ) { if ( $ this -> canBeCleared ( $ class ) ) { $ this -> stdout ( "\t* $name ($class)\n" , Console :: FG_GREEN ) ; } else {...
Notifies user that given caches are found and can be flushed .
1,956
private function confirmClear ( $ cachesNames ) { $ this -> stdout ( "The following cache components will be flushed:\n\n" , Console :: FG_YELLOW ) ; foreach ( $ cachesNames as $ name ) { $ this -> stdout ( "\t* $name \n" , Console :: FG_GREEN ) ; } return $ this -> confirm ( "\nFlush above cache components?" ) ; }
Prompts user with confirmation if caches should be cleared .
1,957
public function actionIndex ( $ address = 'localhost' ) { $ documentRoot = $ this -> app -> getAlias ( $ this -> docroot ) ; if ( strpos ( $ address , ':' ) === false ) { $ address = $ address . ':' . $ this -> port ; } if ( ! is_dir ( $ documentRoot ) ) { $ this -> stdout ( "Document root \"$documentRoot\" does not ex...
Runs PHP built - in web server .
1,958
public function getAssetManager ( ) { if ( ! is_object ( $ this -> _assetManager ) ) { $ options = $ this -> _assetManager ; if ( empty ( $ options [ '__class' ] ) ) { $ options [ '__class' ] = AssetManager :: class ; } if ( ! isset ( $ options [ 'basePath' ] ) ) { throw new Exception ( "Please specify 'basePath' for t...
Returns the asset manager instance .
1,959
protected function loadTargets ( $ targets , $ bundles ) { $ registered = [ ] ; foreach ( $ bundles as $ name => $ bundle ) { $ this -> registerBundle ( $ bundles , $ name , $ registered ) ; } $ bundleOrders = array_combine ( array_keys ( $ registered ) , range ( 0 , count ( $ bundles ) - 1 ) ) ; $ referenced = [ ] ; f...
Creates full list of output asset bundles .
1,960
protected function saveTargets ( $ targets , $ bundleFile ) { $ array = [ ] ; foreach ( $ targets as $ name => $ target ) { if ( isset ( $ this -> targets [ $ name ] ) ) { $ array [ $ name ] = array_merge ( $ this -> targets [ $ name ] , [ '__class' => get_class ( $ target ) , 'sourcePath' => null , 'basePath' => $ thi...
Saves new asset bundles configuration .
1,961
public function getActionOptionsHelp ( $ action ) { $ optionNames = $ this -> options ( $ action -> id ) ; if ( empty ( $ optionNames ) ) { return [ ] ; } $ class = new \ ReflectionClass ( $ this ) ; $ options = [ ] ; foreach ( $ class -> getProperties ( ) as $ property ) { $ name = $ property -> getName ( ) ; if ( ! i...
Returns the help information for the options for the action .
1,962
public function getCommands ( ) { $ commands = $ this -> getModuleCommands ( $ this -> app ) ; sort ( $ commands ) ; return array_unique ( $ commands ) ; }
Returns all available command names .
1,963
protected function validateControllerClass ( $ controllerClass ) { if ( class_exists ( $ controllerClass ) ) { $ class = new \ ReflectionClass ( $ controllerClass ) ; return ! $ class -> isAbstract ( ) && $ class -> isSubclassOf ( Controller :: class ) ; } return false ; }
Validates if the given class is a valid console controller class .
1,964
protected function renderRow ( array $ row , $ spanLeft , $ spanMiddle , $ spanRight ) { $ size = $ this -> _columnWidths ; $ buffer = '' ; $ arrayPointer = [ ] ; $ finalChunk = [ ] ; for ( $ i = 0 , ( $ max = $ this -> calculateRowHeight ( $ row ) ) ? : $ max = 1 ; $ i < $ max ; $ i ++ ) { $ buffer .= $ spanLeft . ' '...
Renders a row of data into a string .
1,965
protected function calculateRowsSize ( ) { $ this -> _columnWidths = $ columns = [ ] ; $ totalWidth = 0 ; $ screenWidth = $ this -> getScreenWidth ( ) - self :: CONSOLE_SCROLLBAR_OFFSET ; for ( $ i = 0 , $ count = count ( $ this -> _headers ) ; $ i < $ count ; $ i ++ ) { $ columns [ ] = ArrayHelper :: getColumn ( $ thi...
Calculate the size of rows to draw anchor of columns in console .
1,966
protected function calculateRowHeight ( $ row ) { $ rowsPerCell = array_map ( function ( $ size , $ columnWidth ) { if ( is_array ( $ columnWidth ) ) { $ rows = 0 ; foreach ( $ columnWidth as $ width ) { $ rows += ceil ( $ width / ( $ size - 2 ) ) ; } return $ rows ; } return ceil ( $ columnWidth / ( $ size - 2 ) ) ; }...
Calculate the height of a row .
1,967
protected function getScreenWidth ( ) { if ( ! $ this -> _screenWidth ) { $ size = Console :: getScreenSize ( ) ; $ this -> _screenWidth = $ size [ 0 ] ?? self :: DEFAULT_CONSOLE_SCREEN_WIDTH + self :: CONSOLE_SCROLLBAR_OFFSET ; } return $ this -> _screenWidth ; }
Getting screen width . If it is not able to determine screen width default value 123 will be set .
1,968
private function filterBySimilarity ( $ actions , $ command ) { $ alternatives = [ ] ; foreach ( $ actions as $ action ) { if ( strpos ( $ action , $ command ) === 0 ) { $ alternatives [ ] = $ action ; } } $ distances = array_map ( function ( $ action ) use ( $ command ) { $ action = strlen ( $ action ) > 255 ? substr ...
Find suggest alternative commands based on string similarity .
1,969
public function actionConfig ( $ filePath ) { $ filePath = $ this -> app -> getAlias ( $ filePath ) ; if ( file_exists ( $ filePath ) ) { if ( ! $ this -> confirm ( "File '{$filePath}' already exists. Do you wish to overwrite it?" ) ) { return ExitCode :: OK ; } } $ array = VarDumper :: export ( $ this -> getOptionValu...
Creates a configuration file for the extract command using command line options specified .
1,970
protected function saveMessagesToPHP ( $ messages , $ dirName , $ overwrite , $ removeUnused , $ sort , $ markUnused ) { foreach ( $ messages as $ category => $ msgs ) { $ file = str_replace ( '\\' , '/' , "$dirName/$category.php" ) ; $ path = dirname ( $ file ) ; FileHelper :: createDirectory ( $ path ) ; $ msgs = arr...
Writes messages into PHP files .
1,971
protected function saveMessagesCategoryToPHP ( $ messages , $ fileName , $ overwrite , $ removeUnused , $ sort , $ category , $ markUnused ) { if ( is_file ( $ fileName ) ) { $ rawExistingMessages = require $ fileName ; $ existingMessages = $ rawExistingMessages ; sort ( $ messages ) ; ksort ( $ existingMessages ) ; if...
Writes category messages into PHP file .
1,972
public function auto ( $ mode = self :: AUTO_ALL ) { Types :: assert ( [ 'int' => [ $ mode ] ] ) ; $ this -> automaticHeaders = $ mode ; }
Enable or disable certain automatically applied header functions
1,973
public function removeHeader ( $ name ) { Types :: assert ( [ 'string' => [ $ name ] ] ) ; $ name = strtolower ( $ name ) ; $ this -> removedHeaders [ $ name ] = true ; }
Queue a header for removal .
1,974
public function protectedCookie ( $ name , $ mode = self :: COOKIE_DEFAULT ) { Types :: assert ( [ 'string|array' => [ $ name ] , 'int' => [ $ mode ] ] ) ; if ( is_string ( $ name ) ) { $ name = strtolower ( $ name ) ; } elseif ( is_array ( $ name ) ) { foreach ( $ name as $ cookie ) { $ this -> protectedCookie ( $ coo...
Configure which cookies SecureHeaders will regard as protected .
1,975
public function removeCSPSource ( $ directive , $ source , $ reportOnly = null ) { Types :: assert ( [ 'string' => [ $ directive , $ source ] ] ) ; $ csp = & $ this -> getCSPObject ( $ reportOnly ) ; $ source = strtolower ( $ source ) ; $ directive = strtolower ( $ directive ) ; if ( ! isset ( $ csp [ $ directive ] [ $...
Remove a previously added source from a CSP directive .
1,976
public function removeCSPDirective ( $ directive , $ reportOnly = null ) { Types :: assert ( [ 'string' => [ $ directive ] ] ) ; $ csp = & $ this -> getCSPObject ( $ reportOnly ) ; $ directive = strtolower ( $ directive ) ; if ( ! isset ( $ csp [ $ directive ] ) ) { return false ; } unset ( $ csp [ $ directive ] ) ; re...
Remove a previously added directive from CSP .
1,977
public function expectCT ( $ maxAge = 31536000 , $ enforce = true , $ reportUri = null ) { Types :: assert ( [ '?int|?string' => [ $ maxAge ] , '?string' => [ $ reportUri ] ] , [ 1 , 3 ] ) ; if ( isset ( $ maxAge ) or ! isset ( $ this -> expectCT [ 'max-age' ] ) ) { $ this -> expectCT [ 'max-age' ] = $ maxAge ; } if ( ...
Used to add and configure the Expect - CT header .
1,978
public function hsts ( $ maxAge = 31536000 , $ subdomains = false , $ preload = false ) { Types :: assert ( [ 'int|string' => [ $ maxAge ] ] ) ; $ this -> hsts [ 'max-age' ] = $ maxAge ; $ this -> hsts [ 'subdomains' ] = ( $ subdomains == true ) ; $ this -> hsts [ 'preload' ] = ( $ preload == true ) ; }
Used to add and configure the Strict - Transport - Security header .
1,979
public function hpkp ( $ pins , $ maxAge = null , $ subdomains = null , $ reportUri = null , $ reportOnly = null ) { Types :: assert ( [ 'string|array' => [ $ pins ] , '?int|?string' => [ $ maxAge ] , '?string' => [ $ reportUri ] ] , [ 1 , 2 , 4 ] ) ; $ hpkp = & $ this -> getHPKPObject ( $ reportOnly ) ; if ( isset ( $...
Add and configure the HTTP Public Key Pins header .
1,980
public function apply ( HttpAdapter $ http = null ) { if ( is_null ( $ http ) ) { $ http = new GlobalHttpAdapter ( ) ; } $ headers = $ http -> getHeaders ( ) ; foreach ( $ this -> pipeline ( ) as $ operation ) { $ operation -> modify ( $ headers ) ; if ( $ operation instanceof ExposesErrors ) { $ this -> errors = array...
Calling this function will initiate the following
1,981
private function validateHeaders ( HeaderBag $ headers ) { $ this -> errors = array_merge ( $ this -> errors , Validator :: validate ( $ headers ) ) ; }
Validate headers in the HeaderBag and store any errors internally .
1,982
private function & getCSPObject ( $ reportOnly ) { if ( ! isset ( $ reportOnly ) or ! $ reportOnly ) { $ csp = & $ this -> csp ; } else { $ csp = & $ this -> cspro ; } return $ csp ; }
Retrieve a reference to either the CSP enforcement or CSP report only array .
1,983
private function cspGenerateNonce ( ) { $ nonce = base64_encode ( openssl_random_pseudo_bytes ( 30 , $ isCryptoStrong ) ) ; if ( ! $ isCryptoStrong ) { $ this -> addError ( 'OpenSSL (openssl_random_pseudo_bytes) reported that it did <strong>not</strong> use a cryptographically strong algorithm ...
Generate a nonce for insertion in a CSP .
1,984
private function & getHPKPObject ( $ reportOnly ) { if ( ! isset ( $ reportOnly ) or ! $ reportOnly ) { $ hpkp = & $ this -> hpkp ; } else { $ hpkp = & $ this -> hpkpro ; } return $ hpkp ; }
Retrieve a reference to either the HPKP enforcement or HPKP report only array .
1,985
private function addError ( $ message , $ level = E_USER_NOTICE ) { Types :: assert ( [ 'string' => [ $ message ] , 'int' => [ $ level ] ] ) ; $ this -> errors [ ] = new Error ( $ message , $ level ) ; }
Add and store an error internally .
1,986
private function injectableSameSiteValue ( ) { if ( ! isset ( $ this -> sameSiteCookies ) and $ this -> strictMode ) { $ sameSite = 'Strict' ; } elseif ( ! isset ( $ this -> sameSiteCookies ) ) { $ sameSite = 'Lax' ; } else { $ sameSite = $ this -> sameSiteCookies ; } return $ sameSite ; }
Determine the appropriate sameSite value to inject .
1,987
private function errorHandler ( $ level , $ message ) { Types :: assert ( [ 'int' => [ $ level ] , 'string' => [ $ message ] ] ) ; if ( error_reporting ( ) & $ level and ( strtolower ( ini_get ( 'display_errors' ) ) === 'on' and ini_get ( 'display_errors' ) ) ) { if ( $ level === E_USER_NOTICE ) { $ error = '<strong>No...
Echo an error iff PHPs settings allow error reporting at the level of errors given and PHPs display_errors setting is on . Will return true if an error is echoed false otherwise .
1,988
public static function validate ( HeaderBag $ headers ) { $ errors = [ ] ; foreach ( self :: $ delegates as $ delegate => $ headerList ) { $ class = self :: VALIDATOR_NAMESPACE . '\\' . $ delegate ; if ( ! is_array ( $ headerList ) ) { $ headerList = [ $ headerList ] ; } foreach ( $ headerList as $ headerName ) { $ hea...
Validate the given headers
1,989
private static function validateSrcAttribute ( Header $ header , $ attributeName ) { Types :: assert ( [ 'string' => [ $ attributeName ] ] , [ 2 ] ) ; $ Errors = [ ] ; if ( $ header -> hasAttribute ( $ attributeName ) ) { $ value = $ header -> getAttributeValue ( $ attributeName ) ; $ badFlags = [ "'unsafe-inline'" , "...
Find bad flags in the given attribute
1,990
private static function enumerateWildcards ( Header $ header , $ directive , $ sources ) { Types :: assert ( [ 'string' => [ $ directive , $ sources ] ] , [ 2 , 3 ] ) ; if ( preg_match_all ( self :: CSP_SOURCE_WILDCARD_RE , $ sources , $ matches ) ) { if ( ! in_array ( $ directive , self :: $ cspSensitiveDirectives ) )...
Find wildcards in CSP directives
1,991
private static function enumerateNonHttps ( Header $ header , $ directive , $ sources ) { Types :: assert ( [ 'string' => [ $ directive , $ sources ] ] , [ 2 , 3 ] ) ; if ( preg_match_all ( '/(?:[ ]|^)\Khttp[:][^ ]*/' , $ sources , $ matches ) ) { $ friendlyHeader = $ header -> getFriendlyName ( ) ; return new Error ( ...
Find non secure origins in CSP directives
1,992
private function compileCSPRO ( ) { $ filteredConfig = array_diff_key ( $ this -> csproConfig , array_flip ( $ this -> csproBlacklist ) ) ; return self :: compile ( $ filteredConfig ) ; }
Compile internal CSPRO config into a CSP header - value string
1,993
public static function mergeCSPList ( array $ cspList ) { $ finalCSP = [ ] ; foreach ( $ cspList as $ csp ) { foreach ( $ csp as $ directive => $ sources ) { if ( ! isset ( $ finalCSP [ $ directive ] ) ) { $ finalCSP [ $ directive ] = $ sources ; continue ; } elseif ( $ finalCSP [ $ directive ] === true ) { continue ; ...
Merge a multiple CSP configs together into a single CSP
1,994
protected function parseAttributes ( ) { $ parts = explode ( '; ' , $ this -> value ) ; $ this -> attributes = [ ] ; foreach ( $ parts as $ part ) { $ attrParts = explode ( '=' , $ part , 2 ) ; $ type = strtolower ( $ attrParts [ 0 ] ) ; if ( ! isset ( $ this -> attributes [ $ type ] ) ) { $ this -> attributes [ $ type...
Parse and store attributes from the internal header value
1,995
protected function writeAttributesToValue ( ) { $ attributeStrings = [ ] ; foreach ( $ this -> attributes as $ attributes ) { foreach ( $ attributes as $ attrInfo ) { $ key = $ attrInfo [ 'name' ] ; $ value = $ attrInfo [ 'value' ] ; if ( $ value === true ) { $ string = $ key ; } elseif ( $ value === false ) { continue...
Write internal attributes to the internal header value
1,996
private function makeHeaderValue ( ) { $ pieces = [ 'max-age=' . $ this -> config [ 'max-age' ] ] ; if ( $ this -> config [ 'subdomains' ] ) { $ pieces [ ] = 'includeSubDomains' ; } if ( $ this -> config [ 'preload' ] ) { $ pieces [ ] = 'preload' ; } return implode ( '; ' , $ pieces ) ; }
Make the HSTS header value
1,997
private function canInjectStrictDynamic ( Header $ header ) { if ( $ header -> hasAttribute ( $ directive = 'script-src' ) or $ header -> hasAttribute ( $ directive = 'default-src' ) ) { if ( preg_match ( "/(?:^|\s)(?:'strict-dynamic'|'none')(?:$|\s)/i" , $ header -> getAttributeValue ( $ directive ) ) ) { return - 1 ;...
Determine which directive strict - dynamic may be injected into if any . If Safe - Mode conflicts - 1 will be returned . If strict - dynamic cannot be injected false will be returned .
1,998
public function register ( Container $ container ) { if ( ! isset ( $ container [ 'console' ] ) ) { throw new \ LogicException ( 'You must register the ConsoleServiceProvider to use the WebServerServiceProvider.' ) ; } $ container [ 'web_server.document_root' ] = null ; $ container [ 'web_server.environment' ] = 'dev' ...
Registers the web server console commands .
1,999
public function register ( Container $ app ) { $ app [ 'console.name' ] = 'Silex console' ; $ app [ 'console.version' ] = 'UNKNOWN' ; $ app [ 'console.project_directory' ] = __DIR__ . '/../../../../..' ; $ app [ 'console.class' ] = ConsoleApplication :: class ; $ app [ 'console.command.ids' ] = [ ] ; $ app [ 'console.b...
Registers the service provider .