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 ( $ e -> getMessage ( ) , null , $ e ) ; } if ( ( $ tokenSize = mb_strlen ( $ token , '8bit' ) ) > static :: MAX_TOKEN_SIZE ) { throw new TokenException ( sprintf ( 'The generated token is larger than %d bytes (%d)' , static :: MAX_TOKEN_SIZE , $ tokenSize ) ) ; } return $ token ; }
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' ] = $ value -> getTimestamp ( ) ; } break ; default : $ claims [ $ name ] = $ value ; break ; } } return $ claims ; }
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 longer than %d bytes (%d).' , static :: MAX_UID_SIZE , $ uidSize ) ) ; } if ( 0 === $ uidSize ) { throw new TokenException ( 'The provided uid is empty.' ) ; } }
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 instanceof $ exceptionType ) ) { continue ; } if ( ! class_exists ( $ formatter ) || ! ( new ReflectionClass ( $ formatter ) ) -> isSubclassOf ( new ReflectionClass ( BaseFormatter :: class ) ) ) { throw new InvalidArgumentException ( sprintf ( "%s is not a valid formatter class." , $ formatter ) ) ; } $ formatterInstance = new $ formatter ( $ this -> config , $ this -> debug ) ; $ formatterInstance -> format ( $ response , $ e , $ this -> reportResponses ) ; break ; } return $ response ; }
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 [ 'private' ] ) ) { $ this -> package [ 'private' ] = true ; } } else { $ this -> package [ 'license' ] = $ license ; } } }
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 ( 'aliases' , array ( ) ) , $ this -> getLockValue ( 'minimum-stability' ) , $ this -> getLockValue ( 'stability-flags' , array ( ) ) , $ this -> getLockValue ( 'prefer-stable' , false ) , $ this -> getLockValue ( 'prefer-lowest' , false ) , $ this -> getLockValue ( 'platform-overrides' , array ( ) ) ) ; return $ this -> composer -> getLocker ( ) -> isLocked ( ) ; }
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-autoloader' ) ; $ authoritative = $ this -> input -> getOption ( 'classmap-authoritative' ) || $ config -> get ( 'classmap-authoritative' ) ; $ apcu = $ this -> input -> getOption ( 'apcu-autoloader' ) || $ config -> get ( 'apcu-autoloader' ) ; $ this -> getInstaller ( ) -> setVerbose ( $ this -> input -> getOption ( 'verbose' ) ) -> setPreferSource ( $ preferSource ) -> setPreferDist ( $ preferDist ) -> setDevMode ( ! $ this -> input -> getOption ( 'no-dev' ) ) -> setDumpAutoloader ( ! $ this -> input -> getOption ( 'no-autoloader' ) ) -> setRunScripts ( false ) -> setSkipSuggest ( true ) -> setOptimizeAutoloader ( $ optimize ) -> setClassMapAuthoritative ( $ authoritative ) -> setApcuAutoloader ( $ apcu ) -> setIgnorePlatformRequirements ( $ this -> input -> getOption ( 'ignore-platform-reqs' ) ) -> run ( ) ; }
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' , '' ) , $ json ) ; } return self :: replaceArrayByMap ( $ json , $ arrayKeys ) ; }
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 = str_replace ( $ match [ 0 ] , $ replace , $ json ) ; } } return $ 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 = isset ( $ packageConfig [ 'foxy' ] ) && \ is_array ( $ packageConfig [ 'foxy' ] ) ? $ packageConfig [ 'foxy' ] : array ( ) ; return array_merge ( $ globalPackageConfig , $ globalConfig , $ 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 RuntimeException ( sprintf ( $ msg , $ requiredVersion , $ composerVersion ) ) ; } }
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 ] = $ package instanceof AliasPackage ? $ package -> getAliasOf ( ) : $ package ; } } return $ lockData ; }
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' => $ config [ 'alias_normalized' ] , ) ; } $ lockData [ 'aliases' ] = $ aliases ; } return $ lockData ; }
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 ; } } return new ArgvInput ( ) ; }
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 -> convertEnvValue ( $ envValue , $ envKey ) ; } $ defaultValue = $ this -> getDefaultValue ( $ key , $ default ) ; return \ array_key_exists ( $ key , $ this -> config ) ? $ this -> getByManager ( $ key , $ this -> config [ $ key ] , $ defaultValue ) : $ defaultValue ; }
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 ( $ this -> config -> get ( 'manager-' . $ action . '-options' , '' ) ) ; return $ bin . ' ' . $ command . ( empty ( $ gOptions ) ? '' : ' ' . $ gOptions ) . ( empty ( $ options ) ? '' : ' ' . $ options ) ; }
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 ( $ package ) ; $ filename = $ installPath . '/' . $ assetManager -> getPackageName ( ) ; $ path = file_exists ( $ filename ) ? str_replace ( '\\' , '/' , realpath ( $ filename ) ) : null ; } return $ path ; }
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 ( $ package -> getRequires ( ) ) || static :: hasPluginDependency ( $ package -> getDevRequires ( ) ) || true === $ projectConfig ) ; }
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 , 'dev-' ) && isset ( $ extra [ 'branch-alias' ] [ $ version ] ) ) { $ version = $ extra [ 'branch-alias' ] [ $ version ] ; } $ packageValue [ 'version' ] = self :: formatVersion ( str_replace ( '-dev' , '' , $ version ) ) ; } return $ packageValue ; }
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 ] . '.' . $ exp [ 2 ] ; }
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 = true ; } if ( ( 0 === strpos ( $ pattern , '/' ) && preg_match ( $ pattern , $ name ) ) || fnmatch ( $ pattern , $ name ) ) { $ value = $ activation ; break ; } } return $ value ; }
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 ( $ installationManager , $ this -> assetManager , $ package , $ configPackages ) ; if ( null !== $ filename ) { list ( $ packageName , $ packagePath ) = $ this -> getMockPackagePath ( $ package , $ assetDir , $ filename ) ; $ assets [ $ packageName ] = $ packagePath ; } } $ assetsEvent = new GetAssetsEvent ( $ assetDir , $ packages , $ assets ) ; $ composer -> getEventDispatcher ( ) -> dispatch ( FoxyEvents :: GET_ASSETS , $ assetsEvent ) ; return $ assetsEvent -> getAssets ( ) ; }
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 , true ) ; copy ( $ filename , $ newFilename ) ; $ jsonFile = new JsonFile ( $ newFilename ) ; $ packageValue = AssetUtil :: formatPackage ( $ package , $ packageName , ( array ) $ jsonFile -> read ( ) ) ; $ jsonFile -> write ( $ packageValue ) ; return array ( $ packageName , $ this -> fs -> findShortestPath ( getcwd ( ) , $ newFilename ) ) ; }
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 && $ manager === $ am -> getName ( ) ) { return $ am ; } } throw new RuntimeException ( sprintf ( 'The asset manager "%s" doesn\'t exist' , $ manager ) ) ; }
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-Allow-Credentials' => true , 'Access-Control-Allow-Origin' => '*' , ] ) -> send ( ) ; }
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 = $ file [ 'tmp_name' ] ; } return new Image ( $ this -> getDataURI ( $ path ) ) ; } ) -> values ( ) -> toArray ( ) ; $ incomingMessage -> setText ( Image :: PATTERN ) ; $ incomingMessage -> setImages ( $ images ) ; } elseif ( $ attachment === self :: ATTACHMENT_AUDIO ) { $ audio = $ this -> files -> map ( function ( $ file ) { if ( $ file instanceof UploadedFile ) { $ path = $ file -> getRealPath ( ) ; } else { $ path = $ file [ 'tmp_name' ] ; } return new Audio ( $ this -> getDataURI ( $ path ) ) ; } ) -> values ( ) -> toArray ( ) ; $ incomingMessage -> setText ( Audio :: PATTERN ) ; $ incomingMessage -> setAudio ( $ audio ) ; } elseif ( $ attachment === self :: ATTACHMENT_VIDEO ) { $ videos = $ this -> files -> map ( function ( $ file ) { if ( $ file instanceof UploadedFile ) { $ path = $ file -> getRealPath ( ) ; } else { $ path = $ file [ 'tmp_name' ] ; } return new Video ( $ this -> getDataURI ( $ path ) ) ; } ) -> values ( ) -> toArray ( ) ; $ incomingMessage -> setText ( Video :: PATTERN ) ; $ incomingMessage -> setVideos ( $ videos ) ; } elseif ( $ attachment === self :: ATTACHMENT_FILE ) { $ files = $ this -> files -> map ( function ( $ file ) { if ( $ file instanceof UploadedFile ) { $ path = $ file -> getRealPath ( ) ; } else { $ path = $ file [ 'tmp_name' ] ; } return new File ( $ this -> getDataURI ( $ path ) ) ; } ) -> values ( ) -> toArray ( ) ; $ incomingMessage -> setText ( File :: PATTERN ) ; $ incomingMessage -> setFiles ( $ files ) ; } return $ incomingMessage ; }
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 -> getData ( ) ; $ this -> messageManager -> save ( $ message ) ; return $ message ; } return $ form ; }
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 && Console :: streamSupportsAnsiColors ( $ stream ) ) { $ message = Console :: ansiFormat ( $ message , $ format ) ; } return $ message ; }
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 :: OK ; } $ filtered = $ this -> filterFixtures ( $ fixturesInput ) ; $ except = $ filtered [ 'except' ] ; if ( ! $ this -> needToApplyAll ( $ fixturesInput [ 0 ] ) ) { $ fixtures = $ filtered [ 'apply' ] ; $ foundFixtures = $ this -> findFixtures ( $ fixtures ) ; $ notFoundFixtures = array_diff ( $ fixtures , $ foundFixtures ) ; if ( $ notFoundFixtures ) { $ this -> notifyNotFound ( $ notFoundFixtures ) ; } } else { $ foundFixtures = $ this -> findFixtures ( ) ; } $ fixturesToLoad = array_diff ( $ foundFixtures , $ except ) ; if ( ! $ foundFixtures ) { throw new Exception ( 'No files were found for: "' . implode ( ', ' , $ fixturesInput ) . "\".\n" . "Check that files exist under fixtures path: \n\"" . $ this -> getFixturePath ( ) . '".' ) ; } if ( ! $ fixturesToLoad ) { $ this -> notifyNothingToLoad ( $ foundFixtures , $ except ) ; return ExitCode :: OK ; } if ( ! $ this -> confirmLoad ( $ fixturesToLoad , $ except ) ) { return ExitCode :: OK ; } $ fixtures = $ this -> getFixturesConfig ( array_merge ( $ this -> globalFixtures , $ fixturesToLoad ) ) ; if ( ! $ fixtures ) { throw new Exception ( 'No fixtures were found in namespace: "' . $ this -> namespace . '"' . '' ) ; } $ fixturesObjects = $ this -> createFixtures ( $ fixtures ) ; $ this -> unloadFixtures ( $ fixturesObjects ) ; $ this -> loadFixtures ( $ fixturesObjects ) ; $ this -> notifyLoaded ( $ fixtures ) ; return ExitCode :: OK ; }
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 ) ; $ notFoundFixtures = array_diff ( $ fixtures , $ foundFixtures ) ; if ( $ notFoundFixtures ) { $ this -> notifyNotFound ( $ notFoundFixtures ) ; } } else { $ foundFixtures = $ this -> findFixtures ( ) ; } $ fixturesToUnload = array_diff ( $ foundFixtures , $ except ) ; if ( ! $ foundFixtures ) { throw new Exception ( 'No files were found for: "' . implode ( ', ' , $ fixturesInput ) . "\".\n" . "Check that files exist under fixtures path: \n\"" . $ this -> getFixturePath ( ) . '".' ) ; } if ( ! $ fixturesToUnload ) { $ this -> notifyNothingToUnload ( $ foundFixtures , $ except ) ; return ExitCode :: OK ; } if ( ! $ this -> confirmUnload ( $ fixturesToUnload , $ except ) ) { return ExitCode :: OK ; } $ fixtures = $ this -> getFixturesConfig ( array_merge ( $ this -> globalFixtures , $ fixturesToUnload ) ) ; if ( ! $ fixtures ) { throw new Exception ( 'No fixtures were found in namespace: ' . $ this -> namespace . '".' ) ; } $ this -> unloadFixtures ( $ this -> createFixtures ( $ fixtures ) ) ; $ this -> notifyUnloaded ( $ 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::namespace parameter' ) ; } }
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 ( $ cachesInput , array_keys ( $ caches ) ) ; if ( $ notFoundCaches ) { $ this -> notifyNotFoundCaches ( $ notFoundCaches ) ; } if ( ! $ foundCaches ) { $ this -> notifyNoCachesFound ( ) ; return ExitCode :: OK ; } if ( ! $ this -> confirmClear ( $ foundCaches ) ) { return ExitCode :: OK ; } foreach ( $ caches as $ name => $ class ) { $ cachesInfo [ ] = [ 'name' => $ name , 'class' => $ class , 'is_flushed' => $ this -> canBeCleared ( $ class ) ? $ this -> app -> get ( $ name ) -> clear ( ) : false , ] ; } $ this -> notifyCleared ( $ cachesInfo ) ; }
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 ) { $ this -> stdout ( "\"$db\" component doesn't inherit \\Yiisoft\\Db\\Connection.\n" , Console :: FG_RED ) ; return ExitCode :: UNSPECIFIED_ERROR ; } elseif ( ! $ this -> confirm ( "Flush cache schema for \"$db\" connection?" ) ) { return ExitCode :: OK ; } try { $ schema = $ connection -> getSchema ( ) ; $ schema -> refresh ( ) ; $ this -> stdout ( "Schema cache for component \"$db\", was flushed.\n\n" , Console :: FG_GREEN ) ; } catch ( \ Exception $ e ) { $ this -> stdout ( $ e -> getMessage ( ) . "\n\n" , Console :: FG_RED ) ; } }
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 { $ this -> stdout ( "\t* $name ($class) - can not be flushed via console\n" , Console :: FG_YELLOW ) ; } } $ this -> stdout ( "\n" ) ; }
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 exist.\n" , Console :: FG_RED ) ; return self :: EXIT_CODE_NO_DOCUMENT_ROOT ; } if ( $ this -> isAddressTaken ( $ address ) ) { $ this -> stdout ( "http://$address is taken by another process.\n" , Console :: FG_RED ) ; return self :: EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS ; } if ( $ this -> router !== null && ! file_exists ( $ this -> router ) ) { $ this -> stdout ( "Routing file \"$this->router\" does not exist.\n" , Console :: FG_RED ) ; return self :: EXIT_CODE_NO_ROUTING_FILE ; } $ this -> stdout ( "Server started on http://{$address}/\n" ) ; $ this -> stdout ( "Document root is \"{$documentRoot}\"\n" ) ; if ( $ this -> router ) { $ this -> stdout ( "Routing file is \"$this->router\"\n" ) ; } $ this -> stdout ( "Quit the server with CTRL-C or COMMAND-C.\n" ) ; passthru ( '"' . PHP_BINARY . '"' . " -S {$address} -t \"{$documentRoot}\" $this->router" ) ; }
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 the 'assetManager' option." ) ; } if ( ! isset ( $ options [ 'baseUrl' ] ) ) { throw new Exception ( "Please specify 'baseUrl' for the 'assetManager' option." ) ; } if ( ! isset ( $ options [ 'forceCopy' ] ) ) { $ options [ 'forceCopy' ] = true ; } $ this -> _assetManager = $ this -> app -> createObject ( $ options ) ; } return $ this -> _assetManager ; }
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 = [ ] ; foreach ( $ targets as $ name => $ target ) { if ( empty ( $ target [ 'depends' ] ) ) { if ( ! isset ( $ all ) ) { $ all = $ name ; } else { throw new Exception ( "Only one target can have empty 'depends' option. Found two now: $all, $name" ) ; } } else { foreach ( $ target [ 'depends' ] as $ bundle ) { if ( ! isset ( $ referenced [ $ bundle ] ) ) { $ referenced [ $ bundle ] = $ name ; } else { throw new Exception ( "Target '{$referenced[$bundle]}' and '$name' cannot contain the bundle '$bundle' at the same time." ) ; } } } } if ( isset ( $ all ) ) { $ targets [ $ all ] [ 'depends' ] = array_diff ( array_keys ( $ registered ) , array_keys ( $ referenced ) ) ; } foreach ( $ targets as $ name => $ target ) { if ( ! isset ( $ target [ 'basePath' ] ) ) { throw new Exception ( "Please specify 'basePath' for the '$name' target." ) ; } if ( ! isset ( $ target [ 'baseUrl' ] ) ) { throw new Exception ( "Please specify 'baseUrl' for the '$name' target." ) ; } usort ( $ target [ 'depends' ] , function ( $ a , $ b ) use ( $ bundleOrders ) { if ( $ bundleOrders [ $ a ] == $ bundleOrders [ $ b ] ) { return 0 ; } return $ bundleOrders [ $ a ] > $ bundleOrders [ $ b ] ? 1 : - 1 ; } ) ; if ( ! isset ( $ target [ '__class' ] ) ) { $ target [ '__class' ] = $ name ; } $ targets [ $ name ] = $ this -> app -> createObject ( $ target ) ; } return $ targets ; }
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' => $ this -> targets [ $ name ] [ 'basePath' ] , 'baseUrl' => $ this -> targets [ $ name ] [ 'baseUrl' ] , 'js' => $ target -> js , 'css' => $ target -> css , 'depends' => [ ] , ] ) ; } else { if ( $ this -> isBundleExternal ( $ target ) ) { $ array [ $ name ] = $ this -> composeBundleConfig ( $ target ) ; } else { $ array [ $ name ] = [ 'sourcePath' => null , 'js' => [ ] , 'css' => [ ] , 'depends' => $ target -> depends , ] ; } } } $ array = VarDumper :: export ( $ array ) ; $ version = date ( 'Y-m-d H:i:s' ) ; $ bundleFileContent = <<<EOD<?php/** * This file is generated by the "yii {$this->id}" command. * DO NOT MODIFY THIS FILE DIRECTLY. * @version {$version} */return {$array};EOD ; if ( ! file_put_contents ( $ bundleFile , $ bundleFileContent , LOCK_EX ) ) { throw new Exception ( "Unable to write output bundle configuration at '{$bundleFile}'." ) ; } $ this -> stdout ( "Output bundle configuration created at '{$bundleFile}'.\n" , Console :: FG_GREEN ) ; }
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 ( ! in_array ( $ name , $ optionNames , true ) ) { continue ; } $ defaultValue = $ property -> getValue ( $ this ) ; $ tags = $ this -> parseDocCommentTags ( $ property ) ; $ name = InflectorHelper :: camel2id ( $ name , '-' , true ) ; if ( isset ( $ tags [ 'var' ] ) || isset ( $ tags [ 'property' ] ) ) { $ doc = $ tags [ 'var' ] ?? $ tags [ 'property' ] ; if ( is_array ( $ doc ) ) { $ doc = reset ( $ doc ) ; } if ( preg_match ( '/^(\S+)(.*)/s' , $ doc , $ matches ) ) { $ type = $ matches [ 1 ] ; $ comment = $ matches [ 2 ] ; } else { $ type = null ; $ comment = $ doc ; } $ options [ $ name ] = [ 'type' => $ type , 'default' => $ defaultValue , 'comment' => $ comment , ] ; } else { $ options [ $ name ] = [ 'type' => null , 'default' => $ defaultValue , 'comment' => '' , ] ; } } return $ options ; }
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 . ' ' ; foreach ( $ size as $ index => $ cellSize ) { $ cell = $ row [ $ index ] ?? null ; $ prefix = '' ; if ( $ index !== 0 ) { $ buffer .= $ spanMiddle . ' ' ; } if ( is_array ( $ cell ) ) { if ( empty ( $ finalChunk [ $ index ] ) ) { $ finalChunk [ $ index ] = '' ; $ start = 0 ; $ prefix = $ this -> _listPrefix ; if ( ! isset ( $ arrayPointer [ $ index ] ) ) { $ arrayPointer [ $ index ] = 0 ; } } else { $ start = mb_strwidth ( $ finalChunk [ $ index ] , $ this -> app -> encoding ) ; } $ chunk = mb_substr ( $ cell [ $ arrayPointer [ $ index ] ] , $ start , $ cellSize - 4 , $ this -> app -> encoding ) ; $ finalChunk [ $ index ] .= $ chunk ; if ( isset ( $ cell [ $ arrayPointer [ $ index ] + 1 ] ) && $ finalChunk [ $ index ] === $ cell [ $ arrayPointer [ $ index ] ] ) { $ arrayPointer [ $ index ] ++ ; $ finalChunk [ $ index ] = '' ; } } else { $ chunk = mb_substr ( $ cell , ( $ cellSize * $ i ) - ( $ i * 2 ) , $ cellSize - 2 , $ this -> app -> encoding ) ; } $ chunk = $ prefix . $ chunk ; $ repeat = $ cellSize - mb_strwidth ( $ chunk , $ this -> app -> encoding ) - 1 ; $ buffer .= $ chunk ; if ( $ repeat >= 0 ) { $ buffer .= str_repeat ( ' ' , $ repeat ) ; } } $ buffer .= "$spanRight\n" ; } return $ buffer ; }
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 ( $ this -> _rows , $ i ) ; $ columns [ $ i ] [ ] = $ this -> _headers [ $ i ] ; } foreach ( $ columns as $ column ) { $ columnWidth = max ( array_map ( function ( $ val ) { if ( is_array ( $ val ) ) { $ encodings = array_fill ( 0 , count ( $ val ) , $ this -> app -> encoding ) ; return max ( array_map ( 'mb_strwidth' , $ val , $ encodings ) ) + mb_strwidth ( $ this -> _listPrefix , $ this -> app -> encoding ) ; } return mb_strwidth ( $ val , $ this -> app -> encoding ) ; } , $ column ) ) + 2 ; $ this -> _columnWidths [ ] = $ columnWidth ; $ totalWidth += $ columnWidth ; } $ relativeWidth = $ screenWidth / $ totalWidth ; if ( $ totalWidth > $ screenWidth ) { foreach ( $ this -> _columnWidths as $ j => $ width ) { $ this -> _columnWidths [ $ j ] = ( int ) ( $ width * $ relativeWidth ) ; if ( $ j === count ( $ this -> _columnWidths ) ) { $ this -> _columnWidths = $ totalWidth ; } $ totalWidth -= $ this -> _columnWidths [ $ j ] ; } } }
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 ) ) ; } , $ this -> _columnWidths , array_map ( function ( $ val ) { if ( is_array ( $ val ) ) { $ encodings = array_fill ( 0 , count ( $ val ) , $ this -> app -> encoding ) ; return array_map ( 'mb_strwidth' , $ val , $ encodings ) ; } return mb_strwidth ( $ val , $ this -> app -> encoding ) ; } , $ row ) ) ; return max ( $ rowsPerCell ) ; }
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 ( $ action , 0 , 255 ) : $ action ; $ command = strlen ( $ command ) > 255 ? substr ( $ command , 0 , 255 ) : $ command ; return levenshtein ( $ action , $ command ) ; } , array_combine ( $ actions , $ actions ) ) ; $ relevantTypos = array_filter ( $ distances , function ( $ distance ) { return $ distance <= 3 ; } ) ; asort ( $ relevantTypos ) ; $ alternatives = array_merge ( $ alternatives , array_flip ( $ relevantTypos ) ) ; return array_unique ( $ alternatives ) ; }
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 -> getOptionValues ( $ this -> action -> id ) ) ; $ content = <<<EOD<?php/** * Configuration file for 'yii {$this->id}/{$this->defaultAction}' command. * * This file is automatically generated by 'yii {$this->id}/{$this->action->id}' command. * It contains parameters for source code messages extraction. * You may modify this file to suit your needs. * * You can use 'yii {$this->id}/{$this->action->id}-template' command to create * template configuration file with detailed description for each parameter. */return $array;EOD ; if ( file_put_contents ( $ filePath , $ content , LOCK_EX ) === false ) { $ this -> stdout ( "Configuration file was NOT created: '{$filePath}'.\n\n" , Console :: FG_RED ) ; return ExitCode :: UNSPECIFIED_ERROR ; } $ this -> stdout ( "Configuration file created: '{$filePath}'.\n\n" , Console :: FG_GREEN ) ; return ExitCode :: OK ; }
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 = array_values ( array_unique ( $ msgs ) ) ; $ coloredFileName = Console :: ansiFormat ( $ file , [ Console :: FG_CYAN ] ) ; $ this -> stdout ( "Saving messages to $coloredFileName...\n" ) ; $ this -> saveMessagesCategoryToPHP ( $ msgs , $ file , $ overwrite , $ removeUnused , $ sort , $ category , $ markUnused ) ; } }
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 ( array_keys ( $ existingMessages ) === $ messages && ( ! $ sort || array_keys ( $ rawExistingMessages ) === $ messages ) ) { $ this -> stdout ( "Nothing new in \"$category\" category... Nothing to save.\n\n" , Console :: FG_GREEN ) ; return ExitCode :: OK ; } unset ( $ rawExistingMessages ) ; $ merged = [ ] ; $ untranslated = [ ] ; foreach ( $ messages as $ message ) { if ( array_key_exists ( $ message , $ existingMessages ) && $ existingMessages [ $ message ] !== '' ) { $ merged [ $ message ] = $ existingMessages [ $ message ] ; } else { $ untranslated [ ] = $ message ; } } ksort ( $ merged ) ; sort ( $ untranslated ) ; $ todo = [ ] ; foreach ( $ untranslated as $ message ) { $ todo [ $ message ] = '' ; } ksort ( $ existingMessages ) ; foreach ( $ existingMessages as $ message => $ translation ) { if ( ! $ removeUnused && ! isset ( $ merged [ $ message ] ) && ! isset ( $ todo [ $ message ] ) ) { if ( ! $ markUnused || ( ! empty ( $ translation ) && ( strncmp ( $ translation , '@@' , 2 ) === 0 && substr_compare ( $ translation , '@@' , - 2 , 2 ) === 0 ) ) ) { $ todo [ $ message ] = $ translation ; } else { $ todo [ $ message ] = '@@' . $ translation . '@@' ; } } } $ merged = array_merge ( $ todo , $ merged ) ; if ( $ sort ) { ksort ( $ merged ) ; } if ( false === $ overwrite ) { $ fileName .= '.merged' ; } $ this -> stdout ( "Translation merged.\n" ) ; } else { $ merged = [ ] ; foreach ( $ messages as $ message ) { $ merged [ $ message ] = '' ; } ksort ( $ merged ) ; } $ array = VarDumper :: export ( $ merged ) ; $ content = <<<EOD<?php{$this->config['phpFileHeader']}{$this->config['phpDocBlock']}return $array;EOD ; if ( file_put_contents ( $ fileName , $ content , LOCK_EX ) === false ) { $ this -> stdout ( "Translation was NOT saved.\n\n" , Console :: FG_RED ) ; return ExitCode :: UNSPECIFIED_ERROR ; } $ this -> stdout ( "Translation saved.\n\n" , Console :: FG_GREEN ) ; return ExitCode :: OK ; }
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 ( $ cookie , $ mode ) ; } return ; } $ stringTypes = [ ] ; if ( ( $ mode & self :: COOKIE_NAME ) === self :: COOKIE_NAME ) { $ stringTypes [ ] = 'names' ; } if ( ( $ mode & self :: COOKIE_SUBSTR ) === self :: COOKIE_SUBSTR ) { $ stringTypes [ ] = 'substrings' ; } foreach ( $ stringTypes as $ type ) { if ( ( $ mode & self :: COOKIE_REMOVE ) !== self :: COOKIE_REMOVE and ! in_array ( $ name , $ this -> protectedCookies [ $ type ] ) ) { $ this -> protectedCookies [ $ type ] [ ] = $ name ; } elseif ( ( $ mode & self :: COOKIE_REMOVE ) === self :: COOKIE_REMOVE and ( $ key = array_search ( $ name , $ this -> protectedCookies [ $ type ] ) ) !== false ) { unset ( $ this -> protectedCookies [ $ type ] [ $ key ] ) ; } } }
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 ] [ $ source ] ) ) { return false ; } unset ( $ csp [ $ directive ] [ $ source ] ) ; return true ; }
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 ] ) ; return true ; }
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 ( isset ( $ enforce ) or ! isset ( $ this -> expectCT [ 'enforce' ] ) ) { $ this -> expectCT [ 'enforce' ] = ( isset ( $ enforce ) ? ( $ enforce == true ) : null ) ; } if ( isset ( $ reportUri ) or ! isset ( $ this -> expectCT [ 'report-uri' ] ) ) { $ this -> expectCT [ 'report-uri' ] = $ reportUri ; } }
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 ( $ maxAge ) or ! isset ( $ this -> hpkp [ 'max-age' ] ) ) { $ hpkp [ 'max-age' ] = $ maxAge ; } if ( isset ( $ subdomains ) or ! isset ( $ this -> hpkp [ 'includesubdomains' ] ) ) { $ hpkp [ 'includesubdomains' ] = ( isset ( $ subdomains ) ? ( $ subdomains == true ) : null ) ; } if ( isset ( $ reportUri ) or ! isset ( $ this -> hpkp [ 'report-uri' ] ) ) { $ hpkp [ 'report-uri' ] = $ reportUri ; } if ( ! is_array ( $ pins ) ) { $ pins = [ $ pins ] ; } foreach ( $ pins as $ key => $ pin ) { if ( is_array ( $ pin ) and count ( $ pin ) === 2 ) { $ res = array_intersect ( $ pin , $ this -> allowedHPKPAlgs ) ; if ( ! empty ( $ res ) ) { $ key = key ( $ res ) ; $ hpkp [ 'pins' ] [ ] = [ $ pin [ ( $ key + 1 ) % 2 ] , $ pin [ $ key ] ] ; } else { continue ; } } elseif ( is_string ( $ pin ) or ( is_array ( $ pin ) and count ( $ pin ) === 1 and ( $ pin = $ pin [ 0 ] ) !== false ) ) { $ hpkp [ 'pins' ] [ ] = [ $ pin , 'sha256' ] ; } } }
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_merge ( $ this -> errors , $ operation -> collectErrors ( ) ) ; } } $ http -> sendHeaders ( $ headers ) ; $ this -> reportMissingHeaders ( $ headers ) ; $ this -> validateHeaders ( $ headers ) ; $ this -> reportErrors ( ) ; return $ headers ; }
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 to generate the nonce for CSP.' , E_USER_WARNING ) ; } return $ nonce ; }
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>Notice:</strong> ' . $ message . "<br><br>\n\n" ; } elseif ( $ level === E_USER_WARNING ) { $ error = '<strong>Warning:</strong> ' . $ message . "<br><br>\n\n" ; } if ( isset ( $ error ) ) { echo $ error ; $ this -> errorString .= $ error ; return true ; } } return false ; }
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 ) { $ headers -> forEachNamed ( $ headerName , function ( Header $ header ) use ( & $ errors , $ class ) { $ errors = array_merge ( $ errors , $ class :: validate ( $ header ) ) ; } ) ; } } return $ errors ; }
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'" , "'unsafe-eval'" ] ; foreach ( $ badFlags as $ badFlag ) { if ( strpos ( $ value , $ badFlag ) !== false ) { $ friendlyHeader = $ header -> getFriendlyName ( ) ; $ Errors [ ] = new Error ( $ friendlyHeader . ' contains the <b>' . $ badFlag . '</b> keyword in <b>' . $ attributeName . '</b>, which prevents CSP protecting against the injection of arbitrary code into the page.' , E_USER_WARNING ) ; } } } return $ Errors ; }
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 ) ) { if ( ( $ key = array_search ( 'data:' , $ matches [ 0 ] ) ) !== false ) { unset ( $ matches [ 0 ] [ $ key ] ) ; } } if ( ! empty ( $ matches [ 0 ] ) ) { $ friendlyHeader = $ header -> getFriendlyName ( ) ; return new Error ( $ friendlyHeader . ' ' . ( count ( $ matches [ 0 ] ) > 1 ? 'contains the following wildcards ' : 'contains a wildcard ' ) . '<b>' . implode ( ', ' , $ matches [ 0 ] ) . '</b> as a source value in <b>' . $ directive . '</b>; this can allow anyone to insert elements covered by the <b>' . $ directive . '</b> directive into the page.' , E_USER_WARNING ) ; } } return null ; }
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 ( $ friendlyHeader . ' contains the insecure protocol HTTP in ' . ( count ( $ matches [ 0 ] ) > 1 ? 'the following source values ' : 'a source value ' ) . '<b>' . implode ( ', ' , $ matches [ 0 ] ) . '</b>; this can allow anyone to insert elements covered by the <b>' . $ directive . '</b> directive into the page.' , E_USER_WARNING ) ; } return null ; }
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 ; } else { $ finalCSP [ $ directive ] = array_merge ( $ finalCSP [ $ directive ] , $ sources ) ; continue ; } } } return $ finalCSP ; }
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 ] = [ ] ; } $ this -> attributes [ $ type ] [ ] = [ 'name' => $ attrParts [ 0 ] , 'value' => isset ( $ attrParts [ 1 ] ) ? $ attrParts [ 1 ] : true ] ; } }
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 ; } else { $ string = "$key=$value" ; } $ attributeStrings [ ] = $ string ; } } $ this -> value = implode ( '; ' , $ attributeStrings ) ; }
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 ; } $ nonceOrHashRe = implode ( '|' , array_map ( function ( $ s ) { return preg_quote ( $ s , '/' ) ; } , array_merge ( [ 'nonce' ] , $ this -> allowedCSPHashAlgs ) ) ) ; $ containsNonceOrHash = preg_match ( "/(?:^|\s)'(?:$nonceOrHashRe)-/i" , $ header -> getAttributeValue ( $ directive ) ) ; if ( $ containsNonceOrHash ) { return $ directive ; } } return false ; }
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' ; $ commands = [ 'server:run' => 'web_server.command.server_run' , 'server:start' => 'web_server.command.server_start' , 'server:stop' => 'web_server.command.server_stop' , 'server:status' => 'web_server.command.server_status' , ] ; $ container [ 'web_server.command.server_run' ] = function ( Container $ container ) { if ( null === $ docRoot = $ container [ 'web_server.document_root' ] ) { throw new \ LogicException ( 'You must set the web_server.document_root parameter to use the development web server.' ) ; } return new ServerRunCommand ( $ docRoot , $ container [ 'web_server.environment' ] ) ; } ; $ container [ 'web_server.command.server_start' ] = function ( Container $ container ) { if ( null === $ docRoot = $ container [ 'web_server.document_root' ] ) { throw new \ LogicException ( 'You must set the web_server.document_root parameter to use the development web server.' ) ; } return new ServerStartCommand ( $ docRoot , $ container [ 'web_server.environment' ] ) ; } ; $ container [ 'web_server.command.server_stop' ] = function ( ) { return new ServerStopCommand ( ) ; } ; $ container [ 'web_server.command.server_status' ] = function ( ) { return new ServerStatusCommand ( ) ; } ; if ( class_exists ( ConsoleFormatter :: class ) ) { $ container [ 'web_server.command.server_log' ] = function ( ) { return new ServerLogCommand ( ) ; } ; $ commands [ 'server:log' ] = 'web_server.command.server_log' ; } $ container [ 'console.command.ids' ] = array_merge ( $ container [ 'console.command.ids' ] , $ commands ) ; }
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.boot_in_constructor' ] = false ; $ app [ 'console' ] = function ( ) use ( $ app ) { $ console = new $ app [ 'console.class' ] ( $ app , $ app [ 'console.project_directory' ] , $ app [ 'console.name' ] , $ app [ 'console.version' ] ) ; $ console -> setDispatcher ( $ app [ 'dispatcher' ] ) ; foreach ( $ app [ 'console.command.ids' ] as $ id ) { $ console -> add ( $ app [ $ id ] ) ; } if ( $ app [ 'dispatcher' ] -> hasListeners ( ConsoleEvents :: INIT ) ) { @ trigger_error ( 'Listening to the Knp\Console\ConsoleEvents::INIT event is deprecated and will be removed in v3 of the service provider. You should extend the console service instead.' , E_USER_DEPRECATED ) ; $ app [ 'dispatcher' ] -> dispatch ( ConsoleEvents :: INIT , new ConsoleEvent ( $ console ) ) ; } return $ console ; } ; $ commands = [ ] ; if ( isset ( $ app [ 'twig' ] ) && class_exists ( TwigBridgeDebugCommand :: class ) ) { $ app [ 'console.command.twig.debug' ] = function ( Container $ container ) { return new DebugCommand ( $ container ) ; } ; $ app [ 'console.command.twig.lint' ] = function ( Container $ container ) { return new LintCommand ( $ container ) ; } ; $ commands [ 'debug:twig' ] = 'console.command.twig.debug' ; $ commands [ 'lint:twig' ] = 'console.command.twig.lint' ; } if ( class_exists ( LintYamlCommand :: class ) ) { $ app [ 'console.command.yaml.lint' ] = function ( ) { return new LintYamlCommand ( ) ; } ; $ commands [ 'lint:yaml' ] = 'console.command.yaml.lint' ; } $ app [ 'console.command.ids' ] = $ commands ; }
Registers the service provider .