idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
21,600
public function errorHandler ( $ errno , $ errstr , $ errfile , $ errline ) { if ( ( $ errorReporting = error_reporting ( ) ) === 0 ) { return true ; } $ logType = null ; foreach ( $ this -> errorLogGroups as $ candidateLogType => $ errorTypes ) { if ( in_array ( $ errno , $ errorTypes ) ) { $ logType = $ candidateLogType ; break ; } } if ( is_null ( $ logType ) ) { throw new \ Exception ( sprintf ( "No log type found for errno '%s'" , $ errno ) ) ; } $ exception = $ this -> createException ( $ errstr , $ errno , $ errfile , $ errline ) ; $ context = array ( 'file' => $ errfile , 'line' => $ errline ) ; if ( $ this -> reportBacktrace ) { $ context [ 'backtrace' ] = $ this -> getBacktraceReporter ( ) -> getBacktrace ( ) ; } if ( $ this -> exceptionInContext ) { $ context [ 'exception' ] = $ exception ; } $ this -> logger -> $ logType ( $ errstr , $ context ) ; if ( ( $ errno & $ errorReporting ) === $ errno && ( $ this -> showErrors || $ this -> getEnvReporter ( ) -> isLive ( ) ) ) { $ this -> getErrorReporter ( ) -> reportError ( $ exception ) ; } if ( in_array ( $ errno , $ this -> terminatingErrors ) ) { $ this -> terminate ( ) ; } return true ; }
Handles general errors user warn and notice
21,601
public function fatalHandler ( ) { $ error = $ this -> getLastError ( ) ; if ( $ this -> isRegistered ( ) && $ this -> isFatalError ( $ error ) ) { if ( defined ( 'FRAMEWORK_PATH' ) ) { chdir ( FRAMEWORK_PATH ) ; } if ( $ this -> isMemoryExhaustedError ( $ error ) ) { $ this -> changeMemoryLimit ( $ this -> reserveMemory ) ; } $ exception = $ this -> createException ( $ error [ 'message' ] , $ error [ 'type' ] , $ error [ 'file' ] , $ error [ 'line' ] ) ; $ context = array ( 'file' => $ error [ 'file' ] , 'line' => $ error [ 'line' ] ) ; if ( $ this -> reportBacktrace ) { $ context [ 'backtrace' ] = $ this -> getBacktraceReporter ( ) -> getBacktrace ( ) ; } if ( $ this -> exceptionInContext ) { $ context [ 'exception' ] = $ exception ; } $ this -> logger -> critical ( $ error [ 'message' ] , $ context ) ; if ( $ this -> showErrors || $ this -> getEnvReporter ( ) -> isLive ( ) ) { $ this -> getErrorReporter ( ) -> reportError ( $ exception ) ; } } }
Handles fatal errors If we are registered and there is a fatal error then log and try to gracefully handle error output In cases where memory is exhausted increase the memory_limit to allow for logging
21,602
protected function isMemoryExhaustedError ( $ error ) { return isset ( $ error [ 'message' ] ) && stripos ( $ error [ 'message' ] , 'memory' ) !== false && stripos ( $ error [ 'message' ] , 'exhausted' ) !== false ; }
Returns whether or not the passed in error is a memory exhausted error
21,603
protected function translateMemoryLimit ( $ memoryLimit ) { $ unit = strtolower ( substr ( $ memoryLimit , - 1 , 1 ) ) ; $ memoryLimit = ( int ) $ memoryLimit ; switch ( $ unit ) { case 'g' : $ memoryLimit *= 1024 ; case 'm' : $ memoryLimit *= 1024 ; case 'k' : $ memoryLimit *= 1024 ; } return $ memoryLimit ; }
Translate the memory limit string to a int in bytes .
21,604
public function getItemId ( ) { if ( $ this -> getProductCustomOption ( ) ) { return $ this -> getItem ( ) -> getData ( 'product_id' ) . '-' . $ this -> getProductCustomOption ( ) -> getProduct ( ) -> getId ( ) ; } return parent :: getItemId ( ) ; }
Retrieve parent - child pairing
21,605
public function startup ( ) { $ manager = ObjectManager :: getInstance ( ) ; $ initializer = $ manager -> get ( 'Shopgate\Base\Helper\Initializer\Config' ) ; $ this -> storeManager = $ initializer -> getStoreManager ( ) ; $ this -> logger = $ initializer -> getLogger ( ) ; $ this -> directory = $ initializer -> getDirectory ( ) ; $ this -> sgCoreConfig = $ initializer -> getSgCoreConfig ( ) ; $ this -> coreConfig = $ initializer -> getCoreConfig ( ) ; $ this -> cache = $ initializer -> getCache ( ) ; $ this -> configResource = $ initializer -> getConfigResource ( ) ; $ this -> configMapping = $ initializer -> getConfigMapping ( ) ; $ this -> configMethods = $ initializer -> getConfigMethods ( ) ; $ this -> registry = $ initializer -> getRegistry ( ) ; $ this -> configHelper = $ initializer -> getHelper ( ) ; $ this -> plugin_name = 'magento2' ; $ this -> configMapping += $ this -> configHelper -> loadUndefinedConfigPaths ( ) ; $ this -> loadArray ( $ this -> configMethods ) ; return true ; }
Assists with initializing
21,606
public function load ( array $ settings = null ) { $ classVars = array_keys ( get_class_vars ( get_class ( $ this ) ) ) ; foreach ( $ settings as $ name => $ value ) { if ( in_array ( $ name , $ this -> blacklistConfig , true ) ) { continue ; } if ( in_array ( $ name , $ classVars , true ) ) { $ method = 'set' . SimpleDataObjectConverter :: snakeCaseToUpperCamelCase ( $ name ) ; if ( method_exists ( $ this , $ method ) ) { $ this -> configMapping += $ this -> configHelper -> getNewSettingPath ( $ name ) ; $ this -> { $ method } ( $ this -> castToType ( $ value , $ name ) ) ; } else { $ this -> logger -> debug ( 'The evaluated method "' . $ method . '" is not available in class ' . __CLASS__ ) ; } } else { if ( array_key_exists ( $ name , $ this -> additionalSettings ) ) { $ this -> additionalSettings [ $ name ] = $ value ; } else { $ this -> logger -> debug ( 'The given setting property "' . $ name . '" is not available in class ' . __CLASS__ ) ; } } } }
Prepares values to be saved . Note that we use the + = operator intentionally
21,607
protected function castToType ( $ value , $ property ) { $ type = $ this -> getPropertyType ( $ property ) ; switch ( $ type ) { case 'array' : return is_array ( $ value ) ? $ value : explode ( "," , $ value ) ; case 'bool' : case 'boolean' : return ( boolean ) $ value ; case 'int' : case 'integer' : return ( int ) $ value ; case 'string' : return ( string ) $ value ; default : return $ value ; } }
Cast a given property value to the matching property type
21,608
protected function getPropertyType ( $ property ) { if ( ! array_key_exists ( $ property , get_class_vars ( 'ShopgateConfig' ) ) ) { return 'string' ; } $ r = new \ ReflectionProperty ( 'ShopgateConfig' , $ property ) ; $ doc = $ r -> getDocComment ( ) ; preg_match_all ( '#@var ([a-zA-Z-_]*(\[\])?)(.*?)\n#s' , $ doc , $ annotations ) ; $ value = 'string' ; if ( count ( $ annotations ) > 0 && isset ( $ annotations [ 1 ] [ 0 ] ) ) { $ value = $ annotations [ 1 ] [ 0 ] ; } return $ value ; }
Fetches the property type described in phpdoc annotation
21,609
public function loadConfig ( ) { if ( ! $ this -> registry -> isRedirect ( ) ) { $ storeId = $ this -> sgCoreConfig -> getStoreId ( $ this -> getShopNumber ( ) ) ; $ this -> storeManager -> setCurrentStore ( $ storeId ) ; } $ this -> loadArray ( $ this -> toArray ( ) ) ; $ this -> setExportTmpAndLogSettings ( ) ; }
Load general information and values . Use shop number to determine store only when it is not a frontend call
21,610
public function getShopNumber ( ) { if ( $ this -> shop_number === null ) { $ this -> shop_number = $ this -> configHelper -> getShopNumber ( ) ; } return $ this -> shop_number ; }
Retrieve the shop number of the current request
21,611
protected function setExportTmpAndLogSettings ( ) { $ this -> setExportFolderPath ( $ this -> directory -> getPath ( DirectoryList :: TMP ) . DS . 'shopgate' . DS . $ this -> getShopNumber ( ) ) ; $ this -> createFolderIfNotExist ( $ this -> getExportFolderPath ( ) ) ; $ this -> setLogFolderPath ( $ this -> directory -> getPath ( DirectoryList :: LOG ) . DS . 'shopgate' . DS . $ this -> getShopNumber ( ) ) ; $ this -> createFolderIfNotExist ( $ this -> getLogFolderPath ( ) ) ; $ this -> setCacheFolderPath ( $ this -> directory -> getPath ( DirectoryList :: TMP ) . DS . 'shopgate' . DS . $ this -> getShopNumber ( ) ) ; $ this -> createFolderIfNotExist ( $ this -> getCacheFolderPath ( ) ) ; }
Setup export log and tmp folder and check if need to create them
21,612
private function methodLoader ( array $ classProperties ) { $ result = [ ] ; foreach ( $ classProperties as $ propertyName => $ nullVal ) { $ result [ $ propertyName ] = $ this -> getPropertyValue ( $ propertyName ) ; } return $ result ; }
Uses the keys of the array as camelCase methods calls them and retrieves the data
21,613
private function getPropertyValue ( $ property ) { $ value = null ; $ getter = 'get' . SimpleDataObjectConverter :: snakeCaseToUpperCamelCase ( $ property ) ; if ( method_exists ( $ this , $ getter ) ) { $ value = $ this -> { $ getter } ( ) ; } elseif ( $ this -> returnAdditionalSetting ( $ property ) ) { $ value = $ this -> returnAdditionalSetting ( $ property ) ; } return $ value ; }
Calls the properties getter method to retrieve the value
21,614
private function getCoreConfigMap ( array $ map ) { $ result = [ ] ; foreach ( $ map as $ key => $ path ) { $ value = $ this -> coreConfig -> getConfigByPath ( $ path ) -> getData ( 'value' ) ; if ( $ value !== null ) { $ result [ $ key ] = $ this -> castToType ( $ value , $ key ) ; } } return $ result ; }
Traverses the config and retrieves data from magento core_config_data table
21,615
public function save ( array $ fieldList , $ validate = true ) { $ this -> logger -> debug ( '# setSettings save start' ) ; if ( $ validate ) { $ this -> validate ( $ fieldList ) ; } foreach ( $ fieldList as $ property ) { if ( in_array ( $ property , $ this -> blacklistConfig , true ) ) { continue ; } if ( isset ( $ this -> configMapping [ $ property ] ) ) { $ config = $ this -> sgCoreConfig -> getSaveScope ( $ this -> configMapping [ $ property ] , $ this -> getShopNumber ( ) ) ; $ this -> saveField ( $ this -> configMapping [ $ property ] , $ property , $ config -> getScope ( ) , $ config -> getScopeId ( ) ) ; } } $ this -> clearCache ( ) ; $ this -> logger -> debug ( '# setSettings save end' ) ; }
Writes the given fields to magento
21,616
protected function saveField ( $ path , $ property , $ scope , $ scopeId , $ value = null ) { if ( $ value === null ) { if ( isset ( $ this -> configMapping [ $ property ] ) ) { $ value = $ this -> getPropertyValue ( $ property ) ; } else { $ this -> logger -> error ( 'The specified property "' . $ property . '" is not in the DI list' ) ; } } if ( $ value !== null ) { $ this -> logger -> debug ( ' Saving config field \'' . $ property . '\' with value \'' . $ value . '\' to scope {\'' . $ scope . '\':\'' . $ scopeId . '\'}' ) ; $ value = $ this -> prepareForDatabase ( $ property , $ value ) ; $ this -> configResource -> saveConfig ( $ path , $ value , $ scope , $ scopeId ) ; } }
Saves this property to magento core_config_data
21,617
protected function prepareForDatabase ( $ property , $ value ) { $ type = $ this -> getPropertyType ( $ property ) ; if ( $ type == 'array' && is_array ( $ value ) ) { return implode ( "," , $ value ) ; } if ( is_bool ( $ value ) ) { $ value = ( int ) $ value ; } return $ value ; }
Converts values into a core_config_data compatible format
21,618
protected function clearCache ( ) { $ result = $ this -> cache -> clean ( [ \ Magento \ Framework \ App \ Config :: CACHE_TAG ] ) ; $ this -> logger -> debug ( ' Config cache cleared with result: ' . ( $ result ? '[OK]' : '[ERROR]' ) ) ; }
Clears config cache after saving altered configuration
21,619
public function getByOrderNumber ( $ number ) { $ connection = $ this -> getConnection ( ) ; $ select = $ connection -> select ( ) -> from ( $ this -> getMainTable ( ) ) -> where ( 'shopgate_order_number = :number' ) ; $ bind = [ ':number' => ( string ) $ number ] ; return $ connection -> fetchRow ( $ select , $ bind ) ; }
Gets order data using shopgate order number
21,620
public function getByOrderId ( $ id ) { $ connection = $ this -> getConnection ( ) ; $ select = $ connection -> select ( ) -> from ( $ this -> getMainTable ( ) ) -> where ( 'order_id = :internal_order_id' ) ; $ bind = [ ':internal_order_id' => ( string ) $ id ] ; return $ connection -> fetchRow ( $ select , $ bind ) ; }
Gets order data using magento increment id
21,621
public function parseEntity ( Card $ entity ) { $ output = [ $ this -> encodeString ( $ entity -> getTicketNumber ( ) , 23 ) , $ this -> encodeInteger ( $ entity -> getUserNumber ( ) , 9 ) , $ this -> encodeInteger ( $ entity -> getArticleNumber ( ) , 3 ) , $ this -> encodeDate ( $ entity -> getValidFrom ( ) ) , $ this -> encodeDate ( $ entity -> getExpires ( ) ) , $ this -> encodeBoolean ( $ entity -> getBlocked ( ) ) , $ this -> encodeDate ( $ entity -> getBlockedDate ( ) ) , $ this -> encodeInteger ( $ entity -> getProductionState ( ) , 1 ) , $ this -> encodeInteger ( $ entity -> getReasonProduction ( ) , 1 ) , $ this -> encodeInteger ( $ entity -> getProductionCounter ( ) , 4 ) , $ this -> encodeBoolean ( $ entity -> getNeutral ( ) ) , $ this -> encodeBoolean ( $ entity -> getRetainTicketEntry ( ) ) , $ this -> encodeBoolean ( $ entity -> getEntryBarrierClosed ( ) ) , $ this -> encodeBoolean ( $ entity -> getExitBarrierClosed ( ) ) , $ this -> encodeBoolean ( $ entity -> getRetainTicketExit ( ) ) , $ this -> encodeBoolean ( $ entity -> getDisplayText ( ) ) , $ this -> encodeString ( $ entity -> getDisplayText1 ( ) , 16 ) , $ this -> encodeString ( $ entity -> getDisplayText2 ( ) , 16 ) , $ this -> encodeInteger ( $ entity -> getPersonnalNo ( ) , 4 ) , $ this -> encodeInteger ( $ entity -> getResidualValue ( ) , 12 ) , $ this -> encodeString ( $ entity -> getSerialNumberKeyCardSwatch ( ) , 20 ) , $ this -> encodeString ( $ entity -> getCurrencyResidualValue ( ) , 3 ) , $ this -> encodeInteger ( $ entity -> getTicketType ( ) , 1 ) , $ this -> encodeString ( $ entity -> getTicketSubType ( ) , 5 ) , $ this -> encodeString ( $ entity -> getSerialNo ( ) , 30 ) , $ this -> encodeDate ( $ entity -> getSuspendPeriodFrom ( ) ) , $ this -> encodeDate ( $ entity -> getSuspendPeriodUntil ( ) ) , $ this -> encodeBoolean ( $ entity -> getUseValidCarParks ( ) ) , $ this -> encodeInteger ( $ entity -> getProductionFacilityNumber ( ) , 7 ) , ] ; return implode ( ";" , $ output ) ; }
Parse a card entity .
21,622
public function load ( $ schema_shortname , $ component_class = 'PatternBuilder\Property\Component\Component' ) { $ cid = $ this -> getCid ( $ schema_shortname ) ; if ( $ this -> use_cache && $ cache = $ this -> getCache ( $ cid ) ) { return clone $ cache ; } else { if ( empty ( $ this -> schemaFiles ) ) { $ this -> schemaFiles = $ this -> getSchemaFiles ( ) ; } if ( ! isset ( $ this -> schemaFiles [ $ schema_shortname ] ) ) { $ message = sprintf ( 'JSON shortname of %s was not found.' , $ schema_shortname ) ; $ this -> logger -> error ( $ message ) ; return false ; } if ( $ json = $ this -> loadSchema ( $ this -> schemaFiles [ $ schema_shortname ] ) ) { $ schema_path = $ this -> schemaFiles [ $ schema_shortname ] ; $ component = new $ component_class ( $ json , $ this -> configuration , $ schema_shortname , $ schema_path ) ; $ this -> setCache ( $ cid , $ component ) ; return $ component ; } else { return false ; } } }
Loads a object either from file or from cache .
21,623
protected function getCache ( $ cid ) { if ( isset ( $ this -> localCache [ $ cid ] ) ) { $ cache = $ this -> localCache [ $ cid ] ; } else { $ cache = $ this -> loadCache ( $ cid ) ; if ( $ cache !== false ) { $ this -> localCache [ $ cid ] = $ cache ; } } return $ cache ; }
Returns the object from local or extended cache .
21,624
protected function setCache ( $ cid , $ component_obj ) { $ this -> localCache [ $ cid ] = $ component_obj ; $ this -> saveCache ( $ cid , $ component_obj ) ; }
Sets the local and extended cache .
21,625
protected function loadSchema ( $ schema_path ) { $ json = false ; if ( file_exists ( $ schema_path ) ) { $ contents = file_get_contents ( $ schema_path ) ; $ json = json_decode ( $ contents ) ; if ( $ json == false ) { $ message = sprintf ( 'Error decoding %s.' , $ schema_path ) ; $ this -> logger -> error ( $ message ) ; } } else { $ message = sprintf ( 'Could not load file %s.' , $ schema_path ) ; $ this -> logger -> error ( $ message ) ; } return $ json ; }
Load the JSON file from disk .
21,626
public function clearCacheByName ( $ short_name ) { $ cid = $ this -> getCid ( $ short_name ) ; unset ( $ this -> schemaFiles [ $ short_name ] ) ; $ this -> clearCache ( $ cid ) ; }
Clear the cached objects for the give schema short name .
21,627
public function warmCache ( $ render_class = 'PatternBuilder\Property\Component\Component' ) { $ this -> schemaFiles = $ this -> getSchemaFiles ( ) ; foreach ( $ this -> schemaFiles as $ key => $ schema_file ) { if ( $ json = $ this -> loadSchema ( $ schema_file ) ) { $ cid = $ this -> getCid ( $ key ) ; $ component = new $ render_class ( $ json ) ; $ this -> setCache ( $ cid , $ component ) ; } } }
Pre - load and create all objects to be cached .
21,628
public static function factory ( $ rawFeed ) { $ repository = new static ; $ skills = new SkillsRepository ( ) ; $ exploded = explode ( "\n" , $ rawFeed ) ; $ spliced = array_splice ( $ exploded , 0 , $ skills -> count ( ) ) ; for ( $ id = 0 ; $ id < count ( $ spliced ) ; $ id ++ ) { list ( $ rank , $ level , $ experience ) = explode ( ',' , $ spliced [ $ id ] ) ; $ skill = $ skills -> find ( $ id ) ; $ repository -> push ( new Stat ( $ skill , $ level , $ rank , $ experience ) ) ; } return $ repository ; }
Creates an \ Burthorpe \ Runescape \ RS3 \ Stats \ Repository instance from a raw feed directly from Jagex
21,629
public function find ( $ id ) { return $ this -> filter ( function ( Contract $ stat ) use ( $ id ) { return $ stat -> getSkill ( ) -> getId ( ) === $ id ; } ) -> first ( ) ; }
Find a stat by the given skill ID
21,630
public function findByName ( $ name ) { return $ this -> filter ( function ( Contract $ stat ) use ( $ name ) { return $ stat -> getSkill ( ) -> getName ( ) === $ name ; } ) -> first ( ) ; }
Find a stat by the given skill name
21,631
public function stats ( $ rsn ) { $ request = new Request ( 'GET' , sprintf ( $ this -> endpoints [ 'hiscores' ] , $ rsn ) ) ; try { $ response = $ this -> guzzle -> send ( $ request ) ; } catch ( RequestException $ e ) { throw new UnknownPlayerException ( $ rsn ) ; } return StatsRepository :: factory ( $ response -> getBody ( ) ) ; }
Get a players statistics from the hiscores API feed
21,632
public function calculateCombatLevel ( $ attack , $ strength , $ magic , $ ranged , $ defence , $ constitution , $ prayer , $ summoning , $ float = false ) { $ highest = max ( ( $ attack + $ strength ) , ( 2 * $ magic ) , ( 2 * $ ranged ) ) ; $ cmb = floor ( 0.25 * ( ( 1.3 * $ highest ) + $ defence + $ constitution + floor ( 0.5 * $ prayer ) + floor ( 0.5 * $ summoning ) ) ) ; return $ float ? $ cmb : ( int ) $ cmb ; }
Calculates a players combat level
21,633
public static function isGifFile ( $ filename ) { try { $ image = new ImageFile ( $ filename ) ; if ( strtolower ( $ image -> getMime ( ) ) !== @ image_type_to_mime_type ( IMAGETYPE_GIF ) ) { return false ; } return true ; } catch ( \ RuntimeException $ ex ) { return false ; } }
Check if the given file is gif file
21,634
public function sendRequest ( $ request , $ options = [ ] ) { $ client = $ this -> client ; $ response = $ client -> send ( $ request , $ options ) ; return $ response ; }
Sends a request to the LIFX HTTP API .
21,635
public function getLights ( $ selector = 'all' ) { $ request = new Request ( 'GET' , 'lights/' . $ selector ) ; $ response = $ this -> sendRequest ( $ request ) ; return $ response -> getBody ( ) ; }
Gets lights belonging to the authenticated account .
21,636
public function toggleLights ( $ selector = 'all' ) { $ request = new Request ( 'POST' , 'lights/' . $ selector . '/toggle' ) ; $ response = $ this -> sendRequest ( $ request ) ; return $ response -> getBody ( ) ; }
Toggle off lights if they are on or turn them on if they are off . Physically powered off lights are ignored .
21,637
public function setLights ( $ selector = 'all' , $ state = 'on' , $ duration = 1.0 ) { $ request = new Request ( 'PUT' , 'lights/' . $ selector . '/state' ) ; $ response = $ this -> sendRequest ( $ request , [ 'query' => [ 'power' => $ state , 'duration' => $ duration ] ] ) ; return $ response -> getBody ( ) ; }
Turn lights on or off .
21,638
public function setColor ( $ selector = 'all' , $ color = 'white' , $ duration = 1.0 , $ power_on = true ) { $ request = new Request ( 'PUT' , 'lights/' . $ selector . '/state' ) ; $ response = $ this -> sendRequest ( $ request , [ 'query' => [ 'color' => $ color , 'duration' => $ duration , 'power_on' => $ power_on , ] ] ) ; return $ response -> getBody ( ) ; }
Set lights to any color .
21,639
public function breatheLights ( $ selector = 'all' , $ color = 'purple' , $ from_color = null , $ period = 1.0 , $ cycles = 1.0 , $ persist = 'false' , $ power_on = 'true' , $ peak = 0.5 ) { $ request = new Request ( 'POST' , 'lights/' . $ selector . '/effects/breathe' ) ; $ response = $ this -> sendRequest ( $ request , [ 'query' => [ 'color' => $ color , 'from_color' => $ from_color , 'period' => $ period , 'cycles' => $ cycles , 'persist' => $ persist , 'power_on' => $ power_on , 'peak' => $ peak , ] ] ) ; return $ response -> getBody ( ) ; }
Performs a breathe effect by slowly fading between the given colors . If from_color is omitted then the current color is used in its place .
21,640
public function pulseLights ( $ selector = 'all' , $ color = 'purple' , $ from_color = null , $ period = 1.0 , $ cycles = 1.0 , $ persist = 'false' , $ power_on = 'true' , $ duty_cycle = 0.5 ) { $ request = new Request ( 'POST' , 'lights/' . $ selector . '/effects/pulse' ) ; $ response = $ this -> sendRequest ( $ request , [ 'query' => [ 'selector' => $ selector , 'color' => $ color , 'from_color' => $ from_color , 'period' => $ period , 'cycles' => $ cycles , 'persist' => $ persist , 'power_on' => $ power_on , 'duty_cycle' => $ duty_cycle , ] ] ) ; return $ response -> getBody ( ) ; }
Performs a pulse effect by quickly flashing between the given colors . If from_color is omitted then the current color is used in its place .
21,641
protected function resolveCategoryIds ( $ categoryId , $ topLevel = false , $ storeViewCode = StoreViewCodes :: ADMIN ) { if ( ( integer ) $ categoryId === 1 ) { return ; } $ category = $ this -> getCategory ( $ categoryId , $ storeViewCode ) ; if ( ! in_array ( $ categoryId , $ this -> productCategoryIds ) ) { if ( $ topLevel ) { $ this -> productCategoryIds [ ] = $ categoryId ; } elseif ( ( integer ) $ category [ MemberNames :: IS_ANCHOR ] === 1 ) { $ this -> productCategoryIds [ ] = $ categoryId ; } else { $ this -> getSubject ( ) -> getSystemLogger ( ) -> debug ( sprintf ( 'Don\'t create URL rewrite for category "%s" because of missing anchor flag' , $ category [ MemberNames :: PATH ] ) ) ; } } $ rootCategory = $ this -> getRootCategory ( ) ; if ( $ rootCategory [ MemberNames :: ENTITY_ID ] !== ( $ parentId = $ category [ MemberNames :: PARENT_ID ] ) ) { $ this -> resolveCategoryIds ( $ parentId , false ) ; } }
Resolve s the parent categories of the category with the passed ID and relate s it with the product with the passed ID if the category is top level OR has the anchor flag set .
21,642
protected function prepareUrlRewriteProductCategoryAttributes ( ) { return $ this -> initializeEntity ( array ( MemberNames :: PRODUCT_ID => $ this -> entityId , MemberNames :: CATEGORY_ID => $ this -> categoryId , MemberNames :: URL_REWRITE_ID => $ this -> urlRewriteId ) ) ; }
Prepare s the URL rewrite product = > category relation attributes .
21,643
protected function prepareTargetPath ( array $ category ) { if ( $ this -> isRootCategory ( $ category ) ) { $ targetPath = sprintf ( 'catalog/product/view/id/%d' , $ this -> entityId ) ; } else { $ targetPath = sprintf ( 'catalog/product/view/id/%d/category/%d' , $ this -> entityId , $ category [ MemberNames :: ENTITY_ID ] ) ; } return $ targetPath ; }
Prepare s the target path for a URL rewrite .
21,644
protected function prepareMetadata ( array $ category ) { $ metadata = array ( ) ; if ( $ this -> isRootCategory ( $ category ) ) { return ; } $ metadata [ UrlRewriteObserver :: CATEGORY_ID ] = ( integer ) $ category [ MemberNames :: ENTITY_ID ] ; return $ metadata ; }
Prepare s the URL rewrite s metadata with the passed category values .
21,645
protected function isRootCategory ( array $ category ) { $ rootCategory = $ this -> getRootCategory ( ) ; return $ rootCategory [ MemberNames :: ENTITY_ID ] === $ category [ MemberNames :: ENTITY_ID ] ; }
Return s TRUE if the passed category IS the root category else FALSE .
21,646
private function fwrite ( $ stream , $ bytes ) { if ( ! \ strlen ( $ bytes ) ) { return 0 ; } $ result = @ fwrite ( $ stream , $ bytes ) ; if ( 0 !== $ result ) { return $ result ; } $ read = [ ] ; $ write = [ $ stream ] ; $ except = [ ] ; @ stream_select ( $ read , $ write , $ except , 0 ) ; if ( ! $ write ) { return 0 ; } $ result = @ fwrite ( $ stream , $ bytes ) ; if ( 0 !== $ result ) { return $ result ; } return false ; }
Replace fwrite behavior as API is broken in PHP .
21,647
public function & GetFilters ( ) { $ filters = [ ] ; foreach ( $ this -> filters as $ direction => $ handler ) $ filters [ $ direction ] = $ handler [ 1 ] ; return $ filters ; }
Get URL address params filters to filter URL params in and out . By route filters you can change incoming request params into application and out from application . For example to translate the values or anything else .
21,648
public function & SetFilters ( array $ filters = [ ] ) { foreach ( $ filters as $ direction => $ handler ) $ this -> SetFilter ( $ handler , $ direction ) ; return $ this ; }
Set URL address params filters to filter URL params in and out . By route filters you can change incoming request params into application and out from application . For example to translate the values or anything else .
21,649
public function GetFilter ( $ direction = \ MvcCore \ IRoute :: CONFIG_FILTER_IN ) { return isset ( $ this -> filters [ $ direction ] ) ? $ this -> filters [ $ direction ] : NULL ; }
Get URL address params filter to filter URL params in and out . By route filter you can change incoming request params into application and out from application . For example to translate the values or anything else .
21,650
public function & SetFilter ( $ handler , $ direction = \ MvcCore \ IRoute :: CONFIG_FILTER_IN ) { $ closureCalling = ( ( is_string ( $ handler ) && strpos ( $ handler , '::' ) !== FALSE ) || ( is_array ( $ handler ) && strpos ( $ handler [ 1 ] , '::' ) !== FALSE ) ) ? FALSE : TRUE ; $ this -> filters [ $ direction ] = [ $ closureCalling , $ handler ] ; return $ this ; }
Set URL address params filter to filter URL params in and out . By route filter you can change incoming request params into application and out from application . For example to translate the values or anything else .
21,651
public function setDirection ( $ direction ) { if ( ! in_array ( $ direction , self :: $ supportedFlipDirection ) ) { throw new \ InvalidArgumentException ( sprintf ( '"%s" Is Not Valid Flip Direction' , ( string ) $ direction ) ) ; } $ this -> flipDirection = $ direction ; return $ this ; }
Set flip direction
21,652
public function buildParam ( $ facetParam , $ field ) { $ param = '' ; if ( $ field !== null ) { $ param .= 'f.' . $ field . '.' ; } $ param .= $ facetParam ; return $ param ; }
Helper function that builds a facet param based on whether it is global or per - field . If the field is null the param is global .
21,653
protected function removeExistingUrlRewrite ( array $ urlRewrite ) { $ requestPath = $ urlRewrite [ MemberNames :: REQUEST_PATH ] ; if ( isset ( $ this -> existingUrlRewrites [ $ requestPath ] ) ) { unset ( $ this -> existingUrlRewrites [ $ requestPath ] ) ; } }
Remove s the passed URL rewrite from the existing one s .
21,654
protected function getCategoryIdFromMetadata ( array $ attr ) { $ metadata = $ this -> getMetadata ( $ attr ) ; return ( integer ) $ metadata [ UrlRewriteObserver :: CATEGORY_ID ] ; }
Extracts the category ID of the passed URL rewrite entity if available and return s it .
21,655
protected function initializeUrlRewriteProductCategory ( $ attr ) { if ( $ urlRewriteProductCategory = $ this -> loadUrlRewriteProductCategory ( $ attr [ MemberNames :: URL_REWRITE_ID ] ) ) { return $ this -> mergeEntity ( $ urlRewriteProductCategory , $ attr ) ; } return $ attr ; }
Initialize the URL rewrite product = > category relation with the passed attributes and returns an instance .
21,656
protected function getMetadata ( $ urlRewrite ) { $ metadata = array ( ) ; if ( isset ( $ urlRewrite [ MemberNames :: METADATA ] ) ) { $ metadata = json_decode ( $ urlRewrite [ MemberNames :: METADATA ] , true ) ; } if ( isset ( $ metadata [ UrlRewriteObserver :: CATEGORY_ID ] ) ) { return $ metadata ; } $ rootCategory = $ this -> getRootCategory ( ) ; $ metadata [ UrlRewriteObserver :: CATEGORY_ID ] = ( integer ) $ rootCategory [ MemberNames :: ENTITY_ID ] ; return $ metadata ; }
Return s the unserialized metadata of the passed URL rewrite . If the metadata doesn t contain a category ID the category ID of the root category will be added .
21,657
public function getNextVersion ( $ from ) { $ found = false ; foreach ( array_keys ( $ this -> versions ) as $ timestamp ) { if ( $ from === null ) { return $ timestamp ; } if ( $ timestamp == $ from ) { $ found = true ; continue ; } if ( $ found ) { return $ timestamp ; } } return ; }
Return the version after the given version .
21,658
public function getPreviousVersion ( $ from ) { $ lastTimestamp = 0 ; foreach ( array_keys ( $ this -> versions ) as $ timestamp ) { if ( $ timestamp == $ from ) { return $ lastTimestamp ; } $ lastTimestamp = $ timestamp ; } return 0 ; }
Return the version before the given version .
21,659
protected function getAllLanguagesFromTable ( ) : void { foreach ( $ this -> translations as $ entry ) { if ( ! in_array ( $ entry -> language , $ this -> languages ) ) { array_push ( $ this -> languages , $ entry -> language ) ; } } $ this -> compareLanguages ( ) ; }
Collects all languages from the Database
21,660
protected function generateGroupFiles ( ) : void { foreach ( $ this -> languages as $ language ) { foreach ( $ this -> translation_groups as $ group ) { $ file = $ this -> language_folder . $ language . "\\" . $ group -> name . ".php" ; if ( ! file_exists ( $ file ) ) { $ new_file = fopen ( $ file , "a" ) ; fclose ( $ new_file ) ; $ this -> info ( "Created translation group - $group->name - for language $language." ) ; } } } }
Generates translation group files for each language if not exists
21,661
private function addTranslationsToArray ( $ array = [ ] ) : array { foreach ( $ array as $ language => $ groups ) { foreach ( $ groups as $ groupname => $ entries ) { $ group_model = TranslationGroup :: where ( 'name' , $ groupname ) -> first ( ) ; $ first_level_translations = Translation :: where ( [ [ 'parent' , '=' , NULL ] , [ 'translation_group' , '=' , $ group_model -> id ] , [ 'language' , '=' , $ language ] ] ) -> get ( ) ; foreach ( $ first_level_translations as $ translation ) { $ array [ $ language ] [ $ groupname ] [ $ translation -> key ] = $ this -> getValue ( $ language , $ translation , $ group_model ) ; } } } return $ array ; }
Collects all relevant translations from database and writes them to the correct array - field .
21,662
private function addTranslationGroupsToArray ( $ array = [ ] ) : array { foreach ( array_keys ( $ array ) as $ language ) { foreach ( $ this -> translation_groups as $ group ) { $ array [ $ language ] [ $ group -> name ] = [ ] ; } } return $ array ; }
Adds translation groups to the given array .
21,663
public function setFormat ( $ name ) { if ( ! $ this -> hasFactory ( $ name ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Invalid Canvas Factory "%s"' , $ name ) ) ; } $ this -> activeFactoryName = $ name ; $ this -> activeCanvas = $ this -> getFactory ( $ name ) -> getCanvas ( ) ; return $ this ; }
Set canvas factory
21,664
public function setFactory ( array $ factories ) { foreach ( $ factories as $ name => $ factory ) { $ this -> addFactory ( $ name , $ factory ) ; } return $ this ; }
Add array of factories
21,665
public function removeFactory ( $ name ) { if ( $ this -> hasFactory ( $ name ) ) { unset ( $ this -> factories [ $ name ] ) ; return true ; } return false ; }
Remove factory by its name
21,666
public function show ( ) { try { header ( sprintf ( 'Content-Type: %s' , $ this -> getMimeType ( ) , true ) ) ; $ this -> save ( null ) ; } catch ( \ Exception $ ex ) { header ( sprintf ( 'Content-Type: text/html' ) , true ) ; throw $ ex ; } }
Output raw canvas directly to the browser
21,667
public function buildAttribute ( $ property ) { $ attribute = '' ; if ( isset ( $ this -> $ property ) ) { $ attribute .= ' ' . $ property . '="' ; if ( is_bool ( $ this -> $ property ) ) { $ attribute .= ( $ this -> $ property ) ? 'true' : 'false' ; } else { $ attribute .= SolrRequest :: escapeXml ( $ this -> $ property ) ; } $ attribute .= '"' ; } return $ attribute ; }
Builds an attribute from a class property if it is set .
21,668
public function setPropertyDefaultValue ( $ property ) { if ( isset ( $ property -> default ) ) { return true ; } elseif ( isset ( $ property -> enum ) && count ( $ property -> enum ) == 1 ) { $ property -> default = reset ( $ property -> enum ) ; return true ; } return false ; }
Set the default value for the property schema .
21,669
protected function prepareFactory ( ) { if ( empty ( $ this -> componentFactory ) && isset ( $ this -> configuration ) ) { $ this -> componentFactory = new ComponentFactory ( $ this -> configuration ) ; } }
Prepare an instance of a component factory for usage .
21,670
public function getValidator ( ) { if ( ! isset ( $ this -> validator ) && isset ( $ this -> configuration ) ) { $ resolver = $ this -> configuration -> getResolver ( ) ; if ( $ resolver && ( $ retriever = $ resolver -> getUriRetriever ( ) ) ) { $ check_mode = JsonSchema \ Validator :: CHECK_MODE_NORMAL ; $ this -> validator = new JsonSchema \ Validator ( $ check_mode , $ retriever ) ; } } return $ this -> validator ; }
Return an instance of the component configuration .
21,671
public function isEmpty ( $ property_name = null ) { $ value = $ this -> get ( $ property_name ) ; return Inspector :: isEmpty ( $ value ) ; }
Determine if a given property contains data .
21,672
public function endIf ( bool $ condition , ? callable $ callback = null ) : void { if ( ( bool ) $ condition ) { $ this -> end ( $ callback ) ; } }
End the timer if condition is matched .
21,673
public function endUnless ( bool $ condition , ? callable $ callback = null ) : void { $ this -> endIf ( ! $ condition , $ callback ) ; }
End the timer unless condition is matched .
21,674
protected function & iniReadFilterEnvironmentSections ( array & $ rawIniData , $ environment ) { $ iniData = [ ] ; foreach ( $ rawIniData as $ keyOrSectionName => $ valueOrSectionValues ) { if ( is_array ( $ valueOrSectionValues ) ) { if ( strpos ( $ keyOrSectionName , '>' ) !== FALSE ) { list ( $ envNamesStrLocal , $ keyOrSectionName ) = explode ( '>' , str_replace ( ' ' , '' , $ keyOrSectionName ) ) ; if ( ! in_array ( $ environment , explode ( ',' , $ envNamesStrLocal ) ) ) continue ; } $ sectionValues = [ ] ; foreach ( $ valueOrSectionValues as $ key => $ value ) $ sectionValues [ $ keyOrSectionName . '.' . $ key ] = $ value ; $ iniData = array_merge ( $ iniData , $ sectionValues ) ; } else { $ iniData [ $ keyOrSectionName ] = $ valueOrSectionValues ; } } return $ iniData ; }
Align all raw INI data to single level array filtered for only current environment data items .
21,675
protected function iniReadExpandLevelsAndReType ( array & $ iniData ) { $ oldIniScannerMode = $ this -> _iniScannerMode === 1 ; foreach ( $ iniData as $ rawKey => $ rawValue ) { $ current = & $ this -> data ; $ rawKeys = [ ] ; $ lastRawKey = $ rawKey ; $ lastDotPos = strrpos ( $ rawKey , '.' ) ; if ( $ lastDotPos !== FALSE ) { $ rawKeys = explode ( '.' , substr ( $ rawKey , 0 , $ lastDotPos ) ) ; $ lastRawKey = substr ( $ rawKey , $ lastDotPos + 1 ) ; } $ levelKey = '' ; $ prevLevelKey = '' ; foreach ( $ rawKeys as $ key ) { $ prevLevelKey = $ levelKey ; $ levelKey .= ( $ levelKey ? '.' : '' ) . $ key ; if ( ! isset ( $ current [ $ key ] ) ) { $ current [ $ key ] = [ ] ; $ this -> objectTypes [ $ levelKey ] = [ 1 , & $ current [ $ key ] ] ; if ( is_numeric ( $ key ) && isset ( $ this -> objectTypes [ $ prevLevelKey ] ) ) { $ this -> objectTypes [ $ prevLevelKey ] [ 0 ] = 0 ; } } $ current = & $ current [ $ key ] ; } if ( $ oldIniScannerMode ) { $ typedValue = $ this -> getTypedValue ( $ rawValue ) ; } else { $ typedValue = $ rawValue ; } if ( isset ( $ current [ $ lastRawKey ] ) ) { $ current [ $ lastRawKey ] [ ] = $ typedValue ; $ this -> objectTypes [ $ levelKey ? $ levelKey : $ lastRawKey ] [ 0 ] = 0 ; } else { if ( ! is_array ( $ current ) ) { $ current = [ $ current ] ; $ this -> objectTypes [ $ levelKey ] = [ 0 , & $ current ] ; } $ current [ $ lastRawKey ] = $ typedValue ; if ( is_numeric ( $ lastRawKey ) ) $ this -> objectTypes [ $ levelKey ] [ 0 ] = 0 ; } } }
Process single level array with dotted keys into tree structure and complete object type switches about tree records to complete journal about final \ stdClass es or array s types .
21,676
protected function getTypedValue ( $ rawValue ) { if ( gettype ( $ rawValue ) == "array" ) { foreach ( $ rawValue as $ key => $ value ) { $ rawValue [ $ key ] = $ this -> getTypedValue ( $ value ) ; } return $ rawValue ; } else if ( mb_strlen ( $ rawValue ) > 0 ) { if ( is_numeric ( $ rawValue ) ) { return $ this -> getTypedValueFloatOrInt ( $ rawValue ) ; } else { return $ this -> getTypedSpecialValueOrString ( $ rawValue ) ; } } else { return $ this -> getTypedSpecialValueOrString ( $ rawValue ) ; } }
Retype raw INI value into array with retyped it s own values or retype raw INI value into float int or string .
21,677
protected function getTypedValueFloatOrInt ( $ rawValue ) { if ( strpos ( $ rawValue , '.' ) !== FALSE || strpos ( $ rawValue , 'e' ) !== FALSE || strpos ( $ rawValue , 'E' ) !== FALSE ) { return floatval ( $ rawValue ) ; } else { $ intVal = intval ( $ rawValue ) ; return ( string ) $ intVal === $ rawValue ? $ intVal : $ rawValue ; } }
Retype raw INI value into float or int .
21,678
protected function getTypedSpecialValueOrString ( $ rawValue ) { $ lowerRawValue = strtolower ( $ rawValue ) ; if ( isset ( static :: $ specialValues [ $ lowerRawValue ] ) ) { return static :: $ specialValues [ $ lowerRawValue ] ; } else { return trim ( $ rawValue ) ; } }
Retype raw INI value into bool NULL or string .
21,679
public static function GetStarted ( ) { if ( static :: $ started === NULL ) { $ req = self :: $ req ? : self :: $ req = & \ MvcCore \ Application :: GetInstance ( ) -> GetRequest ( ) ; if ( ! $ req -> IsCli ( ) ) { $ alreadyStarted = session_status ( ) === PHP_SESSION_ACTIVE && session_id ( ) !== '' ; if ( $ alreadyStarted ) { static :: $ sessionStartTime = time ( ) ; static :: $ sessionMaxTime = static :: $ sessionStartTime ; static :: setUpMeta ( ) ; static :: setUpData ( ) ; } static :: $ started = $ alreadyStarted ; } } return static :: $ started ; }
Get static boolean about if session has been already started or not .
21,680
public function scale ( $ ratio ) { $ this -> getDimension ( ) -> setWidth ( round ( $ ratio * $ this -> getDimension ( ) -> getWidth ( ) ) ) -> setHeight ( round ( $ ratio * $ this -> getDimension ( ) -> getHeight ( ) ) ) ; return $ this ; }
Scale the box by the given ratio
21,681
public function Init ( ) { if ( $ this -> dispatchState > 0 ) return ; self :: $ allControllers [ spl_object_hash ( $ this ) ] = & $ this ; if ( $ this -> parentController === NULL && ! $ this -> request -> IsCli ( ) ) { if ( $ this -> autoStartSession ) $ this -> application -> SessionStart ( ) ; $ responseContentType = $ this -> ajax ? 'text/javascript' : 'text/html' ; $ this -> response -> SetHeader ( 'Content-Type' , $ responseContentType ) ; } if ( $ this -> autoInitProperties ) $ this -> processAutoInitProperties ( ) ; foreach ( $ this -> childControllers as $ controller ) { $ controller -> Init ( ) ; if ( $ controller -> dispatchState == 5 ) break ; } if ( $ this -> dispatchState === 0 ) $ this -> dispatchState = 1 ; }
Application controllers initialization . This is best time to initialize language locale session etc . There is also called auto initialization processing - instance creation on each controller class member implementing \ MvcCore \ IController and marked in doc comments as
21,682
protected function processAutoInitProperties ( ) { $ type = new \ ReflectionClass ( $ this ) ; $ props = $ type -> getProperties ( \ ReflectionProperty :: IS_PUBLIC | \ ReflectionProperty :: IS_PROTECTED | \ ReflectionProperty :: IS_PRIVATE ) ; $ toolsClass = $ this -> application -> GetToolClass ( ) ; foreach ( $ props as $ prop ) { $ docComment = $ prop -> getDocComment ( ) ; if ( mb_strpos ( $ docComment , '@autoinit' ) === FALSE ) continue ; $ propName = $ prop -> getName ( ) ; $ methodName = 'create' . ucfirst ( $ propName ) ; $ hasMethod = $ type -> hasMethod ( $ methodName ) ; if ( ! $ hasMethod ) { $ methodName = '_' . $ methodName ; $ hasMethod = $ type -> hasMethod ( $ methodName ) ; } if ( $ hasMethod ) { $ method = $ type -> getMethod ( $ methodName ) ; if ( ! $ method -> isPublic ( ) ) $ method -> setAccessible ( TRUE ) ; $ instance = $ method -> invoke ( $ this ) ; $ implementsController = $ instance instanceof \ MvcCore \ IController ; } else { $ pos = mb_strpos ( $ docComment , '@var ' ) ; if ( $ pos === FALSE ) continue ; $ docComment = str_replace ( [ "\r" , "\n" , "\t" , "*/" ] , " " , mb_substr ( $ docComment , $ pos + 5 ) ) ; $ pos = mb_strpos ( $ docComment , ' ' ) ; if ( $ pos === FALSE ) continue ; $ className = trim ( mb_substr ( $ docComment , 0 , $ pos ) ) ; if ( ! @ class_exists ( $ className ) ) { $ className = $ prop -> getDeclaringClass ( ) -> getNamespaceName ( ) . '\\' . $ className ; if ( ! @ class_exists ( $ className ) ) continue ; } $ implementsController = $ toolsClass :: CheckClassInterface ( $ className , 'MvcCore\IController' , FALSE , FALSE ) ; if ( $ implementsController ) { $ instance = $ className :: CreateInstance ( ) ; } else { $ instance = new $ className ( ) ; } } if ( $ implementsController ) $ this -> AddChildController ( $ instance , $ propName ) ; if ( ! $ prop -> isPublic ( ) ) $ prop -> setAccessible ( TRUE ) ; $ prop -> setValue ( $ this , $ instance ) ; } }
Initialize all members implementing \ MvcCore \ IController marked in doc comments as
21,683
public function AssetAction ( ) { $ ext = '' ; $ path = $ this -> GetParam ( 'path' , 'a-zA-Z0-9_\-\/\.' ) ; $ path = '/' . ltrim ( str_replace ( '..' , '' , $ path ) , '/' ) ; if ( strpos ( $ path , static :: $ staticPath ) !== 0 && strpos ( $ path , static :: $ tmpPath ) !== 0 ) { throw new \ ErrorException ( "[" . get_class ( $ this ) . "] File path: '$path' is not allowed." , 500 ) ; } $ path = $ this -> request -> GetAppRoot ( ) . $ path ; if ( ! file_exists ( $ path ) ) { throw new \ ErrorException ( "[" . get_class ( $ this ) . "] File not found: '$path'." , 404 ) ; } $ lastDotPos = strrpos ( $ path , '.' ) ; if ( $ lastDotPos !== FALSE ) { $ ext = substr ( $ path , $ lastDotPos + 1 ) ; } if ( isset ( self :: $ _assetsMimeTypes [ $ ext ] ) ) { header ( 'Content-Type: ' . self :: $ _assetsMimeTypes [ $ ext ] ) ; } header_remove ( 'X-Powered-By' ) ; header ( 'Vary: Accept-Encoding' ) ; $ assetMTime = @ filemtime ( $ path ) ; if ( $ assetMTime ) header ( 'Last-Modified: ' . gmdate ( 'D, d M Y H:i:s T' , $ assetMTime ) ) ; readfile ( $ path ) ; exit ; }
Return small assets content with proper headers in single file application mode and immediately exit .
21,684
protected function bootstrapApplication ( $ config ) { if ( ! isset ( $ config [ 'providers' ] ) ) { $ config [ 'providers' ] = [ ] ; } $ config [ 'providers' ] = array_merge ( $ config [ 'providers' ] , $ this -> service_providers ) ; Application :: bootstrap ( $ config ) ; }
Bootstrap WPEmerge .
21,685
public function bootstrap ( $ config = [ ] ) { if ( $ this -> isBootstrapped ( ) ) { throw new ConfigurationException ( static :: class . ' already bootstrapped.' ) ; } $ this -> bootstrapped = true ; $ this -> bootstrapApplication ( $ config ) ; }
Bootstrap the theme .
21,686
public static function EnvironmentDetectByIps ( ) { if ( static :: $ environment === NULL ) { $ request = & \ MvcCore \ Application :: GetInstance ( ) -> GetRequest ( ) ; $ serverAddress = $ request -> GetServerIp ( ) ; $ remoteAddress = $ request -> GetClientIp ( ) ; if ( $ serverAddress == $ remoteAddress ) { static :: $ environment = static :: ENVIRONMENT_DEVELOPMENT ; } else { static :: $ environment = static :: ENVIRONMENT_PRODUCTION ; } } return static :: $ environment ; }
First environment value setup - by server and client IP address .
21,687
public static function EnvironmentDetectBySystemConfig ( array $ environmentsSectionData = [ ] ) { $ environment = NULL ; $ app = self :: $ app ? : self :: $ app = & \ MvcCore \ Application :: GetInstance ( ) ; $ request = $ app -> GetRequest ( ) ; $ clientIp = NULL ; $ serverHostName = NULL ; $ serverGlobals = NULL ; foreach ( ( array ) $ environmentsSectionData as $ environmentName => $ environmentSection ) { $ sectionData = static :: envDetectParseSysConfigEnvSectionData ( $ environmentSection ) ; $ detected = static :: envDetectBySystemConfigEnvSection ( $ sectionData , $ request , $ clientIp , $ serverHostName , $ serverGlobals ) ; if ( $ detected ) { $ environment = $ environmentName ; break ; } } if ( $ environment && ! static :: $ environment ) { static :: SetEnvironment ( $ environment ) ; } else if ( ! static :: $ environment ) { static :: SetEnvironment ( 'production' ) ; } return static :: $ environment ; }
Second environment value setup - by system config data environment record .
21,688
protected static function envDetectParseSysConfigEnvSectionData ( $ environmentSection ) { $ data = ( object ) [ 'clientIps' => ( object ) [ 'check' => FALSE , 'values' => [ ] , 'regExeps' => [ ] ] , 'serverHostNames' => ( object ) [ 'check' => FALSE , 'values' => [ ] , 'regExeps' => [ ] ] , 'serverVariables' => ( object ) [ 'check' => FALSE , 'existence' => [ ] , 'values' => [ ] , 'regExeps' => [ ] ] ] ; if ( is_string ( $ environmentSection ) && strlen ( $ environmentSection ) > 0 ) { static :: envDetectParseSysConfigClientIps ( $ data , $ environmentSection ) ; } else if ( is_array ( $ environmentSection ) || $ environmentSection instanceof \ stdClass ) { foreach ( ( array ) $ environmentSection as $ key => $ value ) { if ( is_numeric ( $ key ) || $ key == 'clients' ) { static :: envDetectParseSysConfigClientIps ( $ data , $ value ) ; } else if ( $ key == 'servers' ) { static :: envDetectParseSysConfigServerNames ( $ data , $ value ) ; } else if ( $ key == 'variables' ) { static :: envDetectParseSysConfigVariables ( $ data , $ value ) ; } } } return $ data ; }
Parse system config environment section data from various declarations into specific detection structure .
21,689
protected static function envDetectParseSysConfigClientIps ( & $ data , $ rawClientIps ) { $ data -> clientIps -> check = TRUE ; if ( is_string ( $ rawClientIps ) ) { if ( substr ( $ rawClientIps , 0 , 1 ) == '/' ) { $ data -> clientIps -> regExeps [ ] = $ rawClientIps ; } else { $ data -> clientIps -> values = array_merge ( $ data -> clientIps -> values , explode ( ',' , str_replace ( ' ' , '' , $ rawClientIps ) ) ) ; } } else if ( is_array ( $ rawClientIps ) || $ rawClientIps instanceof \ stdClass ) { foreach ( ( array ) $ rawClientIps as $ rawClientIpsItem ) { if ( substr ( $ rawClientIpsItem , 0 , 1 ) == '/' ) { $ data -> clientIps -> regExeps [ ] = $ rawClientIpsItem ; } else { $ data -> clientIps -> values = array_merge ( $ data -> clientIps -> values , explode ( ',' , str_replace ( ' ' , '' , $ rawClientIpsItem ) ) ) ; } } } }
Parse system config environment section data from various declarations about client IP addresses into specific detection structure .
21,690
protected static function envDetectParseSysConfigServerNames ( & $ data , $ rawHostNames ) { $ data -> serverHostNames -> check = TRUE ; if ( is_string ( $ rawHostNames ) ) { if ( substr ( $ rawHostNames , 0 , 1 ) == '/' ) { $ data -> serverHostNames -> regExeps [ ] = $ rawHostNames ; } else { $ data -> serverHostNames -> values = array_merge ( $ data -> serverHostNames -> values , explode ( ',' , str_replace ( ' ' , '' , $ rawHostNames ) ) ) ; } } else if ( is_array ( $ rawHostNames ) || $ rawHostNames instanceof \ stdClass ) { foreach ( ( array ) $ rawHostNames as $ rawHostNamesItem ) { if ( substr ( $ rawHostNamesItem , 0 , 1 ) == '/' ) { $ data -> serverHostNames -> regExeps [ ] = $ rawHostNamesItem ; } else { $ data -> serverHostNames -> values = array_merge ( $ data -> serverHostNames -> values , explode ( ',' , str_replace ( ' ' , '' , $ rawHostNamesItem ) ) ) ; } } } }
Parse system config environment section data from various declarations about server host names into specific detection structure .
21,691
protected static function envDetectParseSysConfigVariables ( & $ data , $ rawServerVariable ) { $ data -> serverVariables -> check = TRUE ; if ( is_string ( $ rawServerVariable ) ) { $ data -> serverVariables -> existence [ ] = $ rawServerVariable ; } else if ( is_array ( $ rawServerVariable ) || $ rawServerVariable instanceof \ stdClass ) { foreach ( ( array ) $ rawServerVariable as $ key => $ value ) { if ( is_numeric ( $ key ) ) { $ data -> serverVariables -> existence [ ] = $ value ; } else if ( substr ( $ value , 0 , 1 ) == '/' ) { $ data -> serverVariables -> regExeps [ $ key ] = $ value ; } else { $ data -> serverVariables -> values [ $ key ] = $ value ; } } } }
Parse system config environment section data from various declarations about server environment variables into specific detection structure .
21,692
public static function EncodeJson ( & $ data ) { $ flags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | ( defined ( 'JSON_UNESCAPED_SLASHES' ) ? JSON_UNESCAPED_SLASHES : 0 ) | ( defined ( 'JSON_UNESCAPED_UNICODE' ) ? JSON_UNESCAPED_UNICODE : 0 ) | ( defined ( 'JSON_PRESERVE_ZERO_FRACTION' ) ? JSON_PRESERVE_ZERO_FRACTION : 0 ) ; $ json = json_encode ( $ data , $ flags ) ; if ( $ errorCode = json_last_error ( ) ) { $ selfClass = version_compare ( PHP_VERSION , '5.5' , '>' ) ? self :: class : __CLASS__ ; throw new \ RuntimeException ( "[" . $ selfClass . "] " . json_last_error_msg ( ) , $ errorCode ) ; } if ( PHP_VERSION_ID < 70100 ) { $ json = strtr ( $ json , [ "\xe2\x80\xa8" => '\u2028' , "\xe2\x80\xa9" => '\u2029' , ] ) ; } return $ json ; }
Safely encode json string from php value .
21,693
public static function GetSystemTmpDir ( ) { if ( self :: $ tmpDir === NULL ) { $ tmpDir = sys_get_temp_dir ( ) ; if ( strtolower ( substr ( PHP_OS , 0 , 3 ) ) == 'win' ) { $ sysRoot = getenv ( 'SystemRoot' ) ; if ( ! $ tmpDir || $ tmpDir === $ sysRoot ) { $ tmpDir = ! empty ( $ _SERVER [ 'TEMP' ] ) ? $ _SERVER [ 'TEMP' ] : ( ! empty ( $ _SERVER [ 'TMP' ] ) ? $ _SERVER [ 'TMP' ] : ( ! empty ( $ _SERVER [ 'WINDIR' ] ) ? $ _SERVER [ 'WINDIR' ] . '/Temp' : $ sysRoot . '/Temp' ) ) ; } $ tmpDir = str_replace ( '\\' , '/' , $ tmpDir ) ; } else if ( ! $ tmpDir ) { $ tmpDir = ! empty ( $ _SERVER [ 'TMPDIR' ] ) ? $ _SERVER [ 'TMPDIR' ] : ( ! empty ( $ _SERVER [ 'TMP' ] ) ? $ _SERVER [ 'TMP' ] : ( ! empty ( ini_get ( 'sys_temp_dir' ) ) ? ini_get ( 'sys_temp_dir' ) : '/tmp' ) ) ; } self :: $ tmpDir = $ tmpDir ; } return self :: $ tmpDir ; }
Returns the OS - specific directory for temporary files .
21,694
protected function urlAbsPartAndSplit ( \ MvcCore \ IRequest & $ request , $ resultUrl , & $ domainParams , $ splitUrl ) { $ domainParamsFlag = $ this -> flags [ 1 ] ; $ basePathInReverse = FALSE ; if ( $ domainParamsFlag >= static :: FLAG_HOST_BASEPATH ) { $ basePathInReverse = TRUE ; $ domainParamsFlag -= static :: FLAG_HOST_BASEPATH ; } if ( $ this -> flags [ 0 ] ) { $ this -> urlReplaceDomainReverseParams ( $ request , $ resultUrl , $ domainParams , $ domainParamsFlag ) ; if ( $ basePathInReverse ) { return $ this -> urlAbsPartAndSplitByReverseBasePath ( $ request , $ resultUrl , $ domainParams , $ splitUrl ) ; } else { return $ this -> urlAbsPartAndSplitByRequestedBasePath ( $ request , $ resultUrl , $ splitUrl ) ; } } else { return $ this -> urlAbsPartAndSplitByGlobalSwitchOrBasePath ( $ request , $ resultUrl , $ domainParams , $ domainParamsFlag , $ splitUrl ) ; } }
After final URL is completed split result URL into two parts . First part as scheme domain part and base path and second part as application request path and query string .
21,695
protected function urlAbsPartAndSplitByReverseBasePath ( \ MvcCore \ IRequest & $ request , $ resultUrl , & $ domainParams , $ splitUrl ) { $ doubleSlashPos = mb_strpos ( $ resultUrl , '//' ) ; $ doubleSlashPos = $ doubleSlashPos === FALSE ? 0 : $ doubleSlashPos + 2 ; $ router = & $ this -> router ; $ basePathPlaceHolderPos = mb_strpos ( $ resultUrl , static :: PLACEHOLDER_BASEPATH , $ doubleSlashPos ) ; if ( $ basePathPlaceHolderPos === FALSE ) { return $ this -> urlAbsPartAndSplitByRequestedBasePath ( $ request , $ resultUrl , $ splitUrl ) ; } $ pathPart = mb_substr ( $ resultUrl , $ basePathPlaceHolderPos + mb_strlen ( static :: PLACEHOLDER_BASEPATH ) ) ; $ pathPart = str_replace ( '//' , '/' , $ pathPart ) ; $ basePart = mb_substr ( $ resultUrl , 0 , $ basePathPlaceHolderPos ) ; $ basePathParamName = $ router :: URL_PARAM_BASEPATH ; $ basePart .= isset ( $ domainParams [ $ basePathParamName ] ) ? $ domainParams [ $ basePathParamName ] : $ request -> GetBasePath ( ) ; if ( $ this -> flags [ 0 ] === static :: FLAG_SCHEME_ANY ) $ basePart = $ request -> GetScheme ( ) . $ basePart ; if ( $ splitUrl ) return [ $ basePart , $ pathPart ] ; return [ $ basePart . $ pathPart ] ; }
After final URL is completed split result URL into two parts if there is contained domain part and base path in reverse what is base material to complete result URL . If there is found base path percentage replacement in result url split url after that percentage replacement and replace that part with domain param value or request base path value .
21,696
protected function urlAbsPartAndSplitByRequestedBasePath ( \ MvcCore \ IRequest & $ request , $ resultUrl , $ splitUrl ) { $ doubleSlashPos = mb_strpos ( $ resultUrl , '//' ) ; $ doubleSlashPos = $ doubleSlashPos === FALSE ? 0 : $ doubleSlashPos + 2 ; if ( ! $ splitUrl ) { $ resultSchemePart = mb_substr ( $ resultUrl , 0 , $ doubleSlashPos ) ; $ resultAfterScheme = mb_substr ( $ resultUrl , $ doubleSlashPos ) ; $ resultAfterScheme = str_replace ( '//' , '/' , $ resultAfterScheme ) ; if ( $ this -> flags [ 0 ] === static :: FLAG_SCHEME_ANY ) { $ resultUrl = $ request -> GetScheme ( ) . '//' . $ resultAfterScheme ; } else { $ resultUrl = $ resultSchemePart . $ resultAfterScheme ; } return [ $ resultUrl ] ; } else { $ nextSlashPos = mb_strpos ( $ resultUrl , '/' , $ doubleSlashPos ) ; if ( $ nextSlashPos === FALSE ) { $ queryStringPos = mb_strpos ( $ resultUrl , '?' , $ doubleSlashPos ) ; $ baseUrlPartEndPos = $ queryStringPos === FALSE ? mb_strlen ( $ resultUrl ) : $ queryStringPos ; } else { $ baseUrlPartEndPos = $ nextSlashPos ; } $ requestedBasePath = $ request -> GetBasePath ( ) ; $ basePathLength = mb_strlen ( $ requestedBasePath ) ; if ( $ basePathLength > 0 ) { $ basePathPos = mb_strpos ( $ resultUrl , $ requestedBasePath , $ baseUrlPartEndPos ) ; if ( $ basePathPos === $ baseUrlPartEndPos ) $ baseUrlPartEndPos += $ basePathLength ; } $ basePart = mb_substr ( $ resultUrl , 0 , $ baseUrlPartEndPos ) ; if ( $ this -> flags [ 0 ] === static :: FLAG_SCHEME_ANY ) $ basePart = $ request -> GetScheme ( ) . $ basePart ; $ pathAndQueryPart = str_replace ( '//' , '/' , mb_substr ( $ resultUrl , $ baseUrlPartEndPos ) ) ; return [ $ basePart , $ pathAndQueryPart ] ; } }
After final URL is completed split result URL into two parts if there is contained domain part and base path in reverse what is base material to complete result URL . Try to found the point in result URL where is base path end and application request path begin . By that point split and return result URL .
21,697
public function removeUserMetaKey ( $ user_meta_key ) { $ filter = function ( $ meta_key ) use ( $ user_meta_key ) { return $ meta_key !== $ user_meta_key ; } ; $ this -> avatar_user_meta_keys = array_filter ( $ this -> avatar_user_meta_keys , $ filter ) ; }
Remove a previously added meta key
21,698
protected function idOrEmailToId ( $ id_or_email ) { if ( is_a ( $ id_or_email , WP_Comment :: class ) ) { return intval ( $ id_or_email -> user_id ) ; } if ( ! is_numeric ( $ id_or_email ) ) { $ user = get_user_by ( 'email' , $ id_or_email ) ; if ( $ user ) { return intval ( $ user -> ID ) ; } } return strval ( $ id_or_email ) ; }
Converts an id_or_email to an ID if possible .
21,699
protected function getAttachmentFallbackChain ( $ user_id ) { $ chain = [ ] ; foreach ( $ this -> avatar_user_meta_keys as $ user_meta_key ) { $ attachment_id = get_user_meta ( $ user_id , $ user_meta_key , true ) ; if ( is_numeric ( $ attachment_id ) ) { $ chain [ ] = intval ( $ attachment_id ) ; } } if ( $ this -> default_avatar_id !== 0 ) { $ chain [ ] = $ this -> default_avatar_id ; } return $ chain ; }
Get attachment fallback chain for the user avatar .