idx int64 0 60.3k | question stringlengths 101 6.21k | target stringlengths 7 803 |
|---|---|---|
49,800 | public function buildCommandXmlIn ( $ cmd , $ exec = 'pase' ) { $ xmlIn = '' ; $ propArray = array ( ) ; $ this -> processParamProps ( $ propArray ) ; $ ccsidHexStr = "{$propArray['ccsidStr']}{$propArray['hexStr']}" ; if ( is_string ( $ cmd ) ) { $ cmdArray = array ( $ cmd ) ; } else { $ cmdArray = $ cmd ; } foreach ( $ cmdArray as $ oneCmd ) { if ( $ exec == 'pase' ) { $ oneCmd = '/QOpenSys/usr/bin/system "' . $ oneCmd . '"' ; } $ encodedCmd = $ this -> encodeString ( $ oneCmd ) ; if ( $ exec == 'pase' || $ exec == 'pasecmd' ) { $ xmlIn .= "<sh rows='on'$ccsidHexStr>$encodedCmd</sh>" ; } else { if ( $ exec && in_array ( $ exec , $ this -> _cmdTypes ) ) { $ execStr = " exec='$exec'" ; } else { $ execStr = '' ; } $ xmlIn .= "<cmd$execStr$ccsidHexStr>$encodedCmd</cmd>" ; } } return $ this -> addOuterTags ( $ xmlIn ) ; } | It s more efficient to run multiple commands with one XMLSERVICE call than to do many calls |
49,801 | public function getCmdResultFromXml ( $ xml , $ parentTag = 'sh' ) { $ this -> error = '' ; $ xmlobj = simplexml_load_string ( $ xml ) ; if ( ! $ xmlobj instanceof \ SimpleXMLElement ) { $ this -> error = "Can't read output xml" ; error_log ( $ xml , 3 , '/tmp/bad.xml' ) ; return false ; } $ retval = true ; $ params = $ xmlobj -> xpath ( "/script/$parentTag" ) ; foreach ( $ params as $ simpleXMLElement ) { if ( isset ( $ simpleXMLElement -> error ) ) { $ lastJoblogTag = current ( $ simpleXMLElement -> xpath ( "joblogscan/joblogrec[last()]" ) ) ; if ( $ lastJoblogTag && isset ( $ lastJoblogTag -> jobcpf ) && ( strlen ( $ lastJoblogTag -> jobcpf ) == 7 ) ) { $ this -> cpfErr = ( string ) $ lastJoblogTag -> jobcpf ; $ this -> error = $ this -> cpfErr ; $ this -> errorText = ( string ) $ lastJoblogTag -> jobtext ; $ retval = false ; break ; } if ( isset ( $ simpleXMLElement -> error [ 1 ] ) ) { $ this -> error = ( string ) $ simpleXMLElement -> error [ 1 ] ; } else { $ this -> error = "Command execute failed." ; } $ retval = false ; break ; } if ( strstr ( ( ( string ) $ simpleXMLElement ) , "*** error" ) ) { $ this -> error = "Command execute failed. " ; $ retval = false ; break ; } if ( isset ( $ simpleXMLElement -> success ) ) { $ retval = true ; break ; } if ( strstr ( ( ( string ) $ simpleXMLElement ) , "+++ success" ) ) { $ retval = true ; break ; } } return $ retval ; } | gets any error code and sets it in toolkit . returns true or false depending on interpretation of status |
49,802 | public function getRowsFromXml ( $ xml , $ parent = 'sh' ) { $ this -> error = '' ; $ values = array ( ) ; $ xmlobj = @ simplexml_load_string ( $ xml ) ; if ( ! $ xmlobj instanceof \ SimpleXMLElement ) { $ this -> error = "Can't read output xml" ; return false ; } $ params = $ xmlobj -> xpath ( "/script/$parent/row" ) ; foreach ( $ params as $ simpleXMLElement ) { $ element = ( isset ( $ simpleXMLElement -> data ) ) ? $ simpleXMLElement -> data : $ simpleXMLElement ; $ data = ( isset ( $ element -> hex ) ) ? pack ( "H*" , ( string ) $ element -> hex ) : ( string ) $ element ; if ( $ parent == 'cmd' ) { $ outputFieldName = ( string ) $ element -> attributes ( ) -> desc ; $ data = trim ( $ data , " \n" ) ; $ values [ $ outputFieldName ] = $ data ; } else { $ values [ ] = $ data ; } } if ( count ( $ params ) == 0 ) { $ this -> error = "No rows" ; $ params = $ xmlobj -> xpath ( "/script/$parent" ) ; foreach ( $ params as $ simpleXMLElement ) { if ( strstr ( ( ( string ) $ simpleXMLElement ) , "+++ no output" ) ) { $ this -> error = "Command does not return output" ; } break ; } } return $ values ; } | Get rows from command output . |
49,803 | private function validateDocumentRoot ( ) { if ( end ( explode ( '\\' , $ this -> documentRoot ) ) != "public" && end ( explode ( '/' , $ this -> documentRoot ) ) != "public" ) { die ( $ this -> logEntry ( "Your servers DOCUMENT_ROOT needs to be a directory called `public`" ) ) ; } if ( ! is_writable ( dirname ( $ this -> documentRoot ) ) ) { die ( $ this -> logEntry ( "Web server user does not have access to the DOCUMENT_ROOT's parent directory. " . "This is required in order for Dappur to function properly." ) ) ; } } | structure is correct |
49,804 | private function installUpdateComposer ( ) { if ( ! is_file ( dirname ( $ this -> documentRoot ) . '/composer.phar' ) ) { if ( file_put_contents ( dirname ( $ this -> documentRoot ) . '/composer.phar' , fopen ( "https://getcomposer.org/download/1.7.1/composer.phar" , 'r' ) ) ) { echo $ this -> logEntry ( "Composer downloaded successfully. Making composer.phar executable..." ) ; exec ( "cd " . dirname ( $ this -> documentRoot ) . " && chmod +x composer.phar" ) ; } else { echo $ this -> logEntry ( "Could not get Composer working. Please check your settings and try again." ) ; } } else { $ check_composer = shell_exec ( dirname ( $ this -> documentRoot ) . "/composer.phar" . ' --version 2>&1' ) ; echo $ this -> logEntry ( $ check_composer ) ; if ( strpos ( $ check_composer , 'omposer version' ) ) { $ update_composer = shell_exec ( dirname ( $ this -> documentRoot ) . "/composer.phar self-update 2>&1" ) ; echo $ this -> logEntry ( "Checking For Composer Update..." ) ; echo $ this -> logEntry ( $ update_composer ) ; } } } | Check if composer is installed or download phar and use that . |
49,805 | public function setI5Error ( $ errNum , $ errCat = I5_CAT_PHP , $ errMsg = '' , $ errDesc = '' ) { $ i5ErrorArray = array ( 0 => $ errNum , 1 => $ errCat , 2 => $ errMsg , 3 => $ errDesc , 'num' => $ errNum , 'cat' => $ errCat , 'msg' => $ errMsg , 'desc' => $ errDesc ) ; self :: $ _i5Error = $ i5ErrorArray ; } | Set error information for last action . |
49,806 | public function blogEdit ( Request $ request , Response $ response , $ postId ) { if ( $ check = $ this -> sentinel -> hasPerm ( 'blog.update' , 'dashboard' , $ this -> config [ 'blog-enabled' ] ) ) { return $ check ; } $ post = BlogPosts :: where ( 'id' , $ postId ) -> with ( 'category' ) -> with ( 'tags' ) -> first ( ) ; if ( ! $ post ) { $ this -> flash ( 'danger' , 'That post does not exist.' ) ; return $ this -> redirect ( $ response , 'admin-blog' ) ; } if ( ! $ this -> auth -> check ( ) -> inRole ( 'manager' ) && ! $ this -> auth -> check ( ) -> inRole ( 'admin' ) && $ post -> user_id != $ this -> auth -> check ( ) -> id ) { $ this -> flash ( 'danger' , 'You do not have permission to edit that post.' ) ; return $ this -> redirect ( $ response , 'admin-blog' ) ; } if ( $ request -> isPost ( ) ) { if ( $ this -> blogUtils -> updatePost ( $ post -> id ) ) { return $ this -> redirect ( $ this -> container -> response , 'admin-blog' ) ; } } $ currentTags = $ post -> tags -> pluck ( 'id' ) ; return $ this -> view -> render ( $ response , 'blog-edit.twig' , array ( "post" => $ post -> toArray ( ) , "categories" => BlogCategories :: get ( ) , "tags" => BlogTags :: get ( ) , "currentTags" => $ currentTags ) ) ; } | Edit Blog Post |
49,807 | public function blogPublish ( Request $ request , Response $ response ) { if ( $ check = $ this -> sentinel -> hasPerm ( 'blog.update' , 'dashboard' , $ this -> config [ 'blog-enabled' ] ) ) { return $ check ; } $ post = BlogPosts :: find ( $ request -> getParam ( 'post_id' ) ) ; if ( ! $ post ) { $ this -> flash ( 'danger' , 'That post does not exist.' ) ; return $ this -> redirect ( $ response , 'admin-blog' ) ; } if ( ! $ this -> auth -> check ( ) -> inRole ( 'manager' ) && ! $ this -> auth -> check ( ) -> inRole ( 'admin' ) && $ post -> user_id != $ this -> auth -> check ( ) -> id ) { $ this -> flash ( 'danger' , 'You do not have permission to edit that post.' ) ; return $ this -> redirect ( $ response , 'admin-blog' ) ; } if ( $ this -> blogUtils -> publish ( ) ) { $ this -> flash ( 'success' , 'Post was published successfully.' ) ; return $ this -> redirect ( $ response , 'admin-blog' ) ; } $ this -> flash ( 'danger' , 'There was an error publishing your post.' ) ; return $ this -> redirect ( $ response , 'admin-blog' ) ; } | Publish Blog Post |
49,808 | public function receiveDataQueue ( $ WaitTime , $ KeyOrder = '' , $ KeyLength = 0 , $ KeyData = '' , $ WithRemoveMsg = 'N' ) { return $ this -> receieveDataQueue ( $ WaitTime , $ KeyOrder , $ KeyLength , $ KeyData , $ WithRemoveMsg ) ; } | Correct spelling with this alias |
49,809 | public function GetSPLF ( $ SplfName , $ SplfNbr , $ JobNmbr , $ JobName , $ JobUser , $ TMPFName = '' ) { $ this -> clearError ( ) ; if ( $ TMPFName != '' ) { $ this -> TMPFName = $ TMPFName ; } $ crtf = "CRTDUPOBJ OBJ(ZSF255) FROMLIB(" . $ this -> ToolkitSrvObj -> getOption ( 'HelperLib' ) . ") OBJTYPE(*FILE) TOLIB($this->TmpLib) NEWOBJ($this->TMPFName)" ; $ this -> ToolkitSrvObj -> ClCommandWithCpf ( $ crtf ) ; $ clrpfm = "CLRPFM $this->TmpLib/$this->TMPFName" ; $ this -> ToolkitSrvObj -> ClCommandWithCpf ( $ clrpfm ) ; $ cmd = sprintf ( "CPYSPLF FILE(%s) TOFILE($this->TmpLib/$this->TMPFName) JOB(%s/%s/%s) SPLNBR(%s)" , $ SplfName , trim ( $ JobNmbr ) , trim ( $ JobUser ) , trim ( $ JobName ) , $ SplfNbr ) ; $ this -> ToolkitSrvObj -> ClCommandWithCpf ( $ cmd ) ; sleep ( 1 ) ; $ Txt = $ this -> ReadSPLFData ( ) ; $ dltf = "DLTF FILE($this->TmpLib/$this->TMPFName)" ; $ this -> ToolkitSrvObj -> ClCommandWithCpf ( $ dltf ) ; return $ Txt ; } | multi user using! |
49,810 | protected function setStmtError ( $ stmt = null ) { if ( $ stmt ) { $ this -> setErrorCode ( db2_stmt_error ( $ stmt ) ) ; $ this -> setErrorMsg ( db2_stmt_errormsg ( $ stmt ) ) ; } else { $ this -> setErrorCode ( db2_stmt_error ( ) ) ; $ this -> setErrorMsg ( db2_stmt_errormsg ( ) ) ; } } | set error code and message based on last db2 prepare or execute error . |
49,811 | public function close ( ) { $ apiPgm = 'QGYCLST' ; $ apiLib = 'QSYS' ; $ requestHandle = $ this -> _requestHandle ; $ paramXml = "<parm io='in' comment='1. request handle'> <data var='requestHandle' comment='Request handle: binary/hex' type='4b'>$requestHandle</data> </parm>\n" . Toolkit :: getErrorDataStructXml ( 2 ) ; $ this -> ToolkitSrvObj -> PgmCall ( $ apiPgm , $ apiLib , $ paramXml ) ; if ( $ this -> ToolkitSrvObj -> getErrorCode ( ) ) { return false ; } else { return true ; } } | close the list |
49,812 | public function pcmlToArray ( \ SimpleXMLElement $ xmlObj ) { $ dataDescription = array ( ) ; $ this -> _pcmlStructs = $ xmlObj -> xpath ( 'struct' ) ; $ dataElements = $ xmlObj -> xpath ( 'program/data' ) ; if ( $ dataElements ) { foreach ( $ dataElements as $ dataElement ) { $ dataDescription [ ] = $ this -> singlePcmlToArray ( $ dataElement ) ; } } return $ dataDescription ; } | given an XML object containing a PCML program definition return an old toolkit style of data description array . |
49,813 | public function deleteDataArea ( $ DataAreaName = '' , $ DataAreaLib = '' ) { $ cmd = sprintf ( "QSYS/DLTDTAARA DTAARA(%s/%s)" , ( $ DataAreaLib != '' ? $ DataAreaLib : $ this -> DataAreaLib ) , ( $ DataAreaName != NULL ? $ DataAreaName : $ this -> DataAreaName ) ) ; if ( ! $ this -> ToolkitSrvObj -> CLCommand ( $ cmd ) ) { $ this -> ErrMessage = "Delete Data Area failed." . $ this -> ToolkitSrvObj -> getLastError ( ) ; throw new \ Exception ( $ this -> ErrMessage ) ; } } | requires explicit library |
49,814 | public function write ( Response $ response , $ data , $ status = 200 ) { return $ response -> withStatus ( $ status ) -> getBody ( ) -> write ( $ data ) ; } | Write text in the response body |
49,815 | public function onCorsPreflight ( MvcEvent $ event ) { $ this -> isPreflight = false ; $ request = $ event -> getRequest ( ) ; if ( ! $ request instanceof HttpRequest ) { return ; } try { $ isCorsRequest = $ this -> corsService -> isCorsRequest ( $ request ) ; } catch ( InvalidOriginException $ exception ) { $ response = $ event -> getResponse ( ) ; $ response -> setStatusCode ( 400 ) ; $ response -> setReasonPhrase ( $ exception -> getMessage ( ) ) ; return $ response ; } if ( ! $ isCorsRequest || ! $ this -> corsService -> isPreflightRequest ( $ request ) ) { return ; } $ this -> isPreflight = true ; return $ this -> corsService -> createPreflightCorsResponseWithRouteOptions ( $ request , $ event -> getRouteMatch ( ) ) ; } | Handle a CORS preflight request |
49,816 | public function getConfigFile ( $ name , $ required = true , $ directory = 'config' ) { $ sep = DIRECTORY_SEPARATOR ; $ path = rtrim ( $ this -> directory , $ sep ) . $ sep . trim ( $ directory , $ sep ) . $ sep . $ name ; if ( ! file_exists ( $ path ) ) { if ( $ required ) { throw new \ Exception ( "Config file '$path' does not exist" ) ; } else { return null ; } } return $ path ; } | Gets the filename for a config file |
49,817 | public function web ( $ config = [ ] , $ local = null ) { $ files = [ $ this -> getConfigFile ( 'web.php' ) ] ; if ( $ local === null ) { $ local = $ this -> env ( 'ENABLE_LOCALCONF' , false ) ; } if ( $ local ) { $ localFile = $ this -> getConfigFile ( 'local.php' , false ) ; if ( $ localFile !== null ) { $ files [ ] = $ localFile ; } } return $ this -> mergeFiles ( $ files , $ config ) ; } | Builds the web configuration . |
49,818 | public function mergeFiles ( $ files , $ config = [ ] ) { $ configs = array_map ( function ( $ f ) { return require ( $ f ) ; } , $ files ) ; $ configs [ ] = $ config ; return call_user_func_array ( 'yii\helpers\ArrayHelper::merge' , $ configs ) ; } | Load configuration files and merge them together . |
49,819 | public static function bootstrap ( $ directory , $ vendor = null , $ initEnv = true ) { $ sep = DIRECTORY_SEPARATOR ; if ( $ vendor === null ) { $ vendor = realpath ( __DIR__ . $ sep . '..' . $ sep . '..' . $ sep . '..' ) ; } $ config = new self ( $ directory , $ initEnv ) ; require ( rtrim ( $ vendor , $ sep ) . $ sep . 'yiisoft' . $ sep . 'yii2' . $ sep . 'Yii.php' ) ; return $ config ; } | Init the configuration for the given directory and load the Yii bootstrap file . |
49,820 | public static function initEnv ( $ directory = null ) { if ( $ directory !== null && file_exists ( $ directory . DIRECTORY_SEPARATOR . '.env' ) ) { $ dotenv = new \ Dotenv \ Dotenv ( $ directory ) ; $ dotenv -> load ( ) ; } $ debug = self :: env ( 'YII_DEBUG' , false ) ; if ( $ debug !== false ) { define ( 'YII_DEBUG' , ( bool ) $ debug ) ; if ( YII_DEBUG ) { error_reporting ( E_ALL ) ; } } $ env = self :: env ( 'YII_ENV' , false ) ; if ( $ env !== false ) { define ( 'YII_ENV' , $ env ) ; } } | Init the Yii environment from environment variables . |
49,821 | public function isCorsRequest ( HttpRequest $ request ) { $ headers = $ request -> getHeaders ( ) ; if ( ! $ headers -> has ( 'Origin' ) ) { return false ; } try { $ origin = $ headers -> get ( 'Origin' ) ; } catch ( Header \ Exception \ InvalidArgumentException $ exception ) { throw InvalidOriginException :: fromInvalidHeaderValue ( ) ; } $ originUri = UriFactory :: factory ( $ origin -> getFieldValue ( ) ) ; $ requestUri = $ request -> getUri ( ) ; return ( ! ( $ originUri -> getHost ( ) === $ requestUri -> getHost ( ) ) || ! ( $ originUri -> getPort ( ) === $ requestUri -> getPort ( ) ) || ! ( $ originUri -> getScheme ( ) === $ requestUri -> getScheme ( ) ) ) ; } | Check if the HTTP request is a CORS request by checking if the Origin header is present and that the request URI is not the same as the one in the Origin |
49,822 | public function isPreflightRequest ( HttpRequest $ request ) { return $ this -> isCorsRequest ( $ request ) && strtoupper ( $ request -> getMethod ( ) ) === 'OPTIONS' && $ request -> getHeaders ( ) -> has ( 'Access-Control-Request-Method' ) ; } | Check if the CORS request is a preflight request |
49,823 | public function createPreflightCorsResponse ( HttpRequest $ request ) { $ response = new HttpResponse ( ) ; $ response -> setStatusCode ( 200 ) ; $ headers = $ response -> getHeaders ( ) ; $ headers -> addHeaderLine ( 'Access-Control-Allow-Origin' , $ this -> getAllowedOriginValue ( $ request ) ) ; $ headers -> addHeaderLine ( 'Access-Control-Allow-Methods' , implode ( ', ' , $ this -> options -> getAllowedMethods ( ) ) ) ; $ headers -> addHeaderLine ( 'Access-Control-Allow-Headers' , implode ( ', ' , $ this -> options -> getAllowedHeaders ( ) ) ) ; $ headers -> addHeaderLine ( 'Access-Control-Max-Age' , $ this -> options -> getMaxAge ( ) ) ; $ headers -> addHeaderLine ( 'Content-Length' , 0 ) ; if ( $ this -> options -> getAllowedCredentials ( ) ) { $ headers -> addHeaderLine ( 'Access-Control-Allow-Credentials' , 'true' ) ; } return $ response ; } | Create a preflight response by adding the corresponding headers |
49,824 | public function createPreflightCorsResponseWithRouteOptions ( HttpRequest $ request , $ routeMatch = null ) { $ options = $ this -> options ; if ( $ routeMatch instanceof RouteMatch || $ routeMatch instanceof DeprecatedRouteMatch ) { $ options -> setFromArray ( $ routeMatch -> getParam ( CorsOptions :: ROUTE_PARAM ) ? : [ ] ) ; } $ response = $ this -> createPreflightCorsResponse ( $ request ) ; return $ response ; } | Create a preflight response by adding the correspoding headers which are merged with per - route configuration |
49,825 | public function populateCorsResponse ( HttpRequest $ request , HttpResponse $ response ) { $ origin = $ this -> getAllowedOriginValue ( $ request ) ; if ( $ origin === 'null' ) { $ origin = $ request -> getHeader ( 'Origin' ) ; $ originHeader = $ origin ? $ origin -> getFieldValue ( ) : '' ; throw new DisallowedOriginException ( sprintf ( 'The origin "%s" is not authorized' , $ originHeader ) ) ; } $ headers = $ response -> getHeaders ( ) ; $ headers -> addHeaderLine ( 'Access-Control-Allow-Origin' , $ origin ) ; $ headers -> addHeaderLine ( 'Access-Control-Expose-Headers' , implode ( ', ' , $ this -> options -> getExposedHeaders ( ) ) ) ; $ headers = $ this -> ensureVaryHeader ( $ response ) ; if ( $ this -> options -> getAllowedCredentials ( ) ) { $ headers -> addHeaderLine ( 'Access-Control-Allow-Credentials' , 'true' ) ; } $ response -> setHeaders ( $ headers ) ; return $ response ; } | Populate a simple CORS response |
49,826 | protected function getAllowedOriginValue ( HttpRequest $ request ) { $ allowedOrigins = $ this -> options -> getAllowedOrigins ( ) ; $ origin = $ request -> getHeader ( 'Origin' ) ; if ( $ origin ) { $ origin = $ origin -> getFieldValue ( ) ; if ( in_array ( '*' , $ allowedOrigins ) ) { return $ origin ; } foreach ( $ allowedOrigins as $ allowedOrigin ) { if ( fnmatch ( $ allowedOrigin , $ origin ) ) { return $ origin ; } } } return 'null' ; } | Get a single value for the Access - Control - Allow - Origin header |
49,827 | public function ensureVaryHeader ( HttpResponse $ response ) { $ headers = $ response -> getHeaders ( ) ; $ allowedOrigins = $ this -> options -> getAllowedOrigins ( ) ; if ( in_array ( '*' , $ allowedOrigins ) ) { return $ headers ; } if ( $ headers -> has ( 'Vary' ) ) { $ varyHeader = $ headers -> get ( 'Vary' ) ; $ varyValue = $ varyHeader -> getFieldValue ( ) . ', Origin' ; $ headers -> removeHeader ( $ varyHeader ) ; $ headers -> addHeaderLine ( 'Vary' , $ varyValue ) ; } else { $ headers -> addHeaderLine ( 'Vary' , 'Origin' ) ; } return $ headers ; } | Ensure that the Vary header is set . |
49,828 | protected function addError ( $ phpcsFile , $ stackPtr , $ function , $ pattern = null ) { $ data = array ( $ function ) ; $ error = 'The use of function %s() is ' ; if ( $ this -> error === true ) { $ type = 'Found' ; $ error .= 'forbidden' ; } else { $ type = 'Discouraged' ; $ error .= 'discouraged' ; } if ( $ pattern === null ) { $ pattern = $ function ; } if ( $ this -> forbiddenFunctions [ $ pattern ] !== null && $ this -> forbiddenFunctions [ $ pattern ] !== 'null' ) { $ type .= 'WithAlternative' ; $ data [ ] = $ this -> forbiddenFunctions [ $ pattern ] ; $ error .= '; use %s() instead' ; } if ( $ this -> error === true ) { $ phpcsFile -> addError ( $ error , $ stackPtr , $ type , $ data ) ; } else { $ phpcsFile -> addWarning ( $ error , $ stackPtr , $ type , $ data ) ; } } | Generates the error or warning for this sniff . |
49,829 | public function isMultiLineDeclaration ( $ phpcsFile , $ stackPtr , $ openBracket , $ tokens ) { $ bracketsToCheck = array ( $ stackPtr => $ openBracket ) ; if ( $ tokens [ $ stackPtr ] [ 'code' ] === T_CLOSURE ) { $ use = $ phpcsFile -> findNext ( T_USE , ( $ tokens [ $ openBracket ] [ 'parenthesis_closer' ] + 1 ) , $ tokens [ $ stackPtr ] [ 'scope_opener' ] ) ; if ( $ use !== false ) { $ open = $ phpcsFile -> findNext ( T_OPEN_PARENTHESIS , ( $ use + 1 ) ) ; if ( $ open !== false ) { $ bracketsToCheck [ $ use ] = $ open ; } } } foreach ( $ bracketsToCheck as $ stackPtr => $ openBracket ) { $ next = $ phpcsFile -> findNext ( Tokens :: $ emptyTokens , ( $ openBracket + 1 ) , null , true ) ; if ( $ tokens [ $ next ] [ 'line' ] !== $ tokens [ $ stackPtr ] [ 'line' ] ) { return true ; } $ closeBracket = $ tokens [ $ openBracket ] [ 'parenthesis_closer' ] ; $ end = $ phpcsFile -> findEndOfStatement ( $ openBracket + 1 ) ; while ( $ tokens [ $ end ] [ 'code' ] === T_COMMA ) { $ next = $ phpcsFile -> findNext ( Tokens :: $ emptyTokens , ( $ end + 1 ) , $ closeBracket , true ) ; if ( $ next === false ) { continue ( 2 ) ; } if ( $ tokens [ $ next ] [ 'line' ] !== $ tokens [ $ end ] [ 'line' ] ) { return true ; } $ end = $ phpcsFile -> findEndOfStatement ( $ next ) ; } $ next = $ phpcsFile -> findNext ( Tokens :: $ emptyTokens , ( $ end + 1 ) , $ closeBracket , true ) ; if ( $ next !== false && $ tokens [ $ next ] [ 'line' ] !== $ tokens [ $ end ] [ 'line' ] ) { return true ; } } return false ; } | Determine if this is a multi - line function declaration . |
49,830 | public static function isLowerSnakeCase ( $ string ) { if ( strcmp ( $ string , strtolower ( $ string ) ) !== 0 ) { return false ; } if ( strpos ( $ string , ' ' ) !== false ) { return false ; } return true ; } | Is lower snake case |
49,831 | protected function initializeExecute ( OutputInterface $ output , ProcessHelper $ helper ) { $ this -> execute = $ this -> execute ? : new Execute ( $ output , $ helper ) ; } | Initialize the execute property if necessary . |
49,832 | public function resolveRequirements ( Plugin $ plugin , $ moodleVersion ) { $ map = [ 'auth' => new AuthRequirements ( $ plugin , $ moodleVersion ) , 'block' => new BlockRequirements ( $ plugin , $ moodleVersion ) , 'filter' => new FilterRequirements ( $ plugin , $ moodleVersion ) , 'format' => new FormatRequirements ( $ plugin , $ moodleVersion ) , 'mod' => new ModuleRequirements ( $ plugin , $ moodleVersion ) , 'qtype' => new QuestionRequirements ( $ plugin , $ moodleVersion ) , 'repository' => new RepositoryRequirements ( $ plugin , $ moodleVersion ) , 'theme' => new ThemeRequirements ( $ plugin , $ moodleVersion ) , ] ; if ( array_key_exists ( $ plugin -> type , $ map ) ) { return $ map [ $ plugin -> type ] ; } return new GenericRequirements ( $ plugin , $ moodleVersion ) ; } | Find the requirements for a given plugin type . |
49,833 | protected function loadFile ( $ path ) { if ( pathinfo ( $ path , PATHINFO_EXTENSION ) !== 'php' ) { throw new \ InvalidArgumentException ( 'Can only parse files with ".php" extensions' ) ; } if ( ! file_exists ( $ path ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Failed to find \'%s\' file.' , $ path ) ) ; } return file_get_contents ( $ path ) ; } | Loads the contents of a file . |
49,834 | public function parseFile ( $ path ) { $ factory = new ParserFactory ( ) ; $ parser = $ factory -> create ( ParserFactory :: PREFER_PHP7 ) ; try { $ statements = $ parser -> parse ( $ this -> loadFile ( $ path ) ) ; } catch ( Error $ e ) { throw new \ RuntimeException ( sprintf ( 'Failed to parse %s file due to parse error: %s' , $ path , $ e -> getMessage ( ) ) , 0 , $ e ) ; } if ( $ statements === null ) { throw new \ RuntimeException ( sprintf ( 'Failed to parse %s' , $ path ) ) ; } return $ statements ; } | Parse a PHP file . |
49,835 | private function resolveOptions ( InputInterface $ input ) { $ options = [ ] ; if ( $ this -> supportsCoverage ( ) && $ input -> getOption ( 'coverage-text' ) ) { $ options [ ] = '--coverage-text' ; } if ( $ this -> supportsCoverage ( ) && $ input -> getOption ( 'coverage-clover' ) ) { $ options [ ] = sprintf ( '--coverage-clover %s/coverage.xml' , getcwd ( ) ) ; } if ( is_file ( $ this -> plugin -> directory . '/phpunit.xml' ) ) { $ options [ ] = sprintf ( '--configuration %s' , $ this -> plugin -> directory ) ; } else { $ options [ ] = sprintf ( '--testsuite %s_testsuite' , $ this -> plugin -> getComponent ( ) ) ; } return implode ( ' ' , $ options ) ; } | Resolve options for PHPUnit command . |
49,836 | public function passThrough ( $ commandline , $ cwd = null , $ timeout = null ) { return $ this -> passThroughProcess ( new Process ( $ commandline , $ cwd , null , null , $ timeout ) ) ; } | Run a command and send output unaltered immediately . |
49,837 | public function passThroughProcess ( Process $ process ) { if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( '<bg=blue;fg=white;> RUN </> <fg=blue>%s</>' , $ process -> getCommandLine ( ) ) ) ; } $ process -> run ( function ( $ type , $ buffer ) { $ this -> output -> write ( $ buffer ) ; } ) ; return $ process ; } | Run a process and send output unaltered immediately . |
49,838 | public function requireConfig ( ) { global $ CFG ; if ( ! defined ( 'CLI_SCRIPT' ) ) { define ( 'CLI_SCRIPT' , true ) ; } if ( ! defined ( 'IGNORE_COMPONENT_CACHE' ) ) { define ( 'IGNORE_COMPONENT_CACHE' , true ) ; } if ( ! defined ( 'CACHE_DISABLE_ALL' ) ) { define ( 'CACHE_DISABLE_ALL' , true ) ; } if ( ! defined ( 'ABORT_AFTER_CONFIG' ) ) { define ( 'ABORT_AFTER_CONFIG' , true ) ; } $ path = $ this -> directory . '/config.php' ; if ( ! is_file ( $ path ) ) { throw new \ RuntimeException ( 'Failed to find Moodle config file' ) ; } require_once $ path ; if ( empty ( $ this -> cfg ) ) { $ this -> cfg = $ CFG ; } } | Load s Moodle config so we can use Moodle APIs . |
49,839 | public function getComponentInstallDirectory ( $ component ) { list ( $ type , $ name ) = $ this -> normalizeComponent ( $ component ) ; $ method = new \ ReflectionMethod ( 'core_component' , 'fetch_plugintypes' ) ; $ method -> setAccessible ( true ) ; $ result = $ method -> invoke ( null ) ; if ( ! array_key_exists ( $ type , $ result [ 0 ] ) ) { throw new \ InvalidArgumentException ( sprintf ( 'The component %s has an unknown plugin type of %s' , $ component , $ type ) ) ; } return $ result [ 0 ] [ $ type ] . '/' . $ name ; } | Get the absolute install directory path within Moodle . |
49,840 | public function getConfig ( $ name ) { $ this -> requireConfig ( ) ; if ( ! property_exists ( $ this -> cfg , $ name ) ) { throw new \ RuntimeException ( sprintf ( 'Failed to find $CFG->%s in Moodle config file' , $ name ) ) ; } return $ this -> cfg -> $ name ; } | Get a Moodle config value . |
49,841 | private function resolveDatabaseType ( $ type ) { foreach ( $ this -> getDatabases ( ) as $ database ) { if ( $ database -> type === $ type ) { return $ database ; } } throw new \ DomainException ( sprintf ( 'Unknown database type (%s). Please use mysqli, pgsql or mariadb.' , $ type ) ) ; } | Resolve database class . |
49,842 | public function createContents ( AbstractDatabase $ database , $ dataDir ) { $ template = file_get_contents ( __DIR__ . '/../../res/template/config.php.txt' ) ; $ variables = [ '{{DBTYPE}}' => $ database -> type , '{{DBLIBRARY}}' => $ database -> library , '{{DBHOST}}' => $ database -> host , '{{DBNAME}}' => $ database -> name , '{{DBUSER}}' => $ database -> user , '{{DBPASS}}' => $ database -> pass , '{{WWWROOT}}' => 'http://localhost/moodle' , '{{DATAROOT}}' => $ dataDir , '{{PHPUNITDATAROOT}}' => $ dataDir . '/phpu_moodledata' , '{{BEHATDATAROOT}}' => $ dataDir . '/behat_moodledata' , '{{BEHATDUMP}}' => $ dataDir . '/behat_dump' , '{{BEHATWWWROOT}}' => 'http://localhost:8000' , '{{EXTRACONFIG}}' => self :: PLACEHOLDER , ] ; return str_replace ( array_keys ( $ variables ) , array_values ( $ variables ) , $ template ) ; } | Create a Moodle config . |
49,843 | public function injectLine ( $ contents , $ lineToAdd ) { if ( strpos ( $ contents , self :: PLACEHOLDER ) === false ) { throw new \ RuntimeException ( 'Failed to find placeholder in config file, file might be malformed' ) ; } return str_replace ( self :: PLACEHOLDER , $ lineToAdd . "\n" . self :: PLACEHOLDER , $ contents ) ; } | Adds a line of PHP code into the config file . |
49,844 | public function dump ( $ file , $ contents ) { $ filesystem = new Filesystem ( ) ; $ filesystem -> dumpFile ( $ file , $ contents ) ; $ filesystem -> chmod ( $ file , 0644 ) ; } | Write the config file contents out to the config file . |
49,845 | public function compare ( $ string ) { foreach ( $ this -> tokens as $ token ) { if ( $ token -> hasTokenBeenFound ( ) ) { continue ; } $ token -> compare ( $ string ) ; } } | Given some string see if it matches any of our tokens . |
49,846 | protected function isCacheExpired ( $ fromCurrency , $ toCurrency ) { $ cacheCreationTime = $ this -> getCacheCreationTime ( $ fromCurrency , $ toCurrency ) ; return ( time ( ) - $ cacheCreationTime ) > $ this -> getCacheTimeOut ( ) -> format ( '%s' ) ; } | Checks if cache is expired |
49,847 | public function start ( $ message , $ maxSteps ) { $ this -> info ( $ message ) ; if ( $ this -> progressBar instanceof ProgressBar ) { $ this -> progressBar -> setMessage ( $ message ) ; $ this -> progressBar -> start ( $ maxSteps ) ; } } | Starting the install process . |
49,848 | public function step ( $ message ) { ++ $ this -> stepCount ; $ this -> info ( $ message ) ; if ( $ this -> progressBar instanceof ProgressBar ) { $ this -> progressBar -> setMessage ( $ message ) ; $ this -> progressBar -> advance ( ) ; } } | Signify the move to the next step in the install . |
49,849 | public function end ( $ message ) { $ this -> info ( $ message ) ; if ( $ this -> progressBar instanceof ProgressBar ) { $ this -> progressBar -> setMessage ( $ message ) ; $ this -> progressBar -> finish ( ) ; } } | Ending the install process . |
49,850 | public function debug ( $ message , array $ context = [ ] ) { if ( $ this -> logger instanceof LoggerInterface ) { $ this -> logger -> debug ( $ message , $ context ) ; } } | Log a message shown in highest verbosity mode . |
49,851 | public function findFirstVariableAssignment ( array $ statements , $ name , $ notFoundError = null ) { foreach ( $ this -> filterAssignments ( $ statements ) as $ assign ) { if ( $ assign -> var instanceof Variable && $ assign -> var -> name === $ name ) { return $ assign ; } } throw new \ RuntimeException ( $ notFoundError ? : sprintf ( 'Variable assignment $%s not found' , $ name ) ) ; } | Find first variable assignment with a given name . |
49,852 | public function findFirstPropertyFetchAssignment ( array $ statements , $ variable , $ property , $ notFoundError = null ) { foreach ( $ this -> filterAssignments ( $ statements ) as $ assign ) { if ( ! $ assign -> var instanceof PropertyFetch ) { continue ; } if ( $ assign -> var -> name !== $ property ) { continue ; } $ var = $ assign -> var -> var ; if ( $ var instanceof Variable && $ var -> name === $ variable ) { return $ assign ; } } throw new \ RuntimeException ( $ notFoundError ? : sprintf ( 'Variable assignment $%s->%s not found' , $ variable , $ property ) ) ; } | Find first property fetch assignment with a given name . |
49,853 | public function arrayStringKeys ( Array_ $ array ) { $ keys = [ ] ; foreach ( $ array -> items as $ item ) { if ( $ item -> key instanceof String_ ) { $ keys [ ] = $ item -> key -> value ; } } return $ keys ; } | Given an array find all the string keys . |
49,854 | public function add ( AbstractInstaller $ installer ) { $ installer -> setOutput ( $ this -> output ) ; $ this -> installers [ ] = $ installer ; } | Add an installer . |
49,855 | public function mergeEnv ( ) { $ env = [ ] ; foreach ( $ this -> installers as $ installer ) { $ env = array_merge ( $ env , $ installer -> getEnv ( ) ) ; } return $ env ; } | Merge the environment variables from all installers . |
49,856 | public function sumStepCount ( ) { $ sum = 0 ; foreach ( $ this -> installers as $ installer ) { $ sum += $ installer -> stepCount ( ) ; } return $ sum ; } | Get the total number of steps from all installers . |
49,857 | private function getConsolePath ( ) { if ( file_exists ( $ this -> rootDir . '/app/console' ) ) { return $ this -> rootDir . '/app/console' ; } $ finder = new Finder ( ) ; $ files = $ finder -> files ( ) -> depth ( 1 ) -> name ( 'console' ) -> in ( $ this -> rootDir ) ; foreach ( $ files as $ file ) { return $ file -> getPathname ( ) ; } throw new \ UnderflowException ( 'Symfony console application was not found.' ) ; } | Find path to console application |
49,858 | public function resolve ( $ name ) { if ( ! $ this -> hasStandard ( $ name ) ) { throw new \ InvalidArgumentException ( 'Unknown coding standard: ' . $ name ) ; } foreach ( $ this -> standards [ $ name ] as $ location ) { if ( file_exists ( $ location ) ) { return $ location ; } } throw new \ RuntimeException ( sprintf ( 'Failed to find the \'%s\' coding standard, likely need to run Composer install' , $ name ) ) ; } | Find the location of a standard . |
49,859 | public function install ( InstalledRepositoryInterface $ repo , PackageInterface $ package ) { $ this -> logVerbose ( sprintf ( 'Installing Contao sources for %s' , $ package -> getName ( ) ) ) ; parent :: install ( $ repo , $ package ) ; $ this -> addSymlinks ( $ package , $ this -> getContaoRoot ( ) , $ this -> getSources ( $ package ) ) ; $ this -> addCopies ( $ package , $ this -> getFilesRoot ( ) , $ this -> getUserFiles ( $ package ) , self :: DUPLICATE_IGNORE ) ; $ this -> addRunonces ( $ package , $ this -> getRunonces ( $ package ) ) ; $ this -> logVerbose ( '' ) ; } | Add symlinks for Contao sources after installing a package . |
49,860 | public function update ( InstalledRepositoryInterface $ repo , PackageInterface $ initial , PackageInterface $ target ) { if ( ! $ repo -> hasPackage ( $ initial ) ) { throw new \ InvalidArgumentException ( 'Package is not installed: ' . $ initial ) ; } $ this -> logVerbose ( sprintf ( 'Updating Contao sources for %s' , $ initial -> getName ( ) ) ) ; $ contaoRoot = $ this -> getContaoRoot ( ) ; $ this -> removeSymlinks ( $ initial , $ contaoRoot , $ this -> getSources ( $ initial ) ) ; parent :: update ( $ repo , $ initial , $ target ) ; $ this -> addSymlinks ( $ target , $ contaoRoot , $ this -> getSources ( $ target ) ) ; $ this -> addCopies ( $ target , $ this -> getFilesRoot ( ) , $ this -> getUserFiles ( $ target ) , self :: DUPLICATE_IGNORE ) ; $ this -> addRunonces ( $ target , $ this -> getRunonces ( $ target ) ) ; $ this -> logVerbose ( '' ) ; } | Remove symlinks for Contao sources before update then add them again afterwards . |
49,861 | public function uninstall ( InstalledRepositoryInterface $ repo , PackageInterface $ package ) { if ( ! $ repo -> hasPackage ( $ package ) ) { throw new \ InvalidArgumentException ( 'Package is not installed: ' . $ package ) ; } $ this -> logVerbose ( sprintf ( 'Removing Contao sources for %s' , $ package -> getName ( ) ) ) ; $ this -> removeSymlinks ( $ package , $ this -> getContaoRoot ( ) , $ this -> getSources ( $ package ) ) ; parent :: uninstall ( $ repo , $ package ) ; $ this -> logVerbose ( '' ) ; } | Remove symlinks for Contao sources before uninstalling a package . |
49,862 | protected function addSymlinks ( PackageInterface $ package , $ targetRoot , array $ pathMap , $ mode = self :: DUPLICATE_FAIL ) { if ( empty ( $ pathMap ) ) { return ; } $ packageRoot = $ this -> getInstallPath ( $ package ) ; $ actions = [ ] ; foreach ( $ pathMap as $ sourcePath => $ targetPath ) { $ source = $ this -> filesystem -> normalizePath ( $ packageRoot . ( $ sourcePath ? ( '/' . $ sourcePath ) : '' ) ) ; $ target = $ this -> filesystem -> normalizePath ( $ targetRoot . '/' . $ targetPath ) ; if ( $ this -> canAddSymlink ( $ source , $ target , $ mode ) ) { $ actions [ $ source ] = $ target ; } } foreach ( $ actions as $ source => $ target ) { $ this -> logSymlink ( $ source , $ target ) ; $ this -> filesystem -> ensureDirectoryExists ( dirname ( $ target ) ) ; if ( Platform :: isWindows ( ) ) { $ success = @ symlink ( $ source , $ target ) ; } else { $ success = $ this -> filesystem -> relativeSymlink ( $ source , $ target ) ; } if ( ! $ success ) { throw new \ RuntimeException ( 'Failed to create symlink ' . $ target ) ; } } } | Creates symlinks for a map of relative file paths . Key is the relative path to composer package whereas value is relative to Contao root . |
49,863 | protected function removeSymlinks ( PackageInterface $ package , $ targetRoot , array $ pathMap , $ mode = self :: INVALID_FAIL ) { if ( empty ( $ pathMap ) ) { return ; } $ packageRoot = $ this -> getInstallPath ( $ package ) ; $ actions = [ ] ; foreach ( $ pathMap as $ sourcePath => $ targetPath ) { $ source = $ this -> filesystem -> normalizePath ( $ packageRoot . ( $ sourcePath ? ( '/' . $ sourcePath ) : '' ) ) ; $ target = $ this -> filesystem -> normalizePath ( $ targetRoot . '/' . $ targetPath ) ; if ( $ this -> canRemoveSymlink ( $ source , $ target , $ mode ) ) { $ actions [ ] = $ target ; } } foreach ( $ actions as $ target ) { $ this -> logRemove ( $ target ) ; if ( is_dir ( $ target ) ) { $ this -> filesystem -> removeDirectory ( $ target ) ; } else { $ this -> filesystem -> unlink ( $ target ) ; } $ this -> removeEmptyDirectories ( dirname ( $ target ) , $ targetRoot ) ; } } | Removes symlinks from a map of relative file paths . Key is the relative path to composer package whereas value is relative to Contao root . |
49,864 | protected function addCopies ( PackageInterface $ package , $ targetRoot , array $ pathMap , $ mode = self :: DUPLICATE_FAIL ) { if ( empty ( $ pathMap ) ) { return ; } $ packageRoot = $ this -> getInstallPath ( $ package ) ; $ actions = [ ] ; foreach ( $ pathMap as $ sourcePath => $ targetPath ) { $ source = $ this -> filesystem -> normalizePath ( $ packageRoot . ( empty ( $ sourcePath ) ? '' : ( '/' . $ sourcePath ) ) ) ; $ target = $ this -> filesystem -> normalizePath ( $ targetRoot . '/' . $ targetPath ) ; if ( ! is_readable ( $ source ) ) { throw new \ RuntimeException ( sprintf ( 'Installation source "%s" does not exist' , $ sourcePath ) ) ; } if ( file_exists ( $ target ) && ! $ this -> canAddTarget ( $ target , $ mode ) ) { continue ; } $ actions [ $ source ] = $ target ; } foreach ( $ actions as $ source => $ target ) { $ this -> logCopy ( $ source , $ target ) ; $ this -> copyRecursive ( $ source , $ target ) ; } } | Creates copies for a map of relative file paths . Key is the relative path to composer package whereas value is relative to Contao root . |
49,865 | protected function removeCopies ( $ targetRoot , array $ pathMap ) { if ( empty ( $ pathMap ) ) { return ; } $ actions = [ ] ; foreach ( $ pathMap as $ targetPath ) { $ target = $ this -> filesystem -> normalizePath ( $ targetRoot . '/' . $ targetPath ) ; if ( ! file_exists ( $ target ) ) { continue ; } $ actions [ ] = $ target ; } foreach ( $ actions as $ target ) { $ this -> logRemove ( $ target ) ; $ this -> filesystem -> unlink ( $ target ) ; $ this -> removeEmptyDirectories ( dirname ( $ target ) , $ targetRoot ) ; } } | Removes copies from a map of relative file paths . Key is the relative path to composer package whereas value is relative to Contao root . |
49,866 | protected function addRunonces ( PackageInterface $ package , array $ files ) { $ rootDir = $ this -> getInstallPath ( $ package ) ; foreach ( $ files as $ file ) { $ this -> runonceManager -> addFile ( $ this -> filesystem -> normalizePath ( $ rootDir . '/' . $ file ) ) ; } } | Adds runonce files of a package to the RunonceManager instance . |
49,867 | private function copyRecursive ( $ source , $ target ) { if ( ! is_dir ( $ source ) ) { $ this -> filesystem -> ensureDirectoryExists ( dirname ( $ target ) ) ; copy ( $ source , $ target ) ; return ; } $ iterator = new \ RecursiveIteratorIterator ( new \ RecursiveDirectoryIterator ( $ source , \ RecursiveDirectoryIterator :: SKIP_DOTS ) , \ RecursiveIteratorIterator :: SELF_FIRST ) ; $ this -> filesystem -> ensureDirectoryExists ( $ target ) ; foreach ( $ iterator as $ file ) { $ targetPath = $ target . DIRECTORY_SEPARATOR . $ iterator -> getSubPathName ( ) ; if ( $ file -> isDir ( ) ) { $ this -> filesystem -> ensureDirectoryExists ( $ targetPath ) ; } else { copy ( $ file -> getPathname ( ) , $ targetPath ) ; } } } | Recursive copy source file or directory to target path . |
49,868 | private function removeEmptyDirectories ( $ pathname , $ root ) { if ( is_dir ( $ pathname ) && $ pathname !== $ root && $ this -> filesystem -> isDirEmpty ( $ pathname ) ) { $ this -> filesystem -> removeDirectory ( $ pathname ) ; if ( ! $ this -> removeEmptyDirectories ( dirname ( $ pathname ) , $ root ) ) { if ( $ this -> io -> isVeryVerbose ( ) ) { $ this -> io -> writeError ( sprintf ( ' - Removing empty directory "%s"' , $ pathname ) ) ; } } return true ; } return false ; } | Clean up empty directories . |
49,869 | private function canAddSymlink ( $ source , $ target , $ mode ) { if ( ! is_readable ( $ source ) ) { throw new \ RuntimeException ( sprintf ( 'Installation source "%s" does not exist or is not readable' , $ source ) ) ; } if ( file_exists ( $ target ) ) { if ( is_link ( $ target ) && $ source === realpath ( $ target ) ) { return false ; } if ( ! $ this -> canAddTarget ( $ target , $ mode ) ) { return false ; } } return true ; } | Check if the source exists is readable and shall get symlink ed to the target . |
49,870 | private function canRemoveSymlink ( $ source , $ target , $ mode ) { if ( ! file_exists ( $ target ) ) { return false ; } if ( ! is_link ( $ target ) || $ this -> filesystem -> normalizePath ( $ source ) !== $ this -> filesystem -> normalizePath ( realpath ( $ target ) ) ) { if ( self :: INVALID_IGNORE === $ mode ) { return false ; } if ( self :: INVALID_FAIL === $ mode ) { throw new \ RuntimeException ( sprintf ( '"%s" is not a link to "%s" (expected "%s" but got "%s")' , $ target , $ source , $ this -> filesystem -> normalizePath ( $ source ) , $ this -> filesystem -> normalizePath ( realpath ( $ target ) ) ) ) ; } } return true ; } | Check if the target exists is a symlink and the symlink points to the target and therefore shall get removed . |
49,871 | private function canAddTarget ( $ target , $ mode ) { if ( $ mode === self :: DUPLICATE_IGNORE ) { return false ; } if ( $ mode !== self :: DUPLICATE_OVERWRITE || ! $ this -> filesystem -> remove ( $ target ) ) { throw new \ RuntimeException ( sprintf ( 'Installation target "%s" already exists' , $ target ) ) ; } return true ; } | Checks if the target file should be added based on the given mode . |
49,872 | public static function getCurrency ( $ countryCode ) { if ( ! array_key_exists ( $ countryCode , self :: $ currencies ) ) { throw new Exception \ InvalidArgumentException ( sprintf ( 'Unsupported Country Code, %s' , $ countryCode ) ) ; } return self :: $ currencies [ $ countryCode ] ; } | Gets Currency code by Country code |
49,873 | private function getContaoExtra ( PackageInterface $ package , $ key ) { $ extras = $ package -> getExtra ( ) ; if ( ! isset ( $ extras [ 'contao' ] ) || ! isset ( $ extras [ 'contao' ] [ $ key ] ) ) { return null ; } return $ extras [ 'contao' ] [ $ key ] ; } | Retrieves a value from the package extra contao section . |
49,874 | public function runInstallation ( InstallerCollection $ installers ) { $ this -> output -> start ( 'Starting install' , $ installers -> sumStepCount ( ) + 1 ) ; foreach ( $ installers -> all ( ) as $ installer ) { $ installer -> install ( ) ; } $ this -> output -> end ( 'Install completed' ) ; } | Run the entire install process . |
49,875 | public function renderReport ( Report $ report ) { $ this -> output -> writeln ( '' ) ; $ groupByFile = [ ] ; foreach ( $ report -> getRuleViolations ( ) as $ violation ) { $ groupByFile [ $ violation -> getFileName ( ) ] [ ] = $ violation ; } foreach ( $ report -> getErrors ( ) as $ error ) { $ groupByFile [ $ error -> getFile ( ) ] [ ] = $ error ; } foreach ( $ groupByFile as $ file => $ problems ) { $ violationCount = 0 ; $ errorCount = 0 ; $ table = new Table ( $ this -> output ) ; $ table -> setStyle ( 'borderless' ) ; foreach ( $ problems as $ problem ) { if ( $ problem instanceof RuleViolation ) { $ table -> addRow ( [ $ problem -> getBeginLine ( ) , '<comment>VIOLATION</comment>' , $ problem -> getDescription ( ) ] ) ; ++ $ violationCount ; } if ( $ problem instanceof ProcessingError ) { $ table -> addRow ( [ '-' , '<error>ERROR</error>' , $ problem -> getMessage ( ) ] ) ; ++ $ errorCount ; } } $ this -> output -> writeln ( [ sprintf ( '<fg=white;options=bold>FILE: %s</>' , str_replace ( $ this -> basePath . '/' , '' , $ file ) ) , sprintf ( '<fg=white;options=bold>FOUND %d ERRORS AND %d VIOLATIONS</>' , $ errorCount , $ violationCount ) , ] ) ; $ table -> render ( ) ; $ this -> output -> writeln ( '' ) ; } } | This method will be called when the engine has finished the source analysis phase . |
49,876 | public function initializeInstallerFactory ( InputInterface $ input ) { $ validate = new Validate ( ) ; $ resolver = new DatabaseResolver ( ) ; $ pluginDir = realpath ( $ validate -> directory ( $ input -> getOption ( 'plugin' ) ) ) ; $ pluginsDir = $ input -> getOption ( 'extra-plugins' ) ; if ( ! empty ( $ pluginsDir ) ) { $ pluginsDir = realpath ( $ validate -> directory ( $ pluginsDir ) ) ; } $ factory = new InstallerFactory ( ) ; $ factory -> moodle = new Moodle ( $ input -> getOption ( 'moodle' ) ) ; $ factory -> plugin = new MoodlePlugin ( $ pluginDir ) ; $ factory -> execute = $ this -> execute ; $ factory -> repo = $ validate -> gitUrl ( $ input -> getOption ( 'repo' ) ) ; $ factory -> branch = $ validate -> gitBranch ( $ input -> getOption ( 'branch' ) ) ; $ factory -> dataDir = $ input -> getOption ( 'data' ) ; $ factory -> dumper = $ this -> initializePluginConfigDumper ( $ input ) ; $ factory -> pluginsDir = $ pluginsDir ; $ factory -> noInit = $ input -> getOption ( 'no-init' ) ; $ factory -> database = $ resolver -> resolveDatabase ( $ input -> getOption ( 'db-type' ) , $ input -> getOption ( 'db-name' ) , $ input -> getOption ( 'db-user' ) , $ input -> getOption ( 'db-pass' ) , $ input -> getOption ( 'db-host' ) ) ; return $ factory ; } | Create a new installer factory from input options . |
49,877 | public function csvToArray ( $ value ) { if ( $ value === null ) { return [ ] ; } $ result = explode ( ',' , $ value ) ; $ result = array_map ( 'trim' , $ result ) ; $ result = array_filter ( $ result ) ; return array_values ( $ result ) ; } | Convert a CSV string to an array . |
49,878 | public function addInstallers ( InstallerCollection $ installers ) { $ installers -> add ( new MoodleInstaller ( $ this -> execute , $ this -> database , $ this -> moodle , new MoodleConfig ( ) , $ this -> repo , $ this -> branch , $ this -> dataDir ) ) ; $ installers -> add ( new PluginInstaller ( $ this -> moodle , $ this -> plugin , $ this -> pluginsDir , $ this -> dumper ) ) ; $ installers -> add ( new VendorInstaller ( $ this -> moodle , $ this -> plugin , $ this -> execute ) ) ; if ( $ this -> noInit ) { return ; } if ( $ this -> plugin -> hasBehatFeatures ( ) || $ this -> plugin -> hasUnitTests ( ) ) { $ installers -> add ( new TestSuiteInstaller ( $ this -> moodle , $ this -> plugin , $ this -> execute ) ) ; } } | Given a big bag of install options add installers to the collection . |
49,879 | public function getVendorPaths ( ) { $ base = dirname ( $ this -> path ) ; $ paths = [ ] ; foreach ( $ this -> xml -> xpath ( '/libraries/library/location' ) as $ location ) { $ location = trim ( ( string ) $ location , '/' ) ; $ location = $ base . '/' . $ location ; if ( strpos ( $ location , '*' ) !== false ) { $ locations = glob ( $ location ) ; if ( empty ( $ locations ) ) { throw new \ RuntimeException ( sprintf ( 'Failed to run glob on path: %s' , $ location ) ) ; } $ paths = array_merge ( $ paths , $ locations ) ; } elseif ( ! file_exists ( $ location ) ) { throw new \ RuntimeException ( sprintf ( 'The %s contains a non-existent path: %s' , $ this -> path , $ location ) ) ; } else { $ paths [ ] = $ location ; } } return $ paths ; } | Returns all the third party library paths from the XML file . |
49,880 | public function getRelativeVendorPaths ( ) { $ base = dirname ( $ this -> path ) . '/' ; return array_map ( function ( $ path ) use ( $ base ) { return str_replace ( $ base , '' , $ path ) ; } , $ this -> getVendorPaths ( ) ) ; } | Returns all the third party library paths from the XML file . The paths will be relative to the XML file . |
49,881 | protected function addMoodleOption ( Command $ command ) { $ moodle = getenv ( 'MOODLE_DIR' ) !== false ? getenv ( 'MOODLE_DIR' ) : '.' ; $ command -> addOption ( 'moodle' , 'm' , InputOption :: VALUE_REQUIRED , 'Path to Moodle' , $ moodle ) ; return $ command ; } | Adds the moodle option to a command . |
49,882 | protected function initializeMoodle ( InputInterface $ input ) { if ( ! $ this -> moodle ) { $ validate = new Validate ( ) ; $ moodleDir = realpath ( $ validate -> directory ( $ input -> getOption ( 'moodle' ) ) ) ; $ this -> moodle = new Moodle ( $ moodleDir ) ; } } | Initialize the moodle property based on input if necessary . |
49,883 | public function directory ( $ path ) { $ dir = $ this -> realPath ( $ path ) ; if ( ! is_dir ( $ dir ) ) { throw new \ InvalidArgumentException ( sprintf ( 'The path is not a directory: %s' , $ dir ) ) ; } return $ path ; } | Validate a directory path . |
49,884 | public function filePath ( $ path ) { $ file = $ this -> realPath ( $ path ) ; if ( ! is_file ( $ file ) ) { throw new \ InvalidArgumentException ( sprintf ( 'The path is not a file: %s' , $ file ) ) ; } return $ path ; } | Validate a file path . |
49,885 | public function gitBranch ( $ branch ) { $ options = [ 'options' => [ 'regexp' => '/^[a-zA-Z0-9\/\+\._-]+$/' ] ] ; if ( filter_var ( $ branch , FILTER_VALIDATE_REGEXP , $ options ) === false ) { throw new \ InvalidArgumentException ( sprintf ( "Invalid characters found in git branch name '%s'. Use only letters, numbers, underscore, hyphen and forward slashes." , $ branch ) ) ; } return $ branch ; } | Validate git branch name . |
49,886 | public function gitUrl ( $ url ) { $ options = [ 'options' => [ 'regexp' => '/(?:git|ssh|https?|git@[\w\.]+):(?:\/\/)?[\w\.@:\/~_-]+\.git(?:\/?|\#[\d\w\.\-_]+?)$/' ] ] ; if ( filter_var ( $ url , FILTER_VALIDATE_REGEXP , $ options ) === false ) { throw new \ InvalidArgumentException ( sprintf ( 'Invalid URL: %s' , $ url ) ) ; } return $ url ; } | Validate git URL . |
49,887 | public function restorePlugin ( ) { ( new Filesystem ( ) ) -> mirror ( $ this -> backupDir , $ this -> plugin -> directory , null , [ 'delete' => true , 'override' => true ] ) ; } | Revert any changes Grunt tasks might have done . |
49,888 | public function validatePluginFiles ( OutputInterface $ output ) { $ code = 0 ; $ files = Finder :: create ( ) -> files ( ) -> in ( $ this -> backupDir ) -> name ( '*.js' ) -> name ( '*.css' ) -> getIterator ( ) ; foreach ( $ files as $ file ) { $ compareFile = $ this -> plugin -> directory . '/' . $ file -> getRelativePathname ( ) ; if ( ! file_exists ( $ compareFile ) ) { $ output -> writeln ( sprintf ( '<error>File no longer generated and likely should be deleted: %s</error>' , $ file -> getRelativePathname ( ) ) ) ; $ code = 1 ; continue ; } if ( sha1_file ( $ file -> getPathname ( ) ) !== sha1_file ( $ compareFile ) ) { $ output -> writeln ( sprintf ( '<error>File is stale and needs to be rebuilt: %s</error>' , $ file -> getRelativePathname ( ) ) ) ; $ code = 1 ; } } $ files = Finder :: create ( ) -> files ( ) -> in ( $ this -> plugin -> directory ) -> name ( '*.js' ) -> name ( '*.css' ) -> getIterator ( ) ; foreach ( $ files as $ file ) { if ( ! file_exists ( $ this -> backupDir . '/' . $ file -> getRelativePathname ( ) ) ) { $ output -> writeln ( sprintf ( '<error>File is newly generated and needs to be added: %s</error>' , $ file -> getRelativePathname ( ) ) ) ; $ code = 1 ; } } return $ code ; } | Verify that no plugin files were modified need to be deleted or were added . |
49,889 | public function toGruntTask ( $ task ) { $ workingDirectory = $ this -> moodle -> directory ; if ( is_file ( $ this -> plugin -> directory . '/Gruntfile.js' ) ) { $ workingDirectory = $ this -> plugin -> directory ; } $ defaultTask = new GruntTaskModel ( $ task , $ workingDirectory ) ; switch ( $ task ) { case 'amd' : $ amdDir = $ this -> plugin -> directory . '/amd' ; if ( ! is_dir ( $ amdDir ) ) { return null ; } return new GruntTaskModel ( $ task , $ amdDir , 'amd/build' ) ; case 'shifter' : case 'yui' : $ yuiDir = $ this -> plugin -> directory . '/yui' ; if ( ! is_dir ( $ yuiDir ) ) { return null ; } return new GruntTaskModel ( $ task , $ yuiDir . '/src' , 'yui/build' ) ; case 'gherkinlint' : if ( $ this -> moodle -> getBranch ( ) < 33 || ! $ this -> plugin -> hasBehatFeatures ( ) ) { return null ; } return new GruntTaskModel ( $ task , $ this -> moodle -> directory ) ; case 'stylelint:css' : return $ this -> plugin -> hasFilesWithName ( '*.css' ) ? $ defaultTask : null ; case 'stylelint:less' : return $ this -> plugin -> hasFilesWithName ( '*.less' ) ? $ defaultTask : null ; case 'stylelint:scss' : return $ this -> plugin -> hasFilesWithName ( '*.scss' ) ? $ defaultTask : null ; default : return $ defaultTask ; } } | Create a Grunt Task Model based on the task we are trying to run . |
49,890 | public function getComponent ( ) { if ( ! empty ( $ this -> component ) ) { return $ this -> component ; } $ filter = new StatementFilter ( ) ; $ parser = new CodeParser ( ) ; $ notFound = 'The plugin must define the $plugin->component in the version.php file.' ; $ statements = $ parser -> parseFile ( $ this -> directory . '/version.php' ) ; try { $ assign = $ filter -> findFirstPropertyFetchAssignment ( $ statements , 'plugin' , 'component' , $ notFound ) ; } catch ( \ Exception $ e ) { $ assign = $ filter -> findFirstPropertyFetchAssignment ( $ statements , 'module' , 'component' , $ notFound ) ; } if ( ! $ assign -> expr instanceof String_ ) { throw new \ RuntimeException ( 'The $plugin->component must be assigned to a string in the version.php file.' ) ; } $ this -> component = $ assign -> expr -> value ; return $ this -> component ; } | Get a plugin s component name . |
49,891 | public function getDependencies ( ) { if ( is_array ( $ this -> dependencies ) ) { return $ this -> dependencies ; } $ this -> dependencies = [ ] ; $ filter = new StatementFilter ( ) ; $ parser = new CodeParser ( ) ; $ statements = $ parser -> parseFile ( $ this -> directory . '/version.php' ) ; try { $ assign = $ filter -> findFirstPropertyFetchAssignment ( $ statements , 'plugin' , 'dependencies' ) ; } catch ( \ Exception $ e ) { try { $ assign = $ filter -> findFirstPropertyFetchAssignment ( $ statements , 'module' , 'dependencies' ) ; } catch ( \ Exception $ e ) { return $ this -> dependencies ; } } if ( ! $ assign -> expr instanceof Array_ ) { throw new \ RuntimeException ( 'The $plugin->dependencies must be assigned to an array in the version.php file.' ) ; } $ this -> dependencies = $ filter -> arrayStringKeys ( $ assign -> expr ) ; return $ this -> dependencies ; } | Get a plugin s dependencies . |
49,892 | public function hasFilesWithName ( $ pattern ) { $ result = $ this -> getFiles ( Finder :: create ( ) -> name ( $ pattern ) ) ; return count ( $ result ) !== 0 ; } | Determine if the plugin has any files with a given name pattern . |
49,893 | public function getThirdPartyLibraryPaths ( ) { $ xmlFile = $ this -> directory . '/thirdpartylibs.xml' ; if ( ! is_file ( $ xmlFile ) ) { return [ ] ; } $ vendors = new Vendors ( $ xmlFile ) ; return $ vendors -> getRelativeVendorPaths ( ) ; } | Get paths to 3rd party libraries within the plugin . |
49,894 | public function getIgnores ( ) { $ configFile = $ this -> directory . '/.moodle-plugin-ci.yml' ; if ( ! is_file ( $ configFile ) ) { return [ ] ; } $ config = Yaml :: parse ( file_get_contents ( $ configFile ) ) ; if ( ! empty ( $ this -> context ) && array_key_exists ( 'filter-' . $ this -> context , $ config ) ) { return $ config [ 'filter-' . $ this -> context ] ; } return array_key_exists ( 'filter' , $ config ) ? $ config [ 'filter' ] : [ ] ; } | Get ignore file information . |
49,895 | public function getFiles ( Finder $ finder ) { $ finder -> files ( ) -> in ( $ this -> directory ) -> ignoreUnreadableDirs ( ) ; foreach ( $ this -> getThirdPartyLibraryPaths ( ) as $ libPath ) { $ finder -> notPath ( $ libPath ) ; } $ ignores = $ this -> getIgnores ( ) ; if ( ! empty ( $ ignores [ 'notPaths' ] ) ) { foreach ( $ ignores [ 'notPaths' ] as $ notPath ) { $ finder -> notPath ( $ notPath ) ; } } if ( ! empty ( $ ignores [ 'notNames' ] ) ) { foreach ( $ ignores [ 'notNames' ] as $ notName ) { $ finder -> notName ( $ notName ) ; } } $ files = [ ] ; foreach ( $ finder as $ file ) { $ files [ ] = $ file -> getRealPath ( ) ; } return $ files ; } | Get a list of plugin files . |
49,896 | public function getRelativeFiles ( Finder $ finder ) { $ files = [ ] ; foreach ( $ this -> getFiles ( $ finder ) as $ file ) { $ files [ ] = str_replace ( $ this -> directory . '/' , '' , $ file ) ; } return $ files ; } | Get a list of plugin files with paths relative to the plugin itself . |
49,897 | public function setCacheAdapter ( Cache \ Adapter \ CacheAdapterInterface $ cacheAdapter ) { $ this -> setCachable ( true ) ; $ this -> cacheAdapter = $ cacheAdapter ; return $ this ; } | Sets cache adapter |
49,898 | public function getCacheAdapter ( ) { if ( ! $ this -> cacheAdapter ) { $ this -> setCacheAdapter ( new Cache \ Adapter \ FileSystem ( ) ) ; } return $ this -> cacheAdapter ; } | Gets cache adapter |
49,899 | protected function parseCurrencyArgument ( $ data ) { if ( is_string ( $ data ) ) { $ currency = $ data ; } elseif ( is_array ( $ data ) ) { if ( isset ( $ data [ 'country' ] ) ) { $ currency = CountryToCurrency :: getCurrency ( $ data [ 'country' ] ) ; } elseif ( isset ( $ data [ 'currency' ] ) ) { $ currency = $ data [ 'currency' ] ; } else { throw new Exception \ InvalidArgumentException ( 'Please provide country or currency!' ) ; } } else { throw new Exception \ InvalidArgumentException ( 'Invalid currency provided. String or array expected.' ) ; } return $ currency ; } | Parses the Currency Arguments |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.