idx
int64
0
60.3k
question
stringlengths
99
4.85k
target
stringlengths
5
718
1,800
public function withPaginator ( LengthAwarePaginator $ paginator , $ transformer , $ resourceKey = null , $ meta = [ ] ) { $ queryParams = array_diff_key ( $ _GET , array_flip ( [ 'page' ] ) ) ; $ paginator -> appends ( $ queryParams ) ; $ resource = new Collection ( $ paginator -> items ( ) , $ transformer , $ resourc...
Respond with a paginator and a transformer .
1,801
public function getVariationForExperiment ( $ experimentId ) { $ decision = $ this -> getDecisionForExperiment ( $ experimentId ) ; if ( ! is_null ( $ decision ) ) { return $ decision -> getVariationId ( ) ; } return null ; }
Get the variation ID for the given experiment from the experiment bucket map .
1,802
public function getDecisionForExperiment ( $ experimentId ) { if ( isset ( $ this -> _experiment_bucket_map [ $ experimentId ] ) ) { return $ this -> _experiment_bucket_map [ $ experimentId ] ; } return null ; }
Get the decision for the given experiment from the experiment bucket map .
1,803
public static function isFeatureFlagValid ( $ config , $ featureFlag ) { $ experimentIds = $ featureFlag -> getExperimentIds ( ) ; if ( empty ( $ experimentIds ) ) { return true ; } if ( sizeof ( $ experimentIds ) == 1 ) { return true ; } $ groupId = $ config -> getExperimentFromId ( $ experimentIds [ 0 ] ) -> getGroup...
Checks that if there are more than one experiment IDs in the feature flag they must belong to the same mutex group
1,804
public static function doesArrayContainOnlyStringKeys ( $ arr ) { if ( ! is_array ( $ arr ) || empty ( $ arr ) ) { return false ; } return count ( array_filter ( array_keys ( $ arr ) , 'is_string' ) ) == count ( array_keys ( $ arr ) ) ; }
Returns true only if given input is an array with all of it s keys of type string .
1,805
public function getFeatureVariableFromKey ( $ featureFlagKey , $ variableKey ) { $ featureFlag = $ this -> getFeatureFlagFromKey ( $ featureFlagKey ) ; if ( $ featureFlag && ! ( $ featureFlag -> getKey ( ) ) ) { return null ; } if ( isset ( $ this -> _featureFlagVariableMap [ $ featureFlagKey ] ) && isset ( $ this -> _...
Gets the feature variable instance given feature flag key and variable key
1,806
public function getForcedVariation ( $ experimentKey , $ userId ) { if ( ! isset ( $ this -> _forcedVariationMap [ $ userId ] ) ) { $ this -> _logger -> log ( Logger :: DEBUG , sprintf ( 'User "%s" is not in the forced variation map.' , $ userId ) ) ; return null ; } $ experimentToVariationMap = $ this -> _forcedVariat...
Gets the forced variation key for the given user and experiment .
1,807
public function setForcedVariation ( $ experimentKey , $ userId , $ variationKey ) { if ( ! is_null ( $ variationKey ) && ! Validator :: validateNonEmptyString ( $ variationKey ) ) { $ this -> _logger -> log ( Logger :: ERROR , sprintf ( Errors :: INVALID_FORMAT , Optimizely :: VARIATION_KEY ) ) ; return false ; } $ ex...
Sets an associative array of user IDs to an associative array of experiments to forced variations .
1,808
protected function getBucketingId ( $ userId , $ userAttributes ) { $ bucketingIdKey = ControlAttributes :: BUCKETING_ID ; if ( isset ( $ userAttributes [ $ bucketingIdKey ] ) ) { if ( is_string ( $ userAttributes [ $ bucketingIdKey ] ) ) { return $ userAttributes [ $ bucketingIdKey ] ; } $ this -> _logger -> log ( Log...
Gets the ID for Bucketing
1,809
public function getVariation ( Experiment $ experiment , $ userId , $ attributes = null ) { $ bucketingId = $ this -> getBucketingId ( $ userId , $ attributes ) ; if ( ! $ experiment -> isExperimentRunning ( ) ) { $ this -> _logger -> log ( Logger :: INFO , sprintf ( 'Experiment "%s" is not running.' , $ experiment -> ...
Determine which variation to show the user .
1,810
public function getVariationForFeature ( FeatureFlag $ featureFlag , $ userId , $ userAttributes ) { $ decision = $ this -> getVariationForFeatureExperiment ( $ featureFlag , $ userId , $ userAttributes ) ; if ( $ decision ) { return $ decision ; } $ decision = $ this -> getVariationForFeatureRollout ( $ featureFlag , ...
Get the variation the user is bucketed into for the given FeatureFlag
1,811
public function getVariationForFeatureExperiment ( FeatureFlag $ featureFlag , $ userId , $ userAttributes ) { $ featureFlagKey = $ featureFlag -> getKey ( ) ; $ experimentIds = $ featureFlag -> getExperimentIds ( ) ; if ( empty ( $ experimentIds ) ) { $ this -> _logger -> log ( Logger :: DEBUG , "The feature flag '{$f...
Get the variation if the user is bucketed for one of the experiments on this feature flag
1,812
public function getVariationForFeatureRollout ( FeatureFlag $ featureFlag , $ userId , $ userAttributes ) { $ bucketing_id = $ this -> getBucketingId ( $ userId , $ userAttributes ) ; $ featureFlagKey = $ featureFlag -> getKey ( ) ; $ rollout_id = $ featureFlag -> getRolloutId ( ) ; if ( empty ( $ rollout_id ) ) { $ th...
Get the variation if the user is bucketed into rollout for this feature flag Evaluate the user for rules in priority order by seeing if the user satisfies the audience . Fall back onto the everyone else rule if the user is ever excluded from a rule due to traffic allocation .
1,813
private function getWhitelistedVariation ( Experiment $ experiment , $ userId ) { $ forcedVariations = $ experiment -> getForcedVariations ( ) ; if ( ! is_null ( $ forcedVariations ) && isset ( $ forcedVariations [ $ userId ] ) ) { $ variationKey = $ forcedVariations [ $ userId ] ; $ variation = $ this -> _projectConfi...
Determine variation the user has been forced into .
1,814
private function getStoredUserProfile ( $ userId ) { if ( is_null ( $ this -> _userProfileService ) ) { return null ; } try { $ userProfileMap = $ this -> _userProfileService -> lookup ( $ userId ) ; if ( is_null ( $ userProfileMap ) ) { $ this -> _logger -> log ( Logger :: INFO , sprintf ( 'No user profile found for u...
Get the stored user profile for the given user ID .
1,815
private function getStoredVariation ( Experiment $ experiment , UserProfile $ userProfile ) { $ experimentKey = $ experiment -> getKey ( ) ; $ userId = $ userProfile -> getUserId ( ) ; $ variationId = $ userProfile -> getVariationForExperiment ( $ experiment -> getId ( ) ) ; if ( is_null ( $ variationId ) ) { $ this ->...
Get the stored variation for the given experiment from the user profile .
1,816
private function saveVariation ( Experiment $ experiment , Variation $ variation , UserProfile $ userProfile ) { if ( is_null ( $ this -> _userProfileService ) ) { return ; } $ experimentId = $ experiment -> getId ( ) ; $ decision = $ userProfile -> getDecisionForExperiment ( $ experimentId ) ; $ variationId = $ variat...
Save the given variation assignment to the given user profile .
1,817
public function isUserInForcedVariation ( $ userId ) { $ forcedVariations = $ this -> getForcedVariations ( ) ; return ! is_null ( $ forcedVariations ) && isset ( $ forcedVariations [ $ userId ] ) ; }
Determine if user is in forced variation of experiment .
1,818
public static function getRandomUuid ( ) { return sprintf ( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x' , mt_rand ( 0 , 0xffff ) , mt_rand ( 0 , 0xffff ) , mt_rand ( 0 , 0xffff ) , mt_rand ( 0 , 0x0fff ) | 0x4000 , mt_rand ( 0 , 0x3fff ) | 0x8000 , mt_rand ( 0 , 0xffff ) , mt_rand ( 0 , 0xffff ) , mt_rand ( 0 , 0xffff ) ) ;...
Generate random uuid
1,819
public static function isValidUserProfileMap ( $ userProfileMap ) { if ( ! is_array ( $ userProfileMap ) ) { return false ; } if ( ! isset ( $ userProfileMap [ self :: USER_ID_KEY ] ) ) { return false ; } if ( ! isset ( $ userProfileMap [ self :: EXPERIMENT_BUCKET_MAP_KEY ] ) ) { return false ; } if ( ! is_array ( $ us...
Grab the revenue value from the event tags . revenue is a reserved keyword .
1,820
public static function convertMapToUserProfile ( $ userProfileMap ) { $ userId = $ userProfileMap [ self :: USER_ID_KEY ] ; $ experimentBucketMap = array ( ) ; foreach ( $ userProfileMap [ self :: EXPERIMENT_BUCKET_MAP_KEY ] as $ experimentId => $ decisionMap ) { $ variationId = $ decisionMap [ self :: VARIATION_ID_KEY...
Convert the given user profile map into a UserProfile object .
1,821
public static function convertUserProfileToMap ( $ userProfile ) { $ userProfileMap = array ( self :: USER_ID_KEY => $ userProfile -> getUserId ( ) , self :: EXPERIMENT_BUCKET_MAP_KEY => array ( ) ) ; $ experimentBucketMap = $ userProfile -> getExperimentBucketMap ( ) ; foreach ( $ experimentBucketMap as $ experimentId...
Convert the given UserProfile object into a map .
1,822
public function addNotificationListener ( $ notification_type , $ notification_callback ) { if ( ! NotificationType :: isNotificationTypeValid ( $ notification_type ) ) { $ this -> _logger -> log ( Logger :: ERROR , "Invalid notification type." ) ; $ this -> _errorHandler -> handleError ( new InvalidNotificationTypeExc...
Adds a notification callback for a notification type to the notification center
1,823
public function removeNotificationListener ( $ notification_id ) { foreach ( $ this -> _notifications as $ notification_type => $ notifications ) { foreach ( array_keys ( $ notifications ) as $ id ) { if ( $ notification_id == $ id ) { unset ( $ this -> _notifications [ $ notification_type ] [ $ id ] ) ; $ this -> _log...
Removes notification callback from the notification center
1,824
public function clearNotifications ( $ notification_type ) { $ this -> _logger -> log ( Logger :: WARNING , "'clearNotifications' is deprecated. Call 'clearNotificationListeners' instead." ) ; $ this -> clearNotificationListeners ( $ notification_type ) ; }
Logs deprecation message
1,825
public function clearNotificationListeners ( $ notification_type ) { if ( ! NotificationType :: isNotificationTypeValid ( $ notification_type ) ) { $ this -> _logger -> log ( Logger :: ERROR , "Invalid notification type." ) ; $ this -> _errorHandler -> handleError ( new InvalidNotificationTypeException ( 'Invalid notif...
Removes all notification callbacks for the given notification type
1,826
public function sendNotifications ( $ notification_type , array $ args = [ ] ) { if ( ! isset ( $ this -> _notifications [ $ notification_type ] ) ) { return ; } set_error_handler ( array ( $ this , 'reportArgumentCountError' ) , E_WARNING ) ; foreach ( array_values ( $ this -> _notifications [ $ notification_type ] ) ...
Executes all registered callbacks for the given notification type
1,827
public function reportArgumentCountError ( ) { $ this -> _logger -> log ( Logger :: ERROR , "Problem calling notify callback." ) ; $ this -> _errorHandler -> handleError ( new InvalidCallbackArgumentCountException ( 'Registered callback expects more number of arguments than the actual number' ) ) ; }
Logs and raises an exception when registered callback expects more number of arguments when executed
1,828
public static function getNumericValue ( $ eventTags , $ logger ) { if ( ! $ eventTags ) { $ logger -> log ( Logger :: DEBUG , "Event tags is undefined." ) ; return null ; } if ( ! is_array ( $ eventTags ) ) { $ logger -> log ( Logger :: DEBUG , "Event tags is not a dictionary." ) ; return null ; } if ( ! isset ( $ eve...
Grab the numeric event value from the event tags . value is a reserved keyword . The value of value can be a float or a numeric string
1,829
protected function setNullForMissingKeys ( array $ leafCondition ) { $ keys = [ 'type' , 'match' , 'value' ] ; foreach ( $ keys as $ key ) { $ leafCondition [ $ key ] = isset ( $ leafCondition [ $ key ] ) ? $ leafCondition [ $ key ] : null ; } return $ leafCondition ; }
Sets null for missing keys in a leaf condition .
1,830
protected function getMatchTypes ( ) { return array ( self :: EXACT_MATCH_TYPE , self :: EXISTS_MATCH_TYPE , self :: GREATER_THAN_MATCH_TYPE , self :: LESS_THAN_MATCH_TYPE , self :: SUBSTRING_MATCH_TYPE ) ; }
Gets the supported match types for condition evaluation .
1,831
protected function getEvaluatorByMatchType ( $ matchType ) { $ evaluatorsByMatchType = array ( ) ; $ evaluatorsByMatchType [ self :: EXACT_MATCH_TYPE ] = 'exactEvaluator' ; $ evaluatorsByMatchType [ self :: EXISTS_MATCH_TYPE ] = 'existsEvaluator' ; $ evaluatorsByMatchType [ self :: GREATER_THAN_MATCH_TYPE ] = 'greaterT...
Gets the evaluator method name for the given match type .
1,832
protected function isValueTypeValidForExactConditions ( $ value ) { if ( is_string ( $ value ) || is_bool ( $ value ) || is_int ( $ value ) || is_float ( $ value ) ) { return true ; } return false ; }
Checks if the given input is a valid value for exact condition evaluation .
1,833
protected function exactEvaluator ( $ condition ) { $ conditionName = $ condition [ 'name' ] ; $ conditionValue = $ condition [ 'value' ] ; $ userValue = isset ( $ this -> userAttributes [ $ conditionName ] ) ? $ this -> userAttributes [ $ conditionName ] : null ; if ( ! $ this -> isValueTypeValidForExactConditions ( $...
Evaluate the given exact match condition for the given user attributes .
1,834
protected function substringEvaluator ( $ condition ) { $ conditionName = $ condition [ 'name' ] ; $ conditionValue = $ condition [ 'value' ] ; $ userValue = isset ( $ this -> userAttributes [ $ conditionName ] ) ? $ this -> userAttributes [ $ conditionName ] : null ; if ( ! is_string ( $ conditionValue ) ) { $ this ->...
Evaluate the given substring than match condition for the given user attributes .
1,835
protected function getEvaluatorByOperatorType ( $ operator ) { $ evaluatorsByOperator = array ( ) ; $ evaluatorsByOperator [ self :: AND_OPERATOR ] = 'andEvaluator' ; $ evaluatorsByOperator [ self :: OR_OPERATOR ] = 'orEvaluator' ; $ evaluatorsByOperator [ self :: NOT_OPERATOR ] = 'notEvaluator' ; return $ evaluatorsBy...
Returns corresponding evaluator method name for the given operator .
1,836
protected function andEvaluator ( array $ conditions , callable $ leafEvaluator ) { $ sawNullResult = false ; foreach ( $ conditions as $ condition ) { $ result = $ this -> evaluate ( $ condition , $ leafEvaluator ) ; if ( $ result === false ) { return false ; } if ( $ result === null ) { $ sawNullResult = true ; } } r...
Evaluates an array of conditions as if the evaluator had been applied to each entry and the results AND - ed together .
1,837
protected function notEvaluator ( array $ condition , callable $ leafEvaluator ) { if ( empty ( $ condition ) ) { return null ; } $ result = $ this -> evaluate ( $ condition [ 0 ] , $ leafEvaluator ) ; return $ result === null ? null : ! $ result ; }
Evaluates an array of conditions as if the evaluator had been applied to a single entry and NOT was applied to the result .
1,838
protected function generateBucketValue ( $ bucketingKey ) { $ hashCode = $ this -> generateHashCode ( $ bucketingKey ) ; $ ratio = $ hashCode / Bucketer :: $ MAX_HASH_VALUE ; $ bucketVal = intval ( floor ( $ ratio * Bucketer :: $ MAX_TRAFFIC_VALUE ) ) ; if ( $ bucketVal < 0 ) { $ bucketVal += 10000 ; } return $ bucketV...
Generate an integer to be used in bucketing user to a particular variation .
1,839
public function bucket ( ProjectConfig $ config , Experiment $ experiment , $ bucketingId , $ userId ) { if ( is_null ( $ experiment -> getKey ( ) ) ) { return null ; } if ( $ experiment -> isInMutexGroup ( ) ) { $ group = $ config -> getGroup ( $ experiment -> getGroupId ( ) ) ; if ( is_null ( $ group -> getId ( ) ) )...
Determine variation the user should be put in .
1,840
private function generateVariableIdToVariableUsageMap ( ) { if ( ! empty ( $ this -> _variableUsageInstances ) ) { foreach ( array_values ( $ this -> _variableUsageInstances ) as $ variableUsage ) { $ this -> _variableIdToVariableUsageInstanceMap [ $ variableUsage -> getId ( ) ] = $ variableUsage ; } } }
Generates variable ID to Variable usage instance map from variable usage instances
1,841
private function validateUserInputs ( $ attributes , $ eventTags = null ) { if ( ! is_null ( $ attributes ) && ! Validator :: areAttributesValid ( $ attributes ) ) { $ this -> _logger -> log ( Logger :: ERROR , 'Provided attributes are in an invalid format.' ) ; $ this -> _errorHandler -> handleError ( new InvalidAttri...
Helper function to validate user inputs into the API methods .
1,842
public function activate ( $ experimentKey , $ userId , $ attributes = null ) { if ( ! $ this -> _isValid ) { $ this -> _logger -> log ( Logger :: ERROR , 'Datafile has invalid format. Failing "activate".' ) ; return null ; } if ( ! $ this -> validateInputs ( [ self :: EXPERIMENT_KEY => $ experimentKey , self :: USER_I...
Buckets visitor and sends impression event to Optimizely .
1,843
public function track ( $ eventKey , $ userId , $ attributes = null , $ eventTags = null ) { if ( ! $ this -> _isValid ) { $ this -> _logger -> log ( Logger :: ERROR , 'Datafile has invalid format. Failing "track".' ) ; return ; } if ( ! $ this -> validateInputs ( [ self :: EVENT_KEY => $ eventKey , self :: USER_ID => ...
Send conversion event to Optimizely .
1,844
public function getVariation ( $ experimentKey , $ userId , $ attributes = null ) { if ( ! $ this -> _isValid ) { $ this -> _logger -> log ( Logger :: ERROR , 'Datafile has invalid format. Failing "getVariation".' ) ; return null ; } if ( ! $ this -> validateInputs ( [ self :: EXPERIMENT_KEY => $ experimentKey , self :...
Get variation where user will be bucketed .
1,845
public function setForcedVariation ( $ experimentKey , $ userId , $ variationKey ) { if ( ! $ this -> validateInputs ( [ self :: EXPERIMENT_KEY => $ experimentKey , self :: USER_ID => $ userId ] ) ) { return false ; } return $ this -> _config -> setForcedVariation ( $ experimentKey , $ userId , $ variationKey ) ; }
Force a user into a variation for a given experiment .
1,846
public function getForcedVariation ( $ experimentKey , $ userId ) { if ( ! $ this -> validateInputs ( [ self :: EXPERIMENT_KEY => $ experimentKey , self :: USER_ID => $ userId ] ) ) { return null ; } $ forcedVariation = $ this -> _config -> getForcedVariation ( $ experimentKey , $ userId ) ; if ( isset ( $ forcedVariat...
Gets the forced variation for a given user and experiment .
1,847
public function isFeatureEnabled ( $ featureFlagKey , $ userId , $ attributes = null ) { if ( ! $ this -> _isValid ) { $ this -> _logger -> log ( Logger :: ERROR , "Datafile has invalid format. Failing '" . __FUNCTION__ . "'." ) ; return false ; } if ( ! $ this -> validateInputs ( [ self :: FEATURE_FLAG_KEY => $ featur...
Determine whether a feature is enabled . Sends an impression event if the user is bucketed into an experiment using the feature .
1,848
public function getEnabledFeatures ( $ userId , $ attributes = null ) { $ enabledFeatureKeys = [ ] ; if ( ! $ this -> validateInputs ( [ self :: USER_ID => $ userId ] ) ) { return $ enabledFeatureKeys ; } if ( ! $ this -> _isValid ) { $ this -> _logger -> log ( Logger :: ERROR , "Datafile has invalid format. Failing '"...
Get keys of all feature flags which are enabled for the user
1,849
public function getFeatureVariableBoolean ( $ featureFlagKey , $ variableKey , $ userId , $ attributes = null ) { return $ this -> getFeatureVariableValueForType ( $ featureFlagKey , $ variableKey , $ userId , $ attributes , FeatureVariable :: BOOLEAN_TYPE ) ; }
Get the Boolean value of the specified variable in the feature flag .
1,850
public function getFeatureVariableInteger ( $ featureFlagKey , $ variableKey , $ userId , $ attributes = null ) { return $ this -> getFeatureVariableValueForType ( $ featureFlagKey , $ variableKey , $ userId , $ attributes , FeatureVariable :: INTEGER_TYPE ) ; }
Get the Integer value of the specified variable in the feature flag .
1,851
public function getFeatureVariableDouble ( $ featureFlagKey , $ variableKey , $ userId , $ attributes = null ) { return $ this -> getFeatureVariableValueForType ( $ featureFlagKey , $ variableKey , $ userId , $ attributes , FeatureVariable :: DOUBLE_TYPE ) ; }
Get the Double value of the specified variable in the feature flag .
1,852
public function getFeatureVariableString ( $ featureFlagKey , $ variableKey , $ userId , $ attributes = null ) { return $ this -> getFeatureVariableValueForType ( $ featureFlagKey , $ variableKey , $ userId , $ attributes , FeatureVariable :: STRING_TYPE ) ; }
Get the String value of the specified variable in the feature flag .
1,853
private function getCommonParams ( $ config , $ userId , $ attributes ) { $ visitor = [ SNAPSHOTS => [ ] , VISITOR_ID => $ userId , ATTRIBUTES => [ ] ] ; $ commonParams = [ ACCOUNT_ID => $ config -> getAccountId ( ) , PROJECT_ID => $ config -> getProjectId ( ) , VISITORS => [ $ visitor ] , REVISION => $ config -> getRe...
Helper function to get parameters common to impression and conversion events .
1,854
private function getImpressionParams ( Experiment $ experiment , $ variationId ) { $ impressionParams = [ DECISIONS => [ [ CAMPAIGN_ID => $ experiment -> getLayerId ( ) , EXPERIMENT_ID => $ experiment -> getId ( ) , VARIATION_ID => $ variationId ] ] , EVENTS => [ [ ENTITY_ID => $ experiment -> getLayerId ( ) , TIMESTAM...
Helper function to get parameters specific to impression event .
1,855
private function getConversionParams ( $ eventEntity , $ eventTags ) { $ conversionParams = [ ] ; $ singleSnapshot = [ ] ; $ eventDict = [ ENTITY_ID => $ eventEntity -> getId ( ) , TIMESTAMP => time ( ) * 1000 , UUID => GeneratorUtils :: getRandomUuid ( ) , KEY => $ eventEntity -> getKey ( ) ] ; if ( ! is_null ( $ even...
Helper function to get parameters specific to conversion event .
1,856
public function createImpressionEvent ( $ config , $ experimentKey , $ variationKey , $ userId , $ attributes ) { $ eventParams = $ this -> getCommonParams ( $ config , $ userId , $ attributes ) ; $ experiment = $ config -> getExperimentFromKey ( $ experimentKey ) ; $ variation = $ config -> getVariationFromKey ( $ exp...
Create impression event to be sent to the logging endpoint .
1,857
public function createConversionEvent ( $ config , $ eventKey , $ userId , $ attributes , $ eventTags ) { $ eventParams = $ this -> getCommonParams ( $ config , $ userId , $ attributes ) ; $ eventEntity = $ config -> getEvent ( $ eventKey ) ; $ conversionParams = $ this -> getConversionParams ( $ eventEntity , $ eventT...
Create conversion event to be sent to the logging endpoint .
1,858
public function saveSubmission ( Submission $ submission ) { $ contactFormSubmission = new ContactFormSubmission ( ) ; $ contactFormSubmission -> form = $ submission -> message [ 'formName' ] ?? 'contact' ; $ contactFormSubmission -> fromName = $ submission -> fromName ; $ contactFormSubmission -> fromEmail = $ submiss...
This function can literally be anything you want and you can have as many service functions as you want .
1,859
public function render ( $ view = null , $ layout = null ) { if ( $ this -> hasRendered ) { return null ; } $ this -> layout = "RestApi.{$this->_responseLayout}" ; $ this -> Blocks -> set ( 'content' , $ this -> renderLayout ( '' , $ this -> layout ) ) ; $ this -> hasRendered = true ; return $ this -> Blocks -> get ( '...
Renders api response
1,860
protected function _performTokenValidation ( Event $ event ) { $ request = $ event -> getSubject ( ) -> request ; if ( ! empty ( $ request -> getParam ( 'allowWithoutToken' ) ) && $ request -> getParam ( 'allowWithoutToken' ) ) { return true ; } $ token = '' ; $ header = $ request -> getHeader ( 'Authorization' ) ; if ...
Performs token validation .
1,861
public function beforeDispatch ( Event $ event ) { $ this -> buildResponse ( $ event ) ; Configure :: write ( 'requestLogged' , false ) ; $ request = $ event -> getData ( ) [ 'request' ] ; if ( 'OPTIONS' === $ request -> getMethod ( ) ) { $ event -> stopPropagation ( ) ; $ response = $ event -> getData ( ) [ 'response'...
Handles incoming request and its data .
1,862
private function buildResponse ( Event $ event ) { $ request = $ event -> getData ( ) [ 'request' ] ; $ response = $ event -> getData ( ) [ 'response' ] ; if ( 'xml' === Configure :: read ( 'ApiRequest.responseType' ) ) { $ response -> withType ( 'xml' ) ; } else { $ response -> withType ( 'json' ) ; } $ response -> co...
Prepares the response object with content type and cors headers .
1,863
private function __prepareResponse ( $ exception , $ options = [ ] ) { $ response = $ this -> _getController ( ) -> response ; $ code = $ this -> _code ( $ exception ) ; $ response -> getStatusCode ( $ this -> _code ( $ exception ) ) ; Configure :: write ( 'apiExceptionMessage' , $ exception -> getMessage ( ) ) ; $ res...
Prepare response .
1,864
public function beforeRender ( Event $ event ) { $ this -> httpStatusCode = $ this -> response -> getStatusCode ( ) ; $ messageArr = $ this -> response -> withStatus ( $ this -> httpStatusCode ) ; if ( Configure :: read ( 'ApiRequest.debug' ) && isset ( $ this -> viewVars [ 'error' ] ) ) { $ this -> apiResponse [ $ thi...
beforeRender callback .
1,865
public static function generateToken ( $ payload = null ) { if ( empty ( $ payload ) ) { return false ; } $ token = JWT :: encode ( $ payload , Configure :: read ( 'ApiRequest.jwtAuth.cypherKey' ) , Configure :: read ( 'ApiRequest.jwtAuth.tokenAlgorithm' ) ) ; return $ token ; }
Generates a token based on payload
1,866
protected function createCurlOptions ( RequestInterface $ request , ResponseBuilder $ responseBuilder ) { $ options = array_diff_key ( $ this -> options , array_flip ( [ CURLOPT_INFILE , CURLOPT_INFILESIZE ] ) ) ; $ options [ CURLOPT_HTTP_VERSION ] = $ this -> getCurlHttpVersion ( $ request -> getProtocolVersion ( ) ) ...
Generates cURL options
1,867
protected function createHeaders ( RequestInterface $ request , array $ options ) { $ headers = [ ] ; $ body = $ request -> getBody ( ) ; $ size = $ body -> getSize ( ) ; foreach ( $ request -> getHeaders ( ) as $ header => $ values ) { foreach ( ( array ) $ values as $ value ) { $ headers [ ] = sprintf ( '%s: %s' , $ ...
Create headers array for CURLOPT_HTTPHEADER
1,868
protected function createResponseBuilder ( ) { try { $ body = $ this -> streamFactory -> createStream ( fopen ( 'php://temp' , 'w+' ) ) ; } catch ( \ InvalidArgumentException $ e ) { throw new \ RuntimeException ( 'Can not create "php://temp" stream.' ) ; } $ response = $ this -> messageFactory -> createResponse ( 200 ...
Create new ResponseBuilder instance
1,869
public function createStream ( $ body = null ) { if ( ! $ body instanceof StreamInterface ) { if ( is_resource ( $ body ) ) { $ body = new Stream ( $ body ) ; } else { $ stream = new Stream ( 'php://temp' , 'rb+' ) ; if ( null !== $ body ) { $ stream -> write ( ( string ) $ body ) ; } $ body = $ stream ; } } $ body -> ...
Create a new stream instance .
1,870
public function assertBundles ( TableNode $ expected ) { $ bundle_info = [ ] ; foreach ( $ this -> getContentEntityTypes ( ) as $ entity_type ) { $ bundles = $ this -> entityTypeManager ( ) -> getStorage ( $ entity_type -> getBundleEntityType ( ) ) -> loadMultiple ( ) ; foreach ( $ bundles as $ bundle ) { $ description...
Asserts the configuration of content entity type bundles .
1,871
public function assertFields ( TableNode $ expected ) { $ fields = [ ] ; foreach ( $ this -> getContentEntityTypes ( ) as $ entity_type ) { $ bundles = $ this -> entityTypeManager ( ) -> getStorage ( $ entity_type -> getBundleEntityType ( ) ) -> loadMultiple ( ) ; foreach ( $ bundles as $ bundle ) { $ ids = \ Drupal ::...
Asserts the configuration of fields on select content entity types .
1,872
protected function getContentEntityTypes ( ) { $ ids = [ 'block_content' , 'media' , 'node' , 'paragraph' , 'taxonomy_term' , ] ; $ entity_types = [ ] ; foreach ( $ ids as $ id ) { try { $ entity_types [ ] = $ this -> entityTypeManager ( ) -> getDefinition ( $ id ) ; } catch ( PluginNotFoundException $ e ) { } } return...
Gets the content entity types of interest .
1,873
public function assertMenusExist ( TableNode $ expected ) { $ menu_info = [ ] ; $ menus = $ this -> entityTypeManager ( ) -> getStorage ( 'menu' ) -> loadMultiple ( ) ; foreach ( $ menus as $ id => $ menu ) { $ menu_info [ ] = [ $ menu -> label ( ) , $ id , $ menu -> getDescription ( ) ] ; } $ actual = new TableNode ( ...
Asserts the configuration of menus .
1,874
public function assertImageStyles ( TableNode $ expected ) { $ image_style_info = [ ] ; foreach ( $ this -> getImageStyles ( ) as $ image_style ) { $ image_style_info [ ] = [ $ image_style -> label ( ) , $ image_style -> id ( ) , ] ; } $ actual = new TableNode ( $ image_style_info ) ; ( new TableEqualityAssertion ( $ e...
Asserts the configuration of image styles .
1,875
public function assertImageEffects ( TableNode $ expected ) { $ image_style_info = [ ] ; foreach ( $ this -> getImageStyles ( ) as $ image_style ) { foreach ( $ image_style -> getEffects ( ) as $ effect ) { $ image_style_info [ ] = [ $ image_style -> label ( ) , ( string ) $ effect -> label ( ) , $ this -> formatImageE...
Asserts the configuration of image effects .
1,876
private function formatImageEffectSummary ( array $ summary ) { $ rendered = ( string ) $ this -> renderer -> renderPlain ( $ summary ) ; $ plaintext = strip_tags ( $ rendered ) ; $ trimmed = trim ( $ plaintext ) ; $ one_line = preg_replace ( '/[ \n]+/' , ' ' , $ trimmed ) ; return $ one_line ; }
Formats an image effect summary for use in a Gherkin data table .
1,877
public function assertWorkflows ( TableNode $ expected ) { $ workflow_info = [ ] ; foreach ( $ this -> getWorkflows ( ) as $ workflow ) { $ workflow_info [ ] = [ $ workflow -> label ( ) , $ workflow -> id ( ) , ( string ) $ workflow -> getTypePlugin ( ) -> label ( ) , ] ; } $ actual = new TableNode ( $ workflow_info ) ...
Asserts the configuration of workflows .
1,878
public function assertWorkflowStates ( TableNode $ expected ) { $ states_info = [ ] ; foreach ( $ this -> getWorkflows ( ) as $ workflow ) { $ states = $ workflow -> getTypePlugin ( ) -> getStates ( ) ; foreach ( $ states as $ state ) { $ states_info [ ] = [ $ workflow -> label ( ) , $ state -> label ( ) , $ state -> i...
Asserts the configuration of workflow states .
1,879
public function assertWorkflowTransitions ( TableNode $ expected ) { $ states_info = [ ] ; foreach ( $ this -> getWorkflows ( ) as $ workflow ) { $ transitions = $ workflow -> getTypePlugin ( ) -> getTransitions ( ) ; foreach ( $ transitions as $ transition ) { foreach ( $ transition -> from ( ) as $ from_state ) { $ s...
Asserts the configuration of workflow transitions .
1,880
public function assertRolesExist ( TableNode $ expected ) { $ role_info = [ ] ; $ roles = $ this -> entityTypeManager ( ) -> getStorage ( 'user_role' ) -> loadMultiple ( ) ; foreach ( $ roles as $ id => $ role ) { $ role_info [ ] = [ $ role -> label ( ) , $ id ] ; } $ actual = new TableNode ( $ role_info ) ; ( new Tabl...
Asserts the configuration of roles .
1,881
public function assertViewsExist ( TableNode $ expected ) { $ views_info = [ ] ; foreach ( $ this -> getViews ( ) as $ id => $ view ) { $ views_info [ ] = [ $ view -> label ( ) , $ id , $ this -> getBaseTableLabel ( $ view -> get ( 'base_table' ) ) , $ view -> status ( ) ? 'Enabled' : 'Disabled' , $ view -> get ( 'desc...
Asserts the configuration of views .
1,882
public function assertViewDisplaysExist ( TableNode $ expected ) { $ displays_info = [ ] ; foreach ( $ this -> getViews ( ) as $ view ) { foreach ( $ view -> get ( 'display' ) as $ display ) { $ definition = $ this -> viewsDisplayManager -> getDefinition ( $ display [ 'display_plugin' ] ) ; $ displays_info [ ] = [ $ vi...
Asserts the configuration of views displays .
1,883
private function getBaseTables ( ) { $ base_tables = [ ] ; $ wizard_plugins = $ this -> viewsWizardManager -> getDefinitions ( ) ; foreach ( $ wizard_plugins as $ wizard ) { if ( ! array_key_exists ( 'base_table' , $ wizard ) ) { continue ; } $ base_tables [ $ wizard [ 'base_table' ] ] = ( string ) $ wizard [ 'title' ]...
Gets the list of Views base tables .
1,884
private function getBaseTableLabel ( $ id ) { return array_key_exists ( $ id , $ this -> baseTables ) ? $ this -> baseTables [ $ id ] : $ id ; }
Gets the human - readable label for a given base table ID .
1,885
private function registerCache ( ContainerBuilder $ container ) : self { $ container -> register ( 'contentful.delivery.cache_clearer' , CacheClearer :: class ) -> setAbstract ( \ true ) ; $ container -> register ( 'contentful.delivery.cache_warmer' , CacheWarmer :: class ) -> setAbstract ( \ true ) ; return $ this ; }
Registers two base cache handlers one for warming up and one for clearing . They are defined as abstract as a concrete implementation will be defined for every configured client .
1,886
private function registerCommand ( ContainerBuilder $ container ) : self { $ container -> register ( 'contentful.delivery.command.info' , InfoCommand :: class ) -> addArgument ( new Parameter ( 'contentful.delivery.clients.info' ) ) -> addTag ( 'console.command' , [ 'command' => 'contentful:delivery:info' , ] ) ; $ con...
Registers the CLI command which is in charge of extracting the configuration info and displaying it for debugging purposes .
1,887
private function registerDataCollector ( ContainerBuilder $ container ) : self { $ container -> register ( 'contentful.delivery.data_collector' , ClientDataCollector :: class ) -> addArgument ( new TaggedIteratorArgument ( 'contentful.delivery.client' ) ) -> addArgument ( new Parameter ( 'contentful.delivery.clients.in...
Registers the data collector which will display info about the configured clients and the queries being made to the API .
1,888
private function configureDeliveryOptions ( array $ options ) : array { $ logger = $ options [ 'options' ] [ 'logger' ] ; if ( \ null !== $ logger ) { $ options [ 'options' ] [ 'logger' ] = \ true === $ logger ? new Reference ( LoggerInterface :: class ) : new Reference ( $ options [ 'options' ] [ 'logger' ] ) ; } if (...
Converts the references in the configuration into actual Reference objects .
1,889
public function process ( ContainerBuilder $ container ) { if ( ! $ container -> hasDefinition ( 'profiler' ) || ! $ container -> hasDefinition ( 'twig' ) ) { return ; } $ container -> register ( 'contentful.delivery.profiler_controller' , ProfilerController :: class ) -> setArguments ( [ new Reference ( 'profiler' ) ,...
Loads the definition for the ProfilerController when the profiler and twig are present .
1,890
public function tagUserContext ( FilterResponseEvent $ event ) { $ response = $ event -> getResponse ( ) ; if ( ! $ response -> isCacheable ( ) ) { return ; } if ( $ response -> headers -> get ( 'Content-Type' ) !== 'application/vnd.fos.user-context-hash' ) { return ; } if ( ! $ response -> getTtl ( ) ) { return ; } $ ...
Tag vnd . fos . user - context - hash responses if they are set to cached .
1,891
protected function cleanupHeadersForProd ( Response $ response ) { $ response -> headers -> remove ( 'xkey' ) ; $ response -> headers -> remove ( 'x-content-digest' ) ; $ varyValues = [ ] ; $ variesByUser = false ; foreach ( $ response -> getVary ( ) as $ value ) { if ( $ value === 'X-User-Hash' ) { $ variesByUser = tr...
Perform cleanup of reponse .
1,892
public function tagHttpCacheForLocation ( Location $ location ) { $ this -> responseTagger -> tag ( $ location ) ; $ this -> responseTagger -> tag ( $ location -> getContentInfo ( ) ) ; }
Adds tags to current response .
1,893
private function saveTag ( $ tag , $ digest ) { $ path = $ this -> getTagPath ( $ tag ) . DIRECTORY_SEPARATOR . $ digest ; if ( ! is_dir ( dirname ( $ path ) ) && false === @ mkdir ( dirname ( $ path ) , 0777 , true ) && ! is_dir ( dirname ( $ path ) ) ) { return false ; } $ tmpFile = tempnam ( dirname ( $ path ) , bas...
Save digest for the given tag .
1,894
private function purgeByCacheTag ( $ tag ) { $ cacheTagsCacheDir = $ this -> getTagPath ( $ tag ) ; if ( ! file_exists ( $ cacheTagsCacheDir ) || ! is_dir ( $ cacheTagsCacheDir ) ) { return ; } $ files = ( new Finder ( ) ) -> files ( ) -> in ( $ cacheTagsCacheDir ) ; foreach ( $ files as $ file ) { if ( $ digest = file...
Purges cache for tag .
1,895
public function onKernelResponse ( FilterResponseEvent $ event ) { if ( HttpKernelInterface :: MASTER_REQUEST != $ event -> getRequestType ( ) ) { return ; } if ( ! in_array ( $ event -> getRequest ( ) -> get ( '_route' ) , $ this -> routes ) ) { return ; } $ response = $ event -> getResponse ( ) ; $ varyHeaders = $ re...
Remove Vary headers for matched routes .
1,896
public function buildProxyClient ( array $ servers , $ baseUrl ) { $ allServers = array ( ) ; foreach ( $ servers as $ server ) { if ( ! $ this -> dynamicSettingParser -> isDynamicSetting ( $ server ) ) { $ allServers [ ] = $ server ; continue ; } $ settings = $ this -> dynamicSettingParser -> parseDynamicSetting ( $ s...
Builds the proxy client taking dynamically defined servers into account .
1,897
private function addPurgeAuthHeader ( array $ headers ) { if ( $ this -> configResolver -> hasParameter ( self :: INVALIDATE_TOKEN_PARAM ) && null !== ( $ token = $ this -> configResolver -> getParameter ( self :: INVALIDATE_TOKEN_PARAM ) ) ) { $ headers [ self :: INVALIDATE_TOKEN_PARAM_NAME ] = $ token ; } return $ he...
Adds an Authentication header for Purge .
1,898
protected function generateTags ( Signal $ signal ) { $ tags = [ ] ; if ( isset ( $ signal -> contentId ) ) { $ tags [ ] = 'content-' . $ signal -> contentId ; $ tags [ ] = 'relation-' . $ signal -> contentId ; } if ( isset ( $ signal -> locationId ) ) { $ tags [ ] = 'location-' . $ signal -> locationId ; $ tags [ ] = ...
Default provides tags to clear content relation location parent and sibling cache .
1,899
protected function getFiles ( $ path ) { $ path = Str :: finish ( $ path , '/' ) ; if ( file_exists ( $ path . App :: getLocale ( ) ) ) { return File :: files ( $ path . App :: getLocale ( ) ) ; } elseif ( file_exists ( $ path . config ( 'app.fallback_locale' ) ) ) { return File :: files ( $ path . config ( 'app.fallba...
Get the files for the given locale .