idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
16,100
protected function applyUserLocale ( UserInterface $ user ) { $ locale = $ user -> getLocale ( ) ; if ( null === $ lang = LangQuery :: create ( ) -> findOneByLocale ( $ locale ) ) { $ lang = Lang :: getDefaultLanguage ( ) ; } $ this -> getSession ( ) -> setLang ( $ lang ) ; }
Save user locale preference in session .
16,101
protected function addConnection ( $ name , array $ parameters = [ ] , array $ envParameters = [ ] ) { $ connectionParameterBag = new ParameterBag ( $ envParameters ) ; $ connectionParameterBag -> add ( $ parameters ) ; $ connectionParameterBag -> resolve ( ) ; $ this -> connections [ $ name ] = $ connectionParameterBag ; }
Create and resolve a ParameterBag for a connection . Add the bag to the connections map .
16,102
public function setupFieldAssociations ( $ fields , $ table , $ fieldConditions , $ strategy ) { $ config = $ this -> getConfig ( ) ; $ this -> _table -> hasMany ( $ config [ 'translationTable' ] , [ 'className' => $ config [ 'translationTable' ] , 'foreignKey' => 'id' , 'strategy' => $ strategy , 'propertyName' => '_i18n' , 'dependent' => true , ] ) ; }
Create a hasMany association for all records
16,103
protected function _addFieldsToQuery ( Query $ query , array $ config ) { if ( $ query -> isAutoFieldsEnabled ( ) ) { return true ; } $ select = array_filter ( $ query -> clause ( 'select' ) , function ( $ field ) { return is_string ( $ field ) ; } ) ; if ( ! $ select ) { return true ; } $ alias = $ config [ 'mainTableAlias' ] ; $ joinRequired = false ; foreach ( $ this -> _translationFields ( ) as $ field ) { if ( array_intersect ( $ select , [ $ field , "$alias.$field" ] ) ) { $ joinRequired = true ; $ query -> select ( $ query -> aliasField ( $ field , $ config [ 'hasOneAlias' ] ) ) ; } } if ( $ joinRequired ) { $ query -> select ( $ query -> aliasField ( 'locale' , $ config [ 'hasOneAlias' ] ) ) ; } return $ joinRequired ; }
Add translation fields to query
16,104
protected function _iterateClause ( Query $ query , $ name = '' , $ config = [ ] ) { $ clause = $ query -> clause ( $ name ) ; if ( ! $ clause || ! $ clause -> count ( ) ) { return false ; } $ alias = $ config [ 'hasOneAlias' ] ; $ fields = $ this -> _translationFields ( ) ; $ mainTableAlias = $ config [ 'mainTableAlias' ] ; $ mainTableFields = $ this -> _mainFields ( ) ; $ joinRequired = false ; $ clause -> iterateParts ( function ( $ c , & $ field ) use ( $ fields , $ alias , $ mainTableAlias , $ mainTableFields , & $ joinRequired ) { if ( ! is_string ( $ field ) || strpos ( $ field , '.' ) ) { return $ c ; } if ( in_array ( $ field , $ fields ) ) { $ joinRequired = true ; $ field = "$alias.$field" ; } elseif ( in_array ( $ field , $ mainTableFields ) ) { $ field = "$mainTableAlias.$field" ; } return $ c ; } ) ; return $ joinRequired ; }
Iterate over a clause to alias fields
16,105
protected function _traverseClause ( Query $ query , $ name = '' , $ config = [ ] ) { $ clause = $ query -> clause ( $ name ) ; if ( ! $ clause || ! $ clause -> count ( ) ) { return false ; } $ alias = $ config [ 'hasOneAlias' ] ; $ fields = $ this -> _translationFields ( ) ; $ mainTableAlias = $ config [ 'mainTableAlias' ] ; $ mainTableFields = $ this -> _mainFields ( ) ; $ joinRequired = false ; $ clause -> traverse ( function ( $ expression ) use ( $ fields , $ alias , $ mainTableAlias , $ mainTableFields , & $ joinRequired ) { if ( ! ( $ expression instanceof FieldInterface ) ) { return ; } $ field = $ expression -> getField ( ) ; if ( ! is_string ( $ field ) || strpos ( $ field , '.' ) ) { return ; } if ( in_array ( $ field , $ fields ) ) { $ joinRequired = true ; $ expression -> setField ( "$alias.$field" ) ; return ; } if ( in_array ( $ field , $ mainTableFields ) ) { $ expression -> setField ( "$mainTableAlias.$field" ) ; } } ) ; return $ joinRequired ; }
Traverse over a clause to alias fields
16,106
protected function _mainFields ( ) { $ fields = $ this -> getConfig ( 'mainTableFields' ) ; if ( $ fields ) { return $ fields ; } $ table = $ this -> _table ; $ fields = $ table -> getSchema ( ) -> columns ( ) ; $ this -> setConfig ( 'mainTableFields' , $ fields ) ; return $ fields ; }
Lazy define and return the main table fields
16,107
protected function _translationFields ( ) { $ fields = $ this -> getConfig ( 'fields' ) ; if ( $ fields ) { return $ fields ; } $ table = $ this -> _translationTable ( ) ; $ fields = $ table -> getSchema ( ) -> columns ( ) ; $ fields = array_values ( array_diff ( $ fields , [ 'id' , 'locale' ] ) ) ; $ this -> setConfig ( 'fields' , $ fields ) ; return $ fields ; }
Lazy define and return the translation table fields
16,108
public static function getI18n ( $ backendContext , $ requestedLangId , ModelCriteria & $ search , $ currentLocale , $ columns , $ foreignTable , $ foreignKey , $ forceReturn = false , $ localeAlias = null ) { if ( $ requestedLangId !== null ) { $ localeSearch = LangQuery :: create ( ) -> findByIdOrLocale ( $ requestedLangId ) ; if ( $ localeSearch === null ) { throw new \ InvalidArgumentException ( sprintf ( 'Incorrect lang argument given : lang %s not found' , $ requestedLangId ) ) ; } $ locale = $ localeSearch -> getLocale ( ) ; } else { $ locale = $ currentLocale ; } if ( $ backendContext ) { self :: getBackEndI18n ( $ search , $ locale , $ columns , $ foreignTable , $ foreignKey , $ localeAlias ) ; } else { self :: getFrontEndI18n ( $ search , $ locale , $ columns , $ foreignTable , $ foreignKey , $ forceReturn , $ localeAlias ) ; } return $ locale ; }
Bild query to retrieve I18n
16,109
public function provideFilesToCheck ( ) { $ iterator = new AppendIterator ( ) ; foreach ( $ this -> getPaths ( ) as $ path ) { $ iterator -> append ( new RecursiveIteratorIterator ( new RecursiveDirectoryIterator ( $ path ) ) ) ; } $ files = new CallbackFilterIterator ( $ iterator , function ( $ file ) { return $ file -> getFilename ( ) [ 0 ] !== '.' && ! $ file -> isDir ( ) ; } ) ; return array_map ( function ( $ file ) { return [ ( string ) $ file ] ; } , iterator_to_array ( $ files ) ) ; }
Get the files to check .
16,110
public function isConnectScreen ( $ screen ) { $ base = ! empty ( $ screen -> base ) ? $ screen -> base : null ; return 'settings_page_boldgrid-connect' === $ base ; }
Check if the current screen is the connect screen .
16,111
public function addScripts ( ) { if ( $ this -> isConnectScreen ( get_current_screen ( ) ) ) { $ handle = 'bglib-connect' ; wp_register_script ( $ handle , Configs :: get ( 'libraryUrl' ) . 'src/assets/js/connect.js' , array ( 'jquery' ) , date ( 'Ymd' ) , false ) ; $ translation = array ( 'settingsSaved' => __ ( 'Settings saved.' , 'boldgrid-library' ) , 'unknownError' => __ ( 'Unknown error.' , 'boldgrid-library' ) , 'ajaxError' => __ ( 'Could not reach the AJAX URL address. HTTP error: ' , 'boldgrid-library' ) , ) ; wp_localize_script ( $ handle , 'BoldGridLibraryConnect' , $ translation ) ; wp_enqueue_script ( $ handle ) ; wp_enqueue_script ( 'jquery-toggles' , Configs :: get ( 'libraryUrl' ) . 'build/toggles.min.js' , array ( 'jquery' ) , date ( 'Ymd' ) , true ) ; wp_enqueue_style ( 'jquery-toggles-full' , Configs :: get ( 'libraryUrl' ) . 'build/toggles-full.css' , array ( ) , date ( 'Ymd' ) ) ; do_action ( 'Boldgrid\Library\Library\Page\Connect\addScripts' ) ; } }
Enqueue scripts needed for this page .
16,112
public function saveSettings ( ) { if ( ! current_user_can ( 'update_plugins' ) ) { wp_send_json_error ( array ( 'error' => __ ( 'User access violation!' , 'boldgrid-library' ) , ) ) ; } if ( ! check_admin_referer ( 'boldgrid_library_connect_settings_save' ) ) { wp_send_json_error ( array ( 'error' => __ ( 'Security violation! Please try again.' , 'boldgrid-library' ) , ) ) ; } $ boldgridSettings = array_merge ( get_option ( 'boldgrid_settings' ) , self :: sanitizeSettings ( array ( 'autoupdate' => ! empty ( $ _POST [ 'autoupdate' ] ) ? ( array ) $ _POST [ 'autoupdate' ] : array ( ) , 'release_channel' => ! empty ( $ _POST [ 'plugin_release_channel' ] ) ? sanitize_key ( $ _POST [ 'plugin_release_channel' ] ) : 'stable' , 'theme_release_channel' => ! empty ( $ _POST [ 'theme_release_channel' ] ) ? sanitize_key ( $ _POST [ 'theme_release_channel' ] ) : 'stable' , ) ) ) ; if ( ! empty ( $ _POST [ 'autoupdate' ] ) ) { unset ( $ boldgridSettings [ 'plugin_autoupdate' ] , $ boldgridSettings [ 'theme_autoupdate' ] ) ; } update_option ( 'boldgrid_settings' , $ boldgridSettings ) ; wp_send_json_success ( ) ; }
AJAX callback for the Connect Settings page .
16,113
public static function sanitizeSettings ( array $ settings ) { $ result = array ( ) ; if ( ! empty ( $ settings [ 'autoupdate' ] ) && is_array ( $ settings [ 'autoupdate' ] ) ) { foreach ( $ settings [ 'autoupdate' ] as $ category => $ itemSetting ) { $ category = sanitize_key ( $ category ) ; foreach ( $ itemSetting as $ id => $ val ) { $ id = sanitize_text_field ( $ id ) ; $ result [ 'autoupdate' ] [ $ category ] [ $ id ] = ( bool ) $ val ; } } } $ channels = array ( 'stable' , 'edge' , 'candidate' , ) ; if ( empty ( $ settings [ 'release_channel' ] ) || ! in_array ( $ settings [ 'release_channel' ] , $ channels , true ) ) { $ result [ 'release_channel' ] = 'stable' ; } else { $ result [ 'release_channel' ] = $ settings [ 'release_channel' ] ; } if ( empty ( $ settings [ 'theme_release_channel' ] ) || ! in_array ( $ settings [ 'theme_release_channel' ] , $ channels , true ) ) { $ result [ 'theme_release_channel' ] = 'stable' ; } else { $ result [ 'theme_release_channel' ] = $ settings [ 'theme_release_channel' ] ; } return $ result ; }
Sanitize settings .
16,114
protected function trans ( $ context , $ key ) { $ message = "" ; if ( array_key_exists ( $ context , $ this -> messages ) ) { if ( array_key_exists ( $ key , $ this -> messages [ $ context ] ) ) { $ message = $ this -> messages [ $ context ] [ $ key ] ; } } return $ message ; }
Translate Hook labels
16,115
public static function getPathToCategory ( $ categoryId ) { $ path = [ ] ; $ category = ( new CategoryQuery ) -> findPk ( $ categoryId ) ; if ( $ category !== null ) { $ path [ ] = $ category ; if ( $ category -> getParent ( ) !== 0 ) { $ path = array_merge ( self :: getPathToCategory ( $ category -> getParent ( ) ) , $ path ) ; } } return $ path ; }
Get categories from root to child
16,116
public function getPathInfo ( ) { $ pathInfo = parent :: getPathInfo ( ) ; $ pathLength = \ strlen ( $ pathInfo ) ; if ( $ pathInfo !== '/' && $ pathInfo [ $ pathLength - 1 ] === '/' && ( bool ) ConfigQuery :: read ( 'allow_slash_ended_uri' , false ) ) { if ( null === $ this -> resolvedPathInfo ) { $ this -> resolvedPathInfo = substr ( $ pathInfo , 0 , $ pathLength - 1 ) ; } $ pathInfo = $ this -> resolvedPathInfo ; } return $ pathInfo ; }
Filter PathInfo to allow slash ending uri
16,117
public function preUpgradePlugin ( $ options ) { $ plugin = ! empty ( $ options [ 'hook_extra' ] [ 'plugin' ] ) ? $ options [ 'hook_extra' ] [ 'plugin' ] : null ; $ isBoldgridPlugin = \ Boldgrid \ Library \ Library \ Util \ Plugin :: isBoldgridPlugin ( $ plugin ) ; if ( $ isBoldgridPlugin ) { $ utilPlugin = new \ Boldgrid \ Library \ Util \ Registration \ Plugin ( $ plugin ) ; $ utilPlugin -> deregister ( ) ; } return $ options ; }
Take action before a plugin is upgraded .
16,118
public function getDomains ( ) { $ domains = array ( ) ; $ checks = $ this -> getChecks ( ) ; foreach ( $ checks as $ check ) { $ domains [ $ check -> id ] = $ check -> hostname ; } return $ domains ; }
Fetches the list of domains being monitored in Pingdom .
16,119
public function getChecks ( $ limit = NULL , $ offset = NULL ) { $ parameters = array ( ) ; if ( ! empty ( $ limit ) ) { $ parameters [ 'limit' ] = $ limit ; if ( ! empty ( $ offset ) ) { $ parameters [ 'offset' ] = $ offset ; } } $ data = $ this -> request ( 'GET' , 'checks' , $ parameters ) ; return $ data -> checks ; }
Retrieves a list of checks .
16,120
public function getCheck ( $ check_id ) { $ this -> ensureParameters ( array ( 'check_id' => $ check_id ) , __METHOD__ ) ; $ data = $ this -> request ( 'GET' , "checks/${check_id}" ) ; return $ data -> check ; }
Retrieves detailed information about a specified check .
16,121
public function addCheck ( $ check , $ defaults = array ( ) ) { $ this -> ensureParameters ( array ( 'name' => $ check [ 'name' ] , 'host' => $ check [ 'host' ] , 'url' => $ check [ 'url' ] , ) , __METHOD__ ) ; $ check += $ defaults ; $ data = $ this -> request ( 'POST' , 'checks' , $ check ) ; return sprintf ( 'Created check %s for %s at http://%s%s' , $ data -> check -> id , $ check [ 'name' ] , $ check [ 'host' ] , $ check [ 'url' ] ) ; }
Adds a new check .
16,122
public function pauseCheck ( $ check_id ) { $ this -> ensureParameters ( array ( 'check_id' => $ check_id ) , __METHOD__ ) ; $ check = array ( 'paused' => TRUE , ) ; return $ this -> modifyCheck ( $ check_id , $ check ) ; }
Pauses a check .
16,123
public function unpauseCheck ( $ check_id ) { $ this -> ensureParameters ( array ( 'check_id' => $ check_id ) , __METHOD__ ) ; $ check = array ( 'paused' => FALSE , ) ; return $ this -> modifyCheck ( $ check_id , $ check ) ; }
Unpauses a check .
16,124
public function pauseChecks ( $ check_ids ) { $ this -> ensureParameters ( array ( 'check_ids' => $ check_ids ) , __METHOD__ ) ; $ parameters = array ( 'paused' => TRUE , ) ; return $ this -> modifyChecks ( $ check_ids , $ parameters ) ; }
Pauses multiple checks .
16,125
public function unpauseChecks ( $ check_ids ) { $ this -> ensureParameters ( array ( 'check_ids' => $ check_ids ) , __METHOD__ ) ; $ parameters = array ( 'paused' => FALSE , ) ; return $ this -> modifyChecks ( $ check_ids , $ parameters ) ; }
Unpauses multiple checks .
16,126
public function modifyCheck ( $ check_id , $ parameters ) { $ this -> ensureParameters ( array ( 'check_id' => $ check_id , 'parameters' => $ parameters , ) , __METHOD__ ) ; $ data = $ this -> request ( 'PUT' , "checks/${check_id}" , $ parameters ) ; return $ data -> message ; }
Modifies a check .
16,127
public function modifyChecks ( $ check_ids , $ parameters ) { $ this -> ensureParameters ( array ( 'check_ids' => $ check_ids , 'parameters' => $ parameters , ) , __METHOD__ ) ; $ parameters [ 'checkids' ] = implode ( ',' , $ check_ids ) ; $ data = $ this -> request ( 'PUT' , 'checks' , $ parameters ) ; return $ data -> message ; }
Modifies multiple checks .
16,128
public function modifyAllChecks ( $ parameters ) { $ this -> ensureParameters ( array ( 'parameters' => $ parameters ) , __METHOD__ ) ; $ data = $ this -> request ( 'PUT' , 'checks' , $ parameters ) ; return $ data -> message ; }
Modifies all checks .
16,129
public function removeCheck ( $ check_id ) { $ this -> ensureParameters ( array ( 'check_id' => $ check_id ) , __METHOD__ ) ; $ data = $ this -> request ( 'DELETE' , "checks/${check_id}" ) ; return $ data -> message ; }
Removes a check .
16,130
public function getContacts ( $ limit = NULL , $ offset = NULL ) { $ parameters = array ( ) ; if ( ! empty ( $ limit ) ) { $ parameters [ 'limit' ] = $ limit ; if ( ! empty ( $ offset ) ) { $ parameters [ 'offset' ] = $ offset ; } } $ data = $ this -> request ( 'GET' , 'contacts' , $ parameters ) ; return $ data -> contacts ; }
Gets the list of contacts stored in Pingdom .
16,131
public function getAnalysis ( $ check_id , $ parameters = array ( ) ) { $ this -> ensureParameters ( array ( 'check_id' => $ check_id ) , __METHOD__ ) ; $ data = $ this -> request ( 'GET' , "analysis/${check_id}" , $ parameters ) ; return $ data -> analysis ; }
Fetches the latest root cause analysis results for a specified check .
16,132
public function getRawAnalysis ( $ check_id , $ analysis_id , $ parameters = array ( ) ) { $ this -> ensureParameters ( array ( 'check_id' => $ check_id , 'analysis_id' => $ analysis_id , ) , __METHOD__ ) ; $ data = $ this -> request ( 'GET' , "analysis/{$check_id}/{$analysis_id}" , $ parameters ) ; return $ data ; }
Fetches the raw root cause analysis for a specified check .
16,133
public function ensureParameters ( $ parameters = array ( ) , $ method ) { if ( empty ( $ parameters ) || empty ( $ method ) ) { throw new MissingParameterException ( sprintf ( '%s called without required parameters.' , __METHOD__ ) ) ; } foreach ( $ parameters as $ parameter => $ value ) { if ( ! isset ( $ value ) ) { throw new MissingParameterException ( sprintf ( 'Missing required %s parameter in %s' , $ parameter , $ method ) ) ; } } }
Checks that required parameters were provided .
16,134
public function request ( $ method , $ resource , $ parameters = array ( ) , $ headers = array ( ) , $ body = NULL ) { $ handle = curl_init ( ) ; $ headers [ ] = 'Content-Type: application/json; charset=utf-8' ; $ headers [ ] = 'App-Key: ' . $ this -> api_key ; if ( ! empty ( $ this -> account_email ) ) { $ headers [ ] = 'Account-Email: ' . $ this -> account_email ; } if ( ! empty ( $ body ) ) { if ( ! is_string ( $ body ) ) { $ body = json_encode ( $ body ) ; } curl_setopt ( $ handle , CURLOPT_POSTFIELDS , $ body ) ; $ headers [ ] = 'Content-Length: ' . strlen ( $ body ) ; } if ( ! empty ( $ headers ) ) { curl_setopt ( $ handle , CURLOPT_HTTPHEADER , $ headers ) ; } curl_setopt ( $ handle , CURLOPT_CUSTOMREQUEST , $ method ) ; curl_setopt ( $ handle , CURLOPT_URL , $ this -> buildRequestUrl ( $ resource , $ parameters ) ) ; curl_setopt ( $ handle , CURLOPT_USERPWD , $ this -> getAuth ( ) ) ; curl_setopt ( $ handle , CURLOPT_FOLLOWLOCATION , TRUE ) ; curl_setopt ( $ handle , CURLOPT_MAXREDIRS , 10 ) ; curl_setopt ( $ handle , CURLOPT_USERAGENT , 'PingdomApi/1.0' ) ; curl_setopt ( $ handle , CURLOPT_RETURNTRANSFER , TRUE ) ; curl_setopt ( $ handle , CURLOPT_TIMEOUT , 10 ) ; $ gzip = ! empty ( $ this -> gzip ) ? 'gzip' : '' ; curl_setopt ( $ handle , CURLOPT_ENCODING , $ gzip ) ; $ response = curl_exec ( $ handle ) ; if ( curl_errno ( $ handle ) > 0 ) { $ curl_error = sprintf ( 'Curl error: %s' , curl_error ( $ handle ) ) ; curl_close ( $ handle ) ; throw new CurlErrorException ( $ curl_error , $ curl_errno ) ; } $ data = json_decode ( $ response ) ; $ status = curl_getinfo ( $ handle , CURLINFO_HTTP_CODE ) ; curl_close ( $ handle ) ; $ status_class = ( int ) floor ( $ status / 100 ) ; if ( $ status_class === 4 || $ status_class === 5 ) { $ message = $ this -> getError ( $ data , $ status ) ; switch ( $ status_class ) { case 4 : throw new ClientErrorException ( sprintf ( 'Client error: %s' , $ message ) , $ status ) ; case 5 : throw new ServerErrorException ( sprintf ( 'Server error: %s' , $ message ) , $ status ) ; } } return $ data ; }
Makes a request to the Pingdom REST API .
16,135
public function buildRequestUrl ( $ resource , $ parameters = array ( ) ) { foreach ( $ parameters as $ property => $ value ) { if ( is_bool ( $ value ) ) { $ parameters [ $ property ] = $ value ? 'true' : 'false' ; } } $ query = empty ( $ parameters ) ? '' : '?' . http_build_query ( $ parameters , NULL , '&' ) ; return sprintf ( '%s/%s%s' , self :: ENDPOINT , $ resource , $ query ) ; }
Builds the request URL .
16,136
protected function getError ( $ response_data , $ status ) { if ( ! empty ( $ response_data -> error ) ) { $ error = $ response_data -> error ; $ message = sprintf ( '%s %s: %s' , $ error -> statuscode , $ error -> statusdesc , $ error -> errormessage ) ; } else { $ message = sprintf ( 'Error code: %s. No reason was given by Pingdom for the error.' , $ status ) ; } return $ message ; }
Gets the human - readable error message for a failed request .
16,137
protected function getArgDefinitions ( ) { return new ArgumentCollection ( Argument :: createIntListTypeArgument ( 'id' ) , Argument :: createBooleanOrBothTypeArgument ( 'is_enabled' ) , Argument :: createBooleanTypeArgument ( 'in_use' ) , Argument :: createAnyListTypeArgument ( 'code' ) , new Argument ( 'order' , new TypeCollection ( new EnumListType ( array ( 'id' , 'id-reverse' , 'code' , 'code-reverse' , 'title' , 'title-reverse' , 'enabled' , 'enabled-reverse' , 'start-date' , 'start-date-reverse' , 'expiration-date' , 'expiration-date-reverse' , 'days-left' , 'days-left-reverse' , 'usages-left' , 'usages-left-reverse' ) ) ) , 'code' ) ) ; }
Define all args used in your loop
16,138
protected function prepareSql ( $ sql ) { $ sql = str_replace ( ";'," , "-CODE-" , $ sql ) ; $ sql = trim ( $ sql ) ; preg_match_all ( '#DELIMITER (.+?)\n(.+?)DELIMITER ;#s' , $ sql , $ m ) ; foreach ( $ m [ 0 ] as $ k => $ v ) { if ( $ m [ 1 ] [ $ k ] == '|' ) { throw new \ RuntimeException ( 'You can not use "|" as delimiter: ' . $ v ) ; } $ stored = str_replace ( ';' , '|' , $ m [ 2 ] [ $ k ] ) ; $ stored = str_replace ( $ m [ 1 ] [ $ k ] , ";\n" , $ stored ) ; $ sql = str_replace ( $ v , $ stored , $ sql ) ; } $ query = array ( ) ; $ tab = explode ( ";\n" , $ sql ) ; $ size = \ count ( $ tab ) ; for ( $ i = 0 ; $ i < $ size ; $ i ++ ) { $ queryTemp = str_replace ( "-CODE-" , ";'," , $ tab [ $ i ] ) ; $ queryTemp = str_replace ( "|" , ";" , $ queryTemp ) ; $ query [ ] = $ queryTemp ; } return $ query ; }
Separate each sql instruction in an array
16,139
public function backupDb ( $ filename , $ tables = '*' ) { $ data = [ ] ; if ( $ tables == '*' ) { $ tables = array ( ) ; $ result = $ this -> connection -> prepare ( 'SHOW TABLES' ) ; $ result -> execute ( ) ; while ( $ row = $ result -> fetch ( PDO :: FETCH_NUM ) ) { $ tables [ ] = $ row [ 0 ] ; } } else { $ tables = \ is_array ( $ tables ) ? $ tables : explode ( ',' , $ tables ) ; } $ data [ ] = "\n" ; $ data [ ] = 'SET foreign_key_checks=0;' ; $ data [ ] = "\n\n" ; foreach ( $ tables as $ table ) { if ( ! preg_match ( "/^[\w_\-]+$/" , $ table ) ) { Tlog :: getInstance ( ) -> alert ( sprintf ( "Attempt to backup the db with this invalid table name: '%s'" , $ table ) ) ; continue ; } $ result = $ this -> execute ( 'SELECT * FROM `' . $ table . '`' ) ; $ fieldCount = $ result -> columnCount ( ) ; $ data [ ] = 'DROP TABLE `' . $ table . '`;' ; $ resultStruct = $ this -> execute ( 'SHOW CREATE TABLE `' . $ table . '`' ) ; $ rowStruct = $ resultStruct -> fetch ( PDO :: FETCH_NUM ) ; $ data [ ] = "\n\n" ; $ data [ ] = $ rowStruct [ 1 ] ; $ data [ ] = ";\n\n" ; for ( $ i = 0 ; $ i < $ fieldCount ; $ i ++ ) { while ( $ row = $ result -> fetch ( PDO :: FETCH_NUM ) ) { $ data [ ] = 'INSERT INTO `' . $ table . '` VALUES(' ; for ( $ j = 0 ; $ j < $ fieldCount ; $ j ++ ) { $ row [ $ j ] = addslashes ( $ row [ $ j ] ) ; $ row [ $ j ] = str_replace ( "\n" , "\\n" , $ row [ $ j ] ) ; if ( isset ( $ row [ $ j ] ) ) { $ data [ ] = '"' . $ row [ $ j ] . '"' ; } else { $ data [ ] = '""' ; } if ( $ j < ( $ fieldCount - 1 ) ) { $ data [ ] = ',' ; } } $ data [ ] = ");\n" ; } } $ data [ ] = "\n\n\n" ; } $ data [ ] = 'SET foreign_key_checks=1;' ; $ this -> writeFilename ( $ filename , $ data ) ; }
Backup the db OR just a table
16,140
private function writeFilename ( $ filename , $ data ) { $ f = fopen ( $ filename , "w+" ) ; fwrite ( $ f , implode ( '' , $ data ) ) ; fclose ( $ f ) ; }
Save an array of data to a filename
16,141
public function toggleVisibility ( CountryToggleVisibilityEvent $ event , $ eventName , EventDispatcherInterface $ dispatcher ) { $ country = $ event -> getCountry ( ) ; $ country -> setDispatcher ( $ dispatcher ) -> setVisible ( ! $ country -> getVisible ( ) ) -> save ( ) ; $ event -> setCountry ( $ country ) ; }
Toggle Country visibility
16,142
public function addItem ( CartEvent $ event , $ eventName , EventDispatcherInterface $ dispatcher ) { $ cart = $ event -> getCart ( ) ; $ newness = $ event -> getNewness ( ) ; $ append = $ event -> getAppend ( ) ; $ quantity = $ event -> getQuantity ( ) ; $ currency = $ cart -> getCurrency ( ) ; $ customer = $ cart -> getCustomer ( ) ; $ discount = 0 ; if ( $ cart -> isNew ( ) ) { $ persistEvent = new CartPersistEvent ( $ cart ) ; $ dispatcher -> dispatch ( TheliaEvents :: CART_PERSIST , $ persistEvent ) ; } if ( null !== $ customer && $ customer -> getDiscount ( ) > 0 ) { $ discount = $ customer -> getDiscount ( ) ; } $ productSaleElementsId = $ event -> getProductSaleElementsId ( ) ; $ productId = $ event -> getProduct ( ) ; $ findItemEvent = clone $ event ; $ dispatcher -> dispatch ( TheliaEvents :: CART_FINDITEM , $ findItemEvent ) ; $ cartItem = $ findItemEvent -> getCartItem ( ) ; if ( $ cartItem === null || $ newness ) { $ productSaleElements = ProductSaleElementsQuery :: create ( ) -> findPk ( $ productSaleElementsId ) ; if ( null !== $ productSaleElements ) { $ productPrices = $ productSaleElements -> getPricesByCurrency ( $ currency , $ discount ) ; $ cartItem = $ this -> doAddItem ( $ dispatcher , $ cart , $ productId , $ productSaleElements , $ quantity , $ productPrices ) ; } } elseif ( $ append && $ cartItem !== null ) { $ cartItem -> addQuantity ( $ quantity ) -> save ( ) ; } $ event -> setCartItem ( $ cartItem ) ; }
add an article in the current cart
16,143
protected function updateQuantity ( EventDispatcherInterface $ dispatcher , CartItem $ cartItem , $ quantity ) { $ cartItem -> setDisptacher ( $ dispatcher ) ; $ cartItem -> updateQuantity ( $ quantity ) -> save ( ) ; return $ cartItem ; }
increase the quantity for an existing cartItem
16,144
protected function doAddItem ( EventDispatcherInterface $ dispatcher , CartModel $ cart , $ productId , ProductSaleElements $ productSaleElements , $ quantity , ProductPriceTools $ productPrices ) { $ cartItem = new CartItem ( ) ; $ cartItem -> setDisptacher ( $ dispatcher ) ; $ cartItem -> setCart ( $ cart ) -> setProductId ( $ productId ) -> setProductSaleElementsId ( $ productSaleElements -> getId ( ) ) -> setQuantity ( $ quantity ) -> setPrice ( $ productPrices -> getPrice ( ) ) -> setPromoPrice ( $ productPrices -> getPromoPrice ( ) ) -> setPromo ( $ productSaleElements -> getPromo ( ) ) -> setPriceEndOfLife ( time ( ) + ConfigQuery :: read ( "cart.priceEOF" , 60 * 60 * 24 * 30 ) ) -> save ( ) ; return $ cartItem ; }
try to attach a new item to an existing cart
16,145
protected function findItem ( $ cartId , $ productId , $ productSaleElementsId ) { return CartItemQuery :: create ( ) -> filterByCartId ( $ cartId ) -> filterByProductId ( $ productId ) -> filterByProductSaleElementsId ( $ productSaleElementsId ) -> findOne ( ) ; }
find a specific record in CartItem table using the Cart id the product id and the product_sale_elements id
16,146
public function findCartItem ( CartEvent $ event ) { if ( null === $ event -> getCartItem ( ) && null !== $ foundItem = CartItemQuery :: create ( ) -> filterByCartId ( $ event -> getCart ( ) -> getId ( ) ) -> filterByProductId ( $ event -> getProduct ( ) ) -> filterByProductSaleElementsId ( $ event -> getProductSaleElementsId ( ) ) -> findOne ( ) ) { $ event -> setCartItem ( $ foundItem ) ; } }
Find a specific record in CartItem table using the current CartEvent
16,147
public function restoreCurrentCart ( CartRestoreEvent $ cartRestoreEvent , $ eventName , EventDispatcherInterface $ dispatcher ) { $ cookieName = ConfigQuery :: read ( "cart.cookie_name" , 'thelia_cart' ) ; $ persistentCookie = ConfigQuery :: read ( "cart.use_persistent_cookie" , 1 ) ; $ cart = null ; if ( $ this -> requestStack -> getCurrentRequest ( ) -> cookies -> has ( $ cookieName ) && $ persistentCookie ) { $ cart = $ this -> managePersistentCart ( $ cartRestoreEvent , $ cookieName , $ dispatcher ) ; } elseif ( ! $ persistentCookie ) { $ cart = $ this -> manageNonPersistentCookie ( $ cartRestoreEvent , $ dispatcher ) ; } if ( null === $ cart ) { $ cart = $ this -> dispatchNewCart ( $ dispatcher ) ; } $ cartRestoreEvent -> setCart ( $ cart ) ; }
Search if cart already exists in session . If not try to restore it from the cart cookie or duplicate an old one .
16,148
protected function manageNonPersistentCookie ( CartRestoreEvent $ cartRestoreEvent , EventDispatcherInterface $ dispatcher ) { $ cart = $ cartRestoreEvent -> getCart ( ) ; if ( null === $ cart ) { $ cart = $ this -> dispatchNewCart ( $ dispatcher ) ; } else { $ cart = $ this -> manageCartDuplicationAtCustomerLogin ( $ cart , $ dispatcher ) ; } return $ cart ; }
The cart token is not saved in a cookie if the cart is present in session we just change the customer id if needed or create duplicate the current cart if the customer is not the same as customer already present in the cart .
16,149
public function createEmptyCart ( CartCreateEvent $ cartCreateEvent ) { $ cart = new CartModel ( ) ; $ cart -> setCurrency ( $ this -> getSession ( ) -> getCurrency ( true ) ) ; if ( null !== $ customer = $ this -> getSession ( ) -> getCustomerUser ( ) ) { $ cart -> setCustomer ( CustomerQuery :: create ( ) -> findPk ( $ customer -> getId ( ) ) ) ; } $ this -> getSession ( ) -> setSessionCart ( $ cart ) ; if ( ConfigQuery :: read ( "cart.use_persistent_cookie" , 1 ) == 1 ) { $ this -> getSession ( ) -> set ( "cart_use_cookie" , "" ) ; } $ cartCreateEvent -> setCart ( $ cart ) ; }
Create a new empty cart object and assign it to the current customer if any .
16,150
protected function duplicateCart ( EventDispatcherInterface $ dispatcher , CartModel $ cart , CustomerModel $ customer = null ) { $ newCart = $ cart -> duplicate ( $ this -> generateCartCookieIdentifier ( ) , $ customer , $ this -> getSession ( ) -> getCurrency ( ) , $ dispatcher ) ; $ cartEvent = new CartDuplicationEvent ( $ newCart , $ cart ) ; $ dispatcher -> dispatch ( TheliaEvents :: CART_DUPLICATE , $ cartEvent ) ; return $ cartEvent -> getDuplicatedCart ( ) ; }
Duplicate an existing Cart . If a customer ID is provided the created cart will be attached to this customer .
16,151
protected function generateCartCookieIdentifier ( ) { $ id = null ; if ( ConfigQuery :: read ( "cart.use_persistent_cookie" , 1 ) == 1 ) { $ id = $ this -> tokenProvider -> getToken ( ) ; $ this -> getSession ( ) -> set ( 'cart_use_cookie' , $ id ) ; } return $ id ; }
Generate the cart cookie identifier or return null if the cart is only managed in the session object not in a client cookie .
16,152
protected function addCriteriaToPositionQuery ( $ query ) { $ contents = ContentFolderQuery :: create ( ) -> filterByFolderId ( $ this -> getDefaultFolderId ( ) ) -> filterByDefaultFolder ( true ) -> select ( 'content_id' ) -> find ( ) ; if ( $ contents != null ) { $ query -> filterById ( $ contents , Criteria :: IN ) ; } }
Calculate next position relative to our parent
16,153
protected function getDatabasePDO ( ) { $ configPath = THELIA_CONF_DIR . "database.yml" ; if ( ! file_exists ( $ configPath ) ) { throw new UpdateException ( "Thelia is not installed yet" ) ; } $ definePropel = new DatabaseConfigurationSource ( Yaml :: parse ( file_get_contents ( $ configPath ) ) , $ this -> getEnvParameters ( ) ) ; return $ definePropel -> getTheliaConnectionPDO ( ) ; }
retrieve the database connection
16,154
public function getDataBaseSize ( ) { $ stmt = $ this -> connection -> query ( "SELECT sum(data_length) / 1024 / 1024 'size' FROM information_schema.TABLES WHERE table_schema = DATABASE() GROUP BY table_schema" ) ; if ( $ stmt -> rowCount ( ) ) { return \ floatval ( $ stmt -> fetch ( PDO :: FETCH_OBJ ) -> size ) ; } throw new \ Exception ( 'Impossible to calculate the database size' ) ; }
Returns the database size in Mo
16,155
public function checkBackupIsPossible ( ) { $ size = 0 ; if ( preg_match ( '/^(\d+)(.)$/' , ini_get ( 'memory_limit' ) , $ matches ) ) { switch ( strtolower ( $ matches [ 2 ] ) ) { case 'k' : $ size = $ matches [ 1 ] / 1024 ; break ; case 'm' : $ size = $ matches [ 1 ] ; break ; case 'g' : $ size = $ matches [ 1 ] * 1024 ; break ; } } if ( $ this -> getDataBaseSize ( ) > ( $ size - 64 ) / 8 ) { return false ; } return true ; }
Checks whether it is possible to make a data base backup
16,156
protected function addPostInstructions ( $ version , $ instructions ) { if ( ! isset ( $ this -> postInstructions [ $ version ] ) ) { $ this -> postInstructions [ $ version ] = [ ] ; } $ this -> postInstructions [ $ version ] [ ] = $ instructions ; }
Add a new post update instruction
16,157
public function getPostInstructions ( $ format = 'plain' ) { $ content = [ ] ; if ( \ count ( $ this -> postInstructions ) == 0 ) { return null ; } ksort ( $ this -> postInstructions ) ; foreach ( $ this -> postInstructions as $ version => $ instructions ) { $ content [ ] = sprintf ( "## %s" , $ version ) ; foreach ( $ instructions as $ instruction ) { $ content [ ] = sprintf ( "%s" , $ instruction ) ; } } $ content = implode ( "\n\n" , $ content ) ; if ( $ format === 'html' ) { $ content = Markdown :: defaultTransform ( $ content ) ; } return $ content ; }
Return the content of all instructions
16,158
protected function checkPermission ( OutputInterface $ output ) { $ output -> writeln ( array ( "Checking some permissions" ) ) ; $ translator = $ this -> getContainer ( ) -> get ( 'thelia.translator' ) ; $ permissions = new CheckPermission ( false , $ translator ) ; $ isValid = $ permissions -> exec ( ) ; foreach ( $ permissions -> getValidationMessages ( ) as $ item => $ data ) { if ( $ data [ 'status' ] ) { $ output -> writeln ( array ( sprintf ( "<info>%s ...</info> %s" , $ data [ 'text' ] , "<info>Ok</info>" ) ) ) ; } else { $ output -> writeln ( array ( sprintf ( "<error>%s </error>%s" , $ data [ 'text' ] , sprintf ( "<error>%s</error>" , $ data [ "hint" ] ) ) ) ) ; } } if ( false === $ isValid ) { throw new \ RuntimeException ( 'Please put correct permissions and reload install process' ) ; } }
Test if needed directories have write permission
16,159
protected function createConfigFile ( $ connectionInfo ) { $ fs = new Filesystem ( ) ; $ sampleConfigFile = THELIA_CONF_DIR . "database.yml.sample" ; $ configFile = THELIA_CONF_DIR . "database.yml" ; $ fs -> copy ( $ sampleConfigFile , $ configFile , true ) ; $ configContent = file_get_contents ( $ configFile ) ; $ configContent = str_replace ( "%DRIVER%" , "mysql" , $ configContent ) ; $ configContent = str_replace ( "%USERNAME%" , $ connectionInfo [ "username" ] , $ configContent ) ; $ configContent = str_replace ( "%PASSWORD%" , $ connectionInfo [ "password" ] , $ configContent ) ; $ configContent = str_replace ( "%DSN%" , sprintf ( "mysql:host=%s;dbname=%s;port=%s" , $ connectionInfo [ "host" ] , $ connectionInfo [ "dbName" ] , $ connectionInfo [ 'port' ] ) , $ configContent ) ; file_put_contents ( $ configFile , $ configContent ) ; $ fs -> remove ( $ this -> getContainer ( ) -> getParameter ( "kernel.cache_dir" ) ) ; }
rename database config file and complete it
16,160
protected function tryConnection ( $ connectionInfo , OutputInterface $ output ) { if ( \ is_null ( $ connectionInfo [ "dbName" ] ) ) { return false ; } $ dsn = "mysql:host=%s;port=%s" ; try { $ connection = new \ PDO ( sprintf ( $ dsn , $ connectionInfo [ "host" ] , $ connectionInfo [ "port" ] ) , $ connectionInfo [ "username" ] , $ connectionInfo [ "password" ] ) ; $ connection -> query ( 'SET NAMES \'UTF8\'' ) ; } catch ( \ PDOException $ e ) { $ output -> writeln ( array ( "<error>Wrong connection information</error>" ) ) ; return false ; } return $ connection ; }
test database access
16,161
public function setVersion ( ) { $ wp_filesystem = self :: getWpFilesystem ( ) ; $ installedFile = wp_normalize_path ( realpath ( __DIR__ . '/../../../../' ) ) . '/composer/installed.json' ; if ( 'direct' === get_filesystem_method ( ) ) { $ file = $ wp_filesystem -> get_contents ( $ installedFile ) ; } else { $ installedUrl = str_replace ( ABSPATH , get_site_url ( ) . '/' , $ installedFile ) ; $ file = wp_remote_retrieve_body ( wp_remote_get ( $ installedUrl ) ) ; } $ installed = json_decode ( $ file , true ) ; $ version = null ; if ( $ installed ) { foreach ( $ installed as $ key => $ value ) { if ( $ value [ 'name' ] === $ this -> getDependency ( ) ) { $ version = $ value [ 'version_normalized' ] ; break ; } } } return $ version ; }
Sets the version of dependency .
16,162
public static function create ( string $ configType , ClassType $ classType , array $ options = [ ] ) { $ classType = ( string ) $ classType ; $ classMapVersion = empty ( $ options [ 'classMapVersion' ] ) ? Configure :: read ( 'ModuleConfig.classMapVersion' ) : ( string ) $ options [ 'classMapVersion' ] ; $ classMap = empty ( $ options [ 'classMap' ] [ $ classMapVersion ] ) ? Configure :: read ( 'ModuleConfig.classMap.' . $ classMapVersion ) : ( array ) $ options [ 'classMap' ] [ $ classMapVersion ] ; if ( empty ( $ classMap [ $ configType ] [ $ classType ] ) ) { throw new InvalidArgumentException ( "No [$classType] found for configuration type [$configType] in class map version [$classMapVersion]" ) ; } $ className = $ classMap [ $ configType ] [ $ classType ] ; $ params = $ options [ 'classArgs' ] ?? [ ] ; $ result = static :: getInstance ( $ className , $ params ) ; return $ result ; }
Create a new instance of a helper class
16,163
public static function getInstance ( string $ class , array $ params = [ ] ) { if ( ! class_exists ( $ class ) ) { throw new InvalidArgumentException ( "Class [$class] does not exist" ) ; } if ( empty ( $ params ) ) { return new $ class ; } $ reflection = new ReflectionClass ( $ class ) ; return $ reflection -> newInstanceArgs ( $ params ) ; }
Get an instance of a given class
16,164
public function includeLanguageJavaScriptFiles ( ) { $ filePath = $ this -> assetHandlerConnectorManager -> getFormzGeneratedFilePath ( 'locale-' . ContextService :: get ( ) -> getLanguageKey ( ) ) . '.js' ; $ this -> assetHandlerConnectorManager -> createFileInTemporaryDirectory ( $ filePath , function ( ) { return $ this -> getFormzLocalizationJavaScriptAssetHandler ( ) -> injectTranslationsForFormFieldsValidation ( ) -> getJavaScriptCode ( ) ; } ) ; $ this -> includeJsFile ( StringService :: get ( ) -> getResourceRelativePath ( $ filePath ) ) ; return $ this ; }
This function will handle the JavaScript language files .
16,165
public function generateAndIncludeFormzConfigurationJavaScript ( ) { $ formzConfigurationJavaScriptAssetHandler = $ this -> getFormzConfigurationJavaScriptAssetHandler ( ) ; $ fileName = $ formzConfigurationJavaScriptAssetHandler -> getJavaScriptFileName ( ) ; $ this -> assetHandlerConnectorManager -> createFileInTemporaryDirectory ( $ fileName , function ( ) use ( $ formzConfigurationJavaScriptAssetHandler ) { return $ formzConfigurationJavaScriptAssetHandler -> getJavaScriptCode ( ) ; } ) ; $ this -> includeJsFile ( StringService :: get ( ) -> getResourceRelativePath ( $ fileName ) ) ; return $ this ; }
Includes FormZ configuration JavaScript declaration . If the file exists it is directly included otherwise the JavaScript code is calculated then put in the cache file .
16,166
public function generateAndIncludeJavaScript ( ) { $ filePath = $ this -> assetHandlerConnectorManager -> getFormzGeneratedFilePath ( ) . '.js' ; $ this -> assetHandlerConnectorManager -> createFileInTemporaryDirectory ( $ filePath , function ( ) { return $ this -> getFormInitializationJavaScriptAssetHandler ( ) -> getFormInitializationJavaScriptCode ( ) . LF . $ this -> getFieldsValidationJavaScriptAssetHandler ( ) -> getJavaScriptCode ( ) . LF . $ this -> getFieldsActivationJavaScriptAssetHandler ( ) -> getFieldsActivationJavaScriptCode ( ) . LF . $ this -> getFieldsValidationActivationJavaScriptAssetHandler ( ) -> getFieldsValidationActivationJavaScriptCode ( ) ; } ) ; $ this -> includeJsFile ( StringService :: get ( ) -> getResourceRelativePath ( $ filePath ) ) ; return $ this ; }
Will include the generated JavaScript from multiple asset handlers sources .
16,167
public function generateAndIncludeInlineJavaScript ( ) { $ formName = $ this -> assetHandlerFactory -> getFormObject ( ) -> getName ( ) ; $ javaScriptCode = $ this -> getFormRequestDataJavaScriptAssetHandler ( ) -> getFormRequestDataJavaScriptCode ( ) ; if ( ExtensionService :: get ( ) -> isInDebugMode ( ) ) { $ javaScriptCode .= LF . $ this -> getDebugActivationCode ( ) ; } $ uri = $ this -> getAjaxUrl ( ) ; $ javaScriptCode .= LF ; $ javaScriptCode .= <<<JSFz.setAjaxUrl('$uri');JS ; $ this -> addInlineJs ( 'FormZ - Initialization ' . $ formName , $ javaScriptCode ) ; return $ this ; }
Here we generate the JavaScript code containing the submitted values and the existing errors which is dynamically created at each request .
16,168
public function includeJavaScriptValidationAndConditionFiles ( ) { $ javaScriptValidationFiles = $ this -> getJavaScriptFiles ( ) ; $ assetHandlerConnectorStates = $ this -> assetHandlerConnectorManager -> getAssetHandlerConnectorStates ( ) ; foreach ( $ javaScriptValidationFiles as $ file ) { if ( false === in_array ( $ file , $ assetHandlerConnectorStates -> getAlreadyIncludedValidationJavaScriptFiles ( ) ) ) { $ assetHandlerConnectorStates -> registerIncludedValidationJavaScriptFiles ( $ file ) ; $ this -> includeJsFile ( StringService :: get ( ) -> getResourceRelativePath ( $ file ) ) ; } } return $ this ; }
Will include all new JavaScript files given by checking that every given file was not already included .
16,169
protected function getJavaScriptFiles ( ) { $ formObject = $ this -> assetHandlerFactory -> getFormObject ( ) ; $ javaScriptFiles = $ this -> getFieldsValidationJavaScriptAssetHandler ( ) -> getJavaScriptValidationFiles ( ) ; $ conditionProcessor = $ this -> getConditionProcessor ( $ formObject ) ; $ javaScriptFiles = array_merge ( $ javaScriptFiles , $ conditionProcessor -> getJavaScriptFiles ( ) ) ; return $ javaScriptFiles ; }
Returns the list of JavaScript files which are used for the current form object .
16,170
protected function includeJsFile ( $ path ) { $ pageRenderer = $ this -> assetHandlerConnectorManager -> getPageRenderer ( ) ; if ( $ this -> environmentService -> isEnvironmentInFrontendMode ( ) ) { $ pageRenderer -> addJsFooterFile ( $ path ) ; } else { $ pageRenderer -> addJsFile ( $ path ) ; } }
We need an abstraction function because the footer inclusion for assets does not work in backend . It means we include every JavaScript asset in the header when the request is in a backend context .
16,171
public static function validatePath ( string $ path = null ) : void { if ( empty ( $ path ) ) { throw new InvalidArgumentException ( "Cannot validate empty path" ) ; } if ( ! file_exists ( $ path ) ) { throw new InvalidArgumentException ( "Path does not exist [$path]" ) ; } if ( ! is_readable ( $ path ) ) { throw new InvalidArgumentException ( "Path is not readable [$path]" ) ; } }
Check validity of the given path
16,172
public static function getControllers ( bool $ includePlugins = true ) : array { $ result = static :: getDirControllers ( APP . 'Controller' . DS ) ; if ( $ includePlugins === false ) { return $ result ; } $ plugins = Plugin :: loaded ( ) ; if ( ! is_array ( $ plugins ) ) { return $ result ; } foreach ( $ plugins as $ plugin ) { $ path = Plugin :: path ( $ plugin ) . 'src' . DS . 'Controller' . DS ; $ result = array_merge ( $ result , static :: getDirControllers ( $ path , $ plugin ) ) ; } return $ result ; }
Method that returns all controller names .
16,173
public static function getApiVersions ( string $ path = '' ) : array { $ apis = [ ] ; $ apiPath = ( ! empty ( $ path ) ) ? $ path : App :: path ( 'Controller/Api' ) [ 0 ] ; $ dir = new Folder ( ) ; $ tree = $ dir -> tree ( $ apiPath , false , 'dir' ) ; foreach ( $ tree as $ treePath ) { if ( $ treePath === $ apiPath ) { continue ; } $ path = str_replace ( $ apiPath , '' , $ treePath ) ; preg_match ( '/V(\d+)\/V(\d+)/' , $ path , $ matches ) ; if ( empty ( $ matches ) ) { continue ; } unset ( $ matches [ 0 ] ) ; $ number = implode ( '.' , $ matches ) ; $ apis [ ] = [ 'number' => $ number , 'prefix' => self :: getApiRoutePrefix ( $ matches ) , 'path' => self :: getApiRoutePath ( $ number ) , ] ; } if ( ! empty ( $ apis ) ) { $ apis = self :: sortApiVersions ( $ apis ) ; } return $ apis ; }
Get Api Directory Tree with prefixes
16,174
public static function getDirControllers ( string $ path , string $ plugin = null , bool $ fqcn = true ) : array { $ result = [ ] ; try { static :: validatePath ( $ path ) ; $ dir = new DirectoryIterator ( $ path ) ; } catch ( InvalidArgumentException $ e ) { return $ result ; } catch ( UnexpectedValueException $ e ) { return $ result ; } foreach ( $ dir as $ fileinfo ) { if ( ! $ fileinfo -> isFile ( ) ) { continue ; } $ className = $ fileinfo -> getBasename ( '.php' ) ; if ( 'AppController' === $ className ) { continue ; } if ( ! empty ( $ plugin ) ) { $ className = $ plugin . '.' . $ className ; } if ( $ fqcn ) { $ className = App :: className ( $ className , 'Controller' ) ; } if ( $ className ) { $ result [ ] = $ className ; } } return $ result ; }
Method that retrieves controller names found on the provided directory path .
16,175
public static function getModels ( string $ connectionManager = 'default' , bool $ excludePhinxlog = true ) : array { $ result = [ ] ; $ tables = ConnectionManager :: get ( $ connectionManager ) -> getSchemaCollection ( ) -> listTables ( ) ; if ( empty ( $ tables ) ) { return $ result ; } foreach ( $ tables as $ table ) { if ( $ excludePhinxlog && preg_match ( '/phinxlog/' , $ table ) ) { continue ; } $ result [ $ table ] = Inflector :: humanize ( $ table ) ; } return $ result ; }
Get All Models
16,176
public static function getModelColumns ( string $ model = '' , string $ connectionManager = 'default' ) : array { $ result = $ columns = [ ] ; if ( empty ( $ model ) ) { return $ result ; } $ model = Inflector :: tableize ( $ model ) ; try { $ connection = ConnectionManager :: get ( $ connectionManager ) ; $ schema = $ connection -> getSchemaCollection ( ) ; $ table = $ schema -> describe ( $ model ) ; $ columns = $ table -> columns ( ) ; } catch ( MissingDatasourceConfigException $ e ) { return $ result ; } catch ( Exception $ e ) { return $ result ; } if ( empty ( $ columns ) ) { return $ result ; } foreach ( $ columns as $ column ) { $ result [ $ column ] = $ column ; } return $ result ; }
Get Model Columns
16,177
public static function getColors ( array $ config = [ ] , bool $ pretty = true ) : array { $ result = [ ] ; $ config = empty ( $ config ) ? Configure :: read ( 'Colors' ) : $ config ; if ( ! $ pretty ) { return $ config ; } if ( ! $ config ) { return $ result ; } foreach ( $ config as $ k => $ v ) { $ result [ $ k ] = '<div><div style="width:20px;height:20px;margin:0;border:1px solid #eee;float:left;background:' . $ k . ';"></div>&nbsp;&nbsp;' . $ v . '</div><div style="clear:all"></div>' ; } return $ result ; }
Get colors for Select2 dropdown
16,178
protected static function sortApiVersions ( array $ versions = [ ] ) : array { usort ( $ versions , function ( $ first , $ second ) { $ firstVersion = ( float ) $ first [ 'number' ] ; $ secondVersion = ( float ) $ second [ 'number' ] ; if ( $ firstVersion == $ secondVersion ) { return 0 ; } return ( $ firstVersion > $ secondVersion ) ? 1 : - 1 ; } ) ; return $ versions ; }
Sorting API Versions ascendingly
16,179
public static function undefined_function ( $ function_name ) { if ( \ function_exists ( $ function_name ) ) { return new \ Twig_Function ( $ function_name , function ( ) use ( $ function_name ) { ob_start ( ) ; $ return = \ call_user_func_array ( $ function_name , \ func_get_args ( ) ) ; $ echo = ob_get_clean ( ) ; return empty ( $ echo ) ? $ return : $ echo ; } , array ( 'is_safe' => array ( 'all' ) ) ) ; } return false ; }
Handler for undefined functions in Twig to pass them through to PHP and buffer echoing versions .
16,180
public function getFormzConfiguration ( ) { $ cacheIdentifier = $ this -> getCacheIdentifier ( ) ; if ( false === array_key_exists ( $ cacheIdentifier , $ this -> instances ) ) { $ this -> instances [ $ cacheIdentifier ] = $ this -> getFormzConfigurationFromCache ( $ cacheIdentifier ) ; } return $ this -> instances [ $ cacheIdentifier ] ; }
Returns the global FormZ configuration .
16,181
protected function getFormzConfigurationFromCache ( $ cacheIdentifier ) { $ cacheInstance = CacheService :: get ( ) -> getCacheInstance ( ) ; if ( $ cacheInstance -> has ( $ cacheIdentifier ) ) { $ instance = $ cacheInstance -> get ( $ cacheIdentifier ) ; } else { $ instance = $ this -> buildFormzConfiguration ( ) ; if ( false === $ instance -> getValidationResult ( ) -> hasErrors ( ) ) { $ cacheInstance -> set ( $ cacheIdentifier , $ instance ) ; } } return $ instance ; }
Will fetch the configuration from cache and build it if not found . It won t be stored in cache if any error is found . This is done this way to avoid the integrator to be forced to flush caches when errors are found .
16,182
final protected static function getNewExceptionInstance ( $ message , $ code , array $ arguments = [ ] ) { $ exceptionClassName = get_called_class ( ) ; return new $ exceptionClassName ( vsprintf ( $ message , $ arguments ) , $ code ) ; }
Creates a new exception instance .
16,183
private function shouldLog ( $ event ) { $ level = isset ( $ this -> configuration [ $ event ] ) ? $ this -> configuration [ $ event ] : '' ; $ level = strtolower ( $ level ) ; if ( ! $ level ) { return '' ; } if ( ! isset ( self :: $ levels [ $ level ] ) ) { return '' ; } return $ level ; }
Should the event be logged?
16,184
public function addSlot ( $ name , Closure $ closure , array $ arguments ) { $ this -> closures [ $ name ] = $ closure ; $ this -> arguments [ $ name ] = $ arguments ; }
Adds a closure - used to render the slot with the given name - to the private storage in this class .
16,185
public function addTemplateVariables ( $ slotName , array $ arguments ) { $ templateVariableContainer = $ this -> renderingContext -> getTemplateVariableContainer ( ) ; $ savedArguments = [ ] ; ArrayUtility :: mergeRecursiveWithOverrule ( $ arguments , $ this -> getSlotArguments ( $ slotName ) ) ; foreach ( $ arguments as $ key => $ value ) { if ( $ templateVariableContainer -> exists ( $ key ) ) { $ savedArguments [ $ key ] = $ templateVariableContainer -> get ( $ key ) ; $ templateVariableContainer -> remove ( $ key ) ; } $ templateVariableContainer -> add ( $ key , $ value ) ; } $ this -> injectedVariables [ $ slotName ] = $ arguments ; $ this -> savedVariables [ $ slotName ] = $ savedArguments ; }
Will merge the given arguments with the ones registered by the given slot and inject them in the template variable container .
16,186
public function restoreTemplateVariables ( $ slotName ) { $ templateVariableContainer = $ this -> renderingContext -> getTemplateVariableContainer ( ) ; $ mergedArguments = ( isset ( $ this -> injectedVariables [ $ slotName ] ) ) ? $ this -> injectedVariables [ $ slotName ] : [ ] ; $ savedArguments = ( isset ( $ this -> savedVariables [ $ slotName ] ) ) ? $ this -> savedVariables [ $ slotName ] : [ ] ; foreach ( array_keys ( $ mergedArguments ) as $ key ) { $ templateVariableContainer -> remove ( $ key ) ; } foreach ( $ savedArguments as $ key => $ value ) { $ templateVariableContainer -> add ( $ key , $ value ) ; } }
Will remove all variables previously injected in the template variable container and restore the ones that were saved before being overridden .
16,187
public function stripLanguage ( $ path , $ language = null ) { $ strip = '/' . ( isset ( $ language ) ? $ language : $ this -> getLanguage ( ) ) ; if ( strlen ( $ strip ) > 1 && strpos ( $ path , $ strip ) === 0 ) { $ path = substr ( $ path , strlen ( $ strip ) ) ; } return $ path ; }
Strip the language from the URI
16,188
public function prependLanguage ( $ path , $ language = null ) { $ prepend = ( isset ( $ language ) ? $ language : $ this -> getLanguage ( ) ) ; if ( strlen ( $ prepend ) > 1 ) { return $ prepend . ( strpos ( $ path , '/' ) === 0 ? $ path : '/' . $ path ) ; } return $ path ; }
Prepend the language to the URI
16,189
public function replaceLanguage ( $ path , $ language , $ replacement = null ) { $ path = $ this -> stripLanguage ( $ path , $ language ) ; $ path = $ this -> prependLanguage ( $ path , $ replacement ) ; return $ path ; }
Replace the language in the URI
16,190
protected function getFromHeader ( ServerRequestInterface $ request ) { $ accept = $ request -> getHeaderLine ( 'Accept-Language' ) ; if ( empty ( $ accept ) || empty ( $ this -> languages ) ) { return ; } $ language = ( new Negotiator ( ) ) -> getBest ( $ accept , $ this -> languages ) ; if ( $ language ) { return $ language -> getValue ( ) ; } }
Retrieve the language using the Accept - Language header .
16,191
protected function getFromPath ( ServerRequestInterface $ request ) { $ uri = $ request -> getUri ( ) ; $ regex = '~^\/?' . $ this -> getRegEx ( ) . '\b~' ; $ path = rtrim ( $ uri -> getPath ( ) , '/\\' ) . '/' ; if ( preg_match ( $ regex , $ path , $ matches ) ) { if ( isset ( $ matches [ 'language' ] ) ) { return $ matches [ 'language' ] ; } else { throw new RuntimeException ( 'The regular expression pattern is missing a named subpattern "language".' ) ; } } }
Retrieve the language from the requested URI .
16,192
protected function getFromQuery ( ServerRequestInterface $ request ) { $ params = array_intersect_key ( $ request -> getQueryParams ( ) , array_flip ( $ this -> getQueryKeys ( ) ) ) ; $ regex = '~^\/?' . $ this -> getRegEx ( ) . '\b~' ; foreach ( $ params as $ key => $ value ) { if ( preg_match ( $ regex , $ value , $ matches ) ) { if ( isset ( $ matches [ 'language' ] ) ) { return $ matches [ 'language' ] ; } else { throw new RuntimeException ( 'The regular expression pattern is missing a named subpattern "language".' ) ; } } } }
Retrieve the language from the requested URI s query string .
16,193
public function setSupportedLanguages ( array $ languages ) { $ this -> languages = $ languages ; $ this -> fallbackLanguage = reset ( $ languages ) ; return $ this ; }
Set the supported languages
16,194
public function setFallbackLanguage ( $ language ) { if ( $ this -> isSupported ( $ language ) ) { $ this -> fallbackLanguage = $ language ; } else { throw new RuntimeException ( 'Variable must be one of the supported languages.' ) ; } return $ this ; }
Set the fallback language
16,195
public function getUserLanguage ( ServerRequestInterface $ request = null ) { if ( $ this -> saveInSession && isset ( $ _SESSION [ 'language' ] ) && $ this -> isSupported ( $ _SESSION [ 'language' ] ) ) { return $ _SESSION [ 'language' ] ; } if ( empty ( $ language ) && $ request instanceof ServerRequestInterface ) { return $ this -> getFromHeader ( $ request ) ; } return null ; }
Retrieve the user s preferred language
16,196
public function setCallbacks ( array $ callables ) { $ this -> callbacks = [ ] ; foreach ( $ callables as $ callable ) { if ( is_callable ( $ callable ) ) { $ this -> addCallback ( $ callable ) ; } } return $ this ; }
Set the callbacks used to assign the current language to .
16,197
public function setQueryKeys ( array $ keys ) { $ this -> queryKeys = [ ] ; foreach ( $ keys as $ key ) { if ( is_string ( $ key ) ) { $ this -> addQueryKey ( $ key ) ; } } return $ this ; }
Set the query string keys to look for when resolving the current language .
16,198
public function sanitizeLanguage ( $ language ) { if ( 0 === count ( $ this -> languages ) ) { throw new RuntimeException ( 'Polyglot features no supported languages.' ) ; } if ( ! $ this -> isSupported ( $ language ) ) { $ language = $ this -> getFallbackLanguage ( ) ; } return $ language ; }
Retrieve the fallback language if the variable isn t a supported language .
16,199
public function isLanguageRequiredInUri ( $ state = null ) { if ( isset ( $ state ) ) { $ this -> languageRequiredInUri = ( bool ) $ state ; } return $ this -> languageRequiredInUri ; }
Determine if languages are required in a URI .