idx
int64
0
60.3k
question
stringlengths
99
4.85k
target
stringlengths
5
718
1,600
protected function delete ( $ url , array $ data = null ) { return $ this -> request ( 'DELETE' , $ url , [ 'Content-Type' => 'application/json' ] , $ data !== null ? json_encode ( $ data ) : null ) ; }
Sends a HTTP DELETE request to the specified url .
1,601
protected function post ( $ url , array $ data = null ) { return $ this -> request ( 'POST' , $ url , [ 'Content-Type' => 'application/json' ] , $ data !== null ? \ json_encode ( $ data ) : null ) ; }
Sends a HTTP POST request to the specified url .
1,602
public function status ( $ status ) { $ httpStatus = ( string ) $ this -> response -> getStatusCode ( ) ; if ( is_array ( $ status ) && ! in_array ( $ httpStatus , $ status ) ) { throw new \ RuntimeException ( "Unexpected response status code: {$httpStatus}" ) ; } if ( is_string ( $ status ) && $ httpStatus !== $ status ) { throw new \ RuntimeException ( "Unexpected response status code: {$httpStatus}" ) ; } return $ this ; }
Asserts the HTTP response status code .
1,603
protected function fileEndsWith ( string $ haystack , string $ needle ) : bool { $ length = strlen ( $ needle ) ; if ( strlen ( $ haystack ) < $ length ) { return $ this -> fileEndsWith ( $ needle , $ haystack ) ; } $ haystack = str_replace ( '\\' , '/' , $ haystack ) ; $ needle = str_replace ( '\\' , '/' , $ needle ) ; return ( substr ( $ haystack , - $ length ) === $ needle ) ; }
Find if two strings end in the same way
1,604
public function getCoveredLines ( ) : array { $ this -> getDiff ( ) ; $ coveredFiles = $ this -> fileChecker -> parseLines ( ) ; $ this -> uncoveredLines = [ ] ; $ this -> coveredLines = [ ] ; $ diffFiles = array_keys ( $ this -> cache -> diff ) ; foreach ( $ diffFiles as $ file ) { $ matchedFile = $ this -> findFile ( $ file , $ coveredFiles ) ; if ( $ matchedFile !== '' ) { $ this -> matchLines ( $ file , $ matchedFile ) ; } } return [ 'uncoveredLines' => $ this -> uncoveredLines , 'coveredLines' => $ this -> coveredLines , ] ; }
array of uncoveredLines and coveredLines
1,605
private function addApple ( $ os ) { $ config = $ this -> root -> children ( ) -> arrayNode ( $ os ) -> children ( ) -> scalarNode ( "timeout" ) -> defaultValue ( 60 ) -> end ( ) -> booleanNode ( "sandbox" ) -> defaultFalse ( ) -> end ( ) -> scalarNode ( "pem" ) -> cannotBeEmpty ( ) -> end ( ) -> scalarNode ( "passphrase" ) -> defaultValue ( "" ) -> end ( ) -> scalarNode ( 'json_unescaped_unicode' ) -> defaultFalse ( ) ; if ( method_exists ( $ config , 'info' ) ) { $ config = $ config -> info ( 'PHP >= 5.4.0 and each messaged must be UTF-8 encoding' ) ; } $ config -> end ( ) -> end ( ) -> end ( ) -> end ( ) ; }
Generic Apple Configuration
1,606
protected function addWindowsphone ( ) { $ this -> root -> children ( ) -> arrayNode ( 'windowsphone' ) -> children ( ) -> scalarNode ( "timeout" ) -> defaultValue ( 5 ) -> end ( ) -> end ( ) -> end ( ) -> end ( ) ; }
Windows Phone configuration
1,607
public function send ( MessageInterface $ message ) { if ( ! $ message instanceof BlackberryMessage ) { throw new InvalidMessageTypeException ( sprintf ( "Message type '%s' not supported by Blackberry" , get_class ( $ message ) ) ) ; } return $ this -> doSend ( $ message ) ; }
Sends a Blackberry Push message
1,608
protected function doSend ( BlackberryMessage $ message ) { $ separator = "mPsbVQo0a68eIL3OAxnm" ; $ body = $ this -> constructMessageBody ( $ message , $ separator ) ; $ browser = new Browser ( new Curl ( ) ) ; $ browser -> getClient ( ) -> setTimeout ( $ this -> timeout ) ; $ listener = new BasicAuthListener ( $ this -> appID , $ this -> password ) ; $ browser -> addListener ( $ listener ) ; $ url = "https://pushapi.na.blackberry.com/mss/PD_pushRequest" ; if ( $ this -> evaluation ) { $ url = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest" ; } $ headers = array ( ) ; $ headers [ ] = "Content-Type: multipart/related; boundary={$separator}; type=application/xml" ; $ headers [ ] = "Accept: text/html, *" ; $ headers [ ] = "Connection: Keep-Alive" ; $ response = $ browser -> post ( $ url , $ headers , $ body ) ; return $ this -> parseResponse ( $ response ) ; }
Does the actual sending
1,609
protected function constructMessageBody ( BlackberryMessage $ message , $ separator ) { $ data = "" ; $ messageID = microtime ( true ) ; $ data .= "--" . $ separator . "\r\n" ; $ data .= "Content-Type: application/xml; charset=UTF-8\r\n\r\n" ; $ data .= $ this -> getXMLBody ( $ message , $ messageID ) . "\r\n" ; $ data .= "--" . $ separator . "\r\n" ; $ data .= "Content-Type: text/plain\r\n" ; $ data .= "Push-Message-ID: {$messageID}\r\n\r\n" ; if ( is_array ( $ message -> getMessageBody ( ) ) ) { $ data .= json_encode ( $ message -> getMessageBody ( ) ) ; } else { $ data .= $ message -> getMessageBody ( ) ; } $ data .= "\r\n" ; $ data .= "--" . $ separator . "--\r\n" ; return $ data ; }
Builds the actual body of the message
1,610
private function getXMLBody ( BlackberryMessage $ message , $ messageID ) { $ deliverBefore = gmdate ( 'Y-m-d\TH:i:s\Z' , strtotime ( '+5 minutes' ) ) ; $ impl = new \ DOMImplementation ( ) ; $ dtd = $ impl -> createDocumentType ( "pap" , "-//WAPFORUM//DTD PAP 2.1//EN" , "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd" ) ; $ doc = $ impl -> createDocument ( "" , "" , $ dtd ) ; $ pm = $ doc -> createElement ( "push-message" ) ; $ pm -> setAttribute ( "push-id" , $ messageID ) ; $ pm -> setAttribute ( "deliver-before-timestamp" , $ deliverBefore ) ; $ pm -> setAttribute ( "source-reference" , $ this -> appID ) ; $ qos = $ doc -> createElement ( "quality-of-service" ) ; $ qos -> setAttribute ( "delivery-method" , "unconfirmed" ) ; $ add = $ doc -> createElement ( "address" ) ; $ add -> setAttribute ( "address-value" , $ message -> getDeviceIdentifier ( ) ) ; $ pm -> appendChild ( $ add ) ; $ pm -> appendChild ( $ qos ) ; $ pap = $ doc -> createElement ( "pap" ) ; $ pap -> appendChild ( $ pm ) ; $ doc -> appendChild ( $ pap ) ; return $ doc -> saveXML ( ) ; }
Create the XML body that accompanies the actual push data
1,611
public function send ( MessageInterface $ message ) { if ( ! $ message instanceof AndroidMessage ) { throw new InvalidMessageTypeException ( sprintf ( "Message type '%s' not supported by GCM" , get_class ( $ message ) ) ) ; } if ( ! $ message -> isGCM ( ) ) { throw new InvalidMessageTypeException ( "Non-GCM messages not supported by the Android GCM sender" ) ; } $ headers = array ( "Authorization: key=" . $ this -> apiKey , "Content-Type: application/json" , ) ; $ data = array_merge ( $ message -> getGCMOptions ( ) , array ( "data" => $ message -> getData ( ) ) ) ; if ( $ this -> useDryRun ) { $ data [ 'dry_run' ] = true ; } $ this -> responses = array ( ) ; $ gcmIdentifiers = $ message -> getGCMIdentifiers ( ) ; if ( count ( $ message -> getGCMIdentifiers ( ) ) == 1 ) { $ data [ 'to' ] = $ gcmIdentifiers [ 0 ] ; $ this -> responses [ ] = $ this -> browser -> post ( $ this -> apiURL , $ headers , json_encode ( $ data ) ) ; } else { $ chunks = array_chunk ( $ message -> getGCMIdentifiers ( ) , $ this -> registrationIdMaxCount ) ; foreach ( $ chunks as $ registrationIDs ) { $ data [ 'registration_ids' ] = $ registrationIDs ; $ this -> responses [ ] = $ this -> browser -> post ( $ this -> apiURL , $ headers , json_encode ( $ data ) ) ; } } if ( $ this -> browser -> getClient ( ) instanceof MultiCurl ) { $ this -> browser -> getClient ( ) -> flush ( ) ; } foreach ( $ this -> responses as $ response ) { $ message = json_decode ( $ response -> getContent ( ) ) ; if ( $ message === null || $ message -> success == 0 || $ message -> failure > 0 ) { if ( $ message == null ) { $ this -> logger -> error ( $ response -> getContent ( ) ) ; } else { foreach ( $ message -> results as $ result ) { if ( isset ( $ result -> error ) ) { $ this -> logger -> error ( $ result -> error ) ; } } } return false ; } } return true ; }
Sends the data to the given registration IDs via the GCM server
1,612
public function unpack ( $ data ) { $ token = unpack ( "N1timestamp/n1length/H*token" , $ data ) ; $ this -> timestamp = $ token [ "timestamp" ] ; $ this -> tokenLength = $ token [ "length" ] ; $ this -> uuid = $ token [ "token" ] ; return $ this ; }
Unpacks the APNS data into the required fields
1,613
protected function setAndroidConfig ( array $ config ) { $ this -> container -> setParameter ( "rms_push_notifications.android.enabled" , true ) ; $ this -> container -> setParameter ( "rms_push_notifications.android.c2dm.enabled" , true ) ; $ username = $ config [ "android" ] [ "username" ] ; $ password = $ config [ "android" ] [ "password" ] ; $ source = $ config [ "android" ] [ "source" ] ; $ timeout = $ config [ "android" ] [ "timeout" ] ; if ( isset ( $ config [ "android" ] [ "c2dm" ] ) ) { $ username = $ config [ "android" ] [ "c2dm" ] [ "username" ] ; $ password = $ config [ "android" ] [ "c2dm" ] [ "password" ] ; $ source = $ config [ "android" ] [ "c2dm" ] [ "source" ] ; } $ this -> container -> setParameter ( "rms_push_notifications.android.timeout" , $ timeout ) ; $ this -> container -> setParameter ( "rms_push_notifications.android.c2dm.username" , $ username ) ; $ this -> container -> setParameter ( "rms_push_notifications.android.c2dm.password" , $ password ) ; $ this -> container -> setParameter ( "rms_push_notifications.android.c2dm.source" , $ source ) ; $ this -> container -> setParameter ( "rms_push_notifications.android.gcm.enabled" , isset ( $ config [ "android" ] [ "gcm" ] ) ) ; if ( isset ( $ config [ "android" ] [ "gcm" ] ) ) { $ this -> container -> setParameter ( "rms_push_notifications.android.gcm.api_key" , $ config [ "android" ] [ "gcm" ] [ "api_key" ] ) ; $ this -> container -> setParameter ( "rms_push_notifications.android.gcm.use_multi_curl" , $ config [ "android" ] [ "gcm" ] [ "use_multi_curl" ] ) ; $ this -> container -> setParameter ( 'rms_push_notifications.android.gcm.dry_run' , $ config [ "android" ] [ "gcm" ] [ "dry_run" ] ) ; } }
Sets Android config into container
1,614
protected function setAppleConfig ( array $ config , $ os ) { $ supportedAppleOS = array ( "mac" , "ios" ) ; if ( ! in_array ( $ os , $ supportedAppleOS , true ) ) { throw new \ RuntimeException ( sprintf ( 'This Apple OS "%s" is not supported' , $ os ) ) ; } $ pemFile = null ; if ( isset ( $ config [ $ os ] [ "pem" ] ) ) { if ( realpath ( $ config [ $ os ] [ "pem" ] ) ) { $ pemFile = $ config [ $ os ] [ "pem" ] ; } elseif ( realpath ( $ this -> kernelRootDir . DIRECTORY_SEPARATOR . $ config [ $ os ] [ "pem" ] ) ) { $ pemFile = $ this -> kernelRootDir . DIRECTORY_SEPARATOR . $ config [ $ os ] [ "pem" ] ; } else { throw new \ RuntimeException ( sprintf ( 'Pem file "%s" not found.' , $ config [ $ os ] [ "pem" ] ) ) ; } } if ( $ config [ $ os ] [ 'json_unescaped_unicode' ] ) { if ( ! version_compare ( PHP_VERSION , '5.4.0' , '>=' ) ) { throw new \ LogicException ( sprintf ( 'Can\'t use JSON_UNESCAPED_UNICODE option. This option can use only PHP Version >= 5.4.0. Your version: %s' , PHP_VERSION ) ) ; } } $ this -> container -> setParameter ( sprintf ( 'rms_push_notifications.%s.enabled' , $ os ) , true ) ; $ this -> container -> setParameter ( sprintf ( 'rms_push_notifications.%s.timeout' , $ os ) , $ config [ $ os ] [ "timeout" ] ) ; $ this -> container -> setParameter ( sprintf ( 'rms_push_notifications.%s.sandbox' , $ os ) , $ config [ $ os ] [ "sandbox" ] ) ; $ this -> container -> setParameter ( sprintf ( 'rms_push_notifications.%s.pem' , $ os ) , $ pemFile ) ; $ this -> container -> setParameter ( sprintf ( 'rms_push_notifications.%s.passphrase' , $ os ) , $ config [ $ os ] [ "passphrase" ] ) ; $ this -> container -> setParameter ( sprintf ( 'rms_push_notifications.%s.json_unescaped_unicode' , $ os ) , ( bool ) $ config [ $ os ] [ 'json_unescaped_unicode' ] ) ; }
Sets Apple config into container
1,615
protected function setBlackberryConfig ( array $ config ) { $ this -> container -> setParameter ( "rms_push_notifications.blackberry.enabled" , true ) ; $ this -> container -> setParameter ( "rms_push_notifications.blackberry.timeout" , $ config [ "blackberry" ] [ "timeout" ] ) ; $ this -> container -> setParameter ( "rms_push_notifications.blackberry.evaluation" , $ config [ "blackberry" ] [ "evaluation" ] ) ; $ this -> container -> setParameter ( "rms_push_notifications.blackberry.app_id" , $ config [ "blackberry" ] [ "app_id" ] ) ; $ this -> container -> setParameter ( "rms_push_notifications.blackberry.password" , $ config [ "blackberry" ] [ "password" ] ) ; }
Sets Blackberry config into container
1,616
public function send ( MessageInterface $ message ) { if ( ! $ message instanceof AndroidMessage ) { throw new InvalidMessageTypeException ( sprintf ( "Message type '%s' not supported by C2DM" , get_class ( $ message ) ) ) ; } if ( $ this -> getAuthToken ( ) ) { $ headers [ ] = "Authorization: GoogleLogin auth=" . $ this -> authToken ; $ data = $ message -> getMessageBody ( ) ; $ buzz = new Browser ( ) ; $ buzz -> getClient ( ) -> setVerifyPeer ( false ) ; $ buzz -> getClient ( ) -> setTimeout ( $ this -> timeout ) ; $ response = $ buzz -> post ( "https://android.apis.google.com/c2dm/send" , $ headers , http_build_query ( $ data ) ) ; return preg_match ( "/^id=/" , $ response -> getContent ( ) ) > 0 ; } return false ; }
Sends a C2DM message This assumes that a valid auth token can be obtained
1,617
protected function getAuthToken ( ) { $ data = array ( "Email" => $ this -> username , "Passwd" => $ this -> password , "accountType" => "HOSTED_OR_GOOGLE" , "source" => $ this -> source , "service" => "ac2dm" ) ; $ buzz = new Browser ( ) ; $ buzz -> getClient ( ) -> setVerifyPeer ( false ) ; $ buzz -> getClient ( ) -> setTimeout ( $ this -> timeout ) ; $ response = $ buzz -> post ( "https://www.google.com/accounts/ClientLogin" , array ( ) , http_build_query ( $ data ) ) ; if ( $ response -> getStatusCode ( ) !== 200 ) { return false ; } preg_match ( "/Auth=([a-z0-9_\-]+)/i" , $ response -> getContent ( ) , $ matches ) ; $ this -> authToken = $ matches [ 1 ] ; return true ; }
Gets a valid authentication token
1,618
public function process ( ContainerBuilder $ container ) { $ service = $ container -> getDefinition ( "rms_push_notifications" ) ; foreach ( $ container -> findTaggedServiceIds ( "rms_push_notifications.handler" ) as $ id => $ attributes ) { if ( ! isset ( $ attributes [ 0 ] [ "osType" ] ) ) { throw new \ LogicException ( "Handler {$id} requires an osType attribute" ) ; } $ definition = $ container -> getDefinition ( $ id ) ; try { $ class = $ definition -> getClass ( ) ; if ( strpos ( $ class , '%' ) === 0 ) { $ class = $ container -> getParameter ( trim ( $ class , '%' ) ) ; } $ refClass = new \ ReflectionClass ( $ class ) ; } catch ( \ ReflectionException $ ref ) { throw new \ RuntimeException ( sprintf ( 'Can\'t compile notification handler by service id "%s".' , $ id ) , 0 , $ ref ) ; } catch ( ParameterNotFoundException $ paramNotFound ) { throw new \ RuntimeException ( sprintf ( 'Can\'t compile notification handler by service id "%s".' , $ id ) , 0 , $ paramNotFound ) ; } $ requiredInterface = 'RMS\\PushNotificationsBundle\\Service\\OS\\OSNotificationServiceInterface' ; if ( ! $ refClass -> implementsInterface ( $ requiredInterface ) ) { throw new \ UnexpectedValueException ( sprintf ( 'Notification service "%s" by id "%s" must be implements "%s" interface!' , $ refClass -> getName ( ) , $ id , $ requiredInterface ) ) ; } $ service -> addMethodCall ( "addHandler" , array ( $ attributes [ 0 ] [ "osType" ] , new Reference ( $ id ) ) ) ; } }
Processes any handlers tagged accordingly
1,619
public function setData ( $ data ) { if ( ! is_array ( $ data ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Messages custom data must be array, "%s" given.' , gettype ( $ data ) ) ) ; } if ( array_key_exists ( "aps" , $ data ) ) { unset ( $ data [ "aps" ] ) ; } foreach ( $ data as $ key => $ value ) { $ this -> addCustomData ( $ key , $ value ) ; } return $ this ; }
Sets any custom data for the APS body
1,620
public function addCustomData ( $ key , $ value ) { if ( $ key == 'aps' ) { throw new \ LogicException ( 'Can\'t replace "aps" data. Please call to setMessage, if your want replace message text.' ) ; } if ( is_object ( $ value ) ) { if ( interface_exists ( 'JsonSerializable' ) && ! $ value instanceof \ stdClass && ! $ value instanceof \ JsonSerializable ) { throw new \ InvalidArgumentException ( sprintf ( 'Object %s::%s must be implements JsonSerializable interface for next serialize data.' , get_class ( $ value ) , spl_object_hash ( $ value ) ) ) ; } } $ this -> customData [ $ key ] = $ value ; return $ this ; }
Add custom data
1,621
public function getMessageBody ( ) { $ payloadBody = $ this -> apsBody ; if ( ! empty ( $ this -> customData ) ) { $ payloadBody = array_merge ( $ payloadBody , $ this -> customData ) ; } return $ payloadBody ; }
Gets the full message body to send to APN
1,622
public function send ( MessageInterface $ message ) { if ( ! $ this -> supports ( $ message -> getTargetOS ( ) ) ) { throw new \ RuntimeException ( "OS type {$message->getTargetOS()} not supported" ) ; } return $ this -> handlers [ $ message -> getTargetOS ( ) ] -> send ( $ message ) ; }
Sends a message to a device identified by the OS and the supplied device token
1,623
public function addHandler ( $ osType , $ service ) { if ( ! isset ( $ this -> handlers [ $ osType ] ) ) { $ this -> handlers [ $ osType ] = $ service ; } }
Adds a handler
1,624
public function getResponses ( $ osType ) { if ( ! isset ( $ this -> handlers [ $ osType ] ) ) { throw new \ RuntimeException ( "OS type {$osType} not supported" ) ; } if ( ! method_exists ( $ this -> handlers [ $ osType ] , 'getResponses' ) ) { throw new \ RuntimeException ( "Handler for OS type {$osType} not supported getResponses() method" ) ; } return $ this -> handlers [ $ osType ] -> getResponses ( ) ; }
Get responses from handler
1,625
public function setAPNSPemAsString ( $ pemContent , $ passphrase ) { if ( isset ( $ this -> handlers [ Types :: OS_IOS ] ) && $ this -> handlers [ Types :: OS_IOS ] instanceof AppleNotification ) { $ appleNotification = $ this -> handlers [ Types :: OS_IOS ] ; $ appleNotification -> setPemAsString ( $ pemContent , $ passphrase ) ; } }
Set Apple Push Notification Service pem as string . Service won t use pem file passed by config anymore .
1,626
public function getMessageBody ( ) { $ data = array ( "registration_id" => $ this -> identifier , "collapse_key" => $ this -> collapseKey , "data.message" => $ this -> message , ) ; if ( ! empty ( $ this -> data ) ) { $ data = array_merge ( $ data , $ this -> data ) ; } return $ data ; }
Gets the message body to send This is primarily used in C2DM
1,627
public function send ( MessageInterface $ message ) { if ( ! $ message instanceof AppleMessage ) { throw new InvalidMessageTypeException ( sprintf ( "Message type '%s' not supported by APN" , get_class ( $ message ) ) ) ; } $ apnURL = "ssl://gateway.push.apple.com:2195" ; if ( $ this -> useSandbox ) { $ apnURL = "ssl://gateway.sandbox.push.apple.com:2195" ; } $ messageId = ++ $ this -> lastMessageId ; if ( $ message -> isMdmMessage ( ) ) { if ( $ message -> getToken ( ) == '' ) { throw new InvalidMessageTypeException ( sprintf ( "Message type '%s' is a MDM message but 'token' is missing" , get_class ( $ message ) ) ) ; } if ( $ message -> getPushMagicToken ( ) == '' ) { throw new InvalidMessageTypeException ( sprintf ( "Message type '%s' is a MDM message but 'pushMagicToken' is missing" , get_class ( $ message ) ) ) ; } $ this -> messages [ $ messageId ] = $ this -> createMdmPayload ( $ message -> getToken ( ) , $ message -> getPushMagicToken ( ) ) ; } else { $ this -> messages [ $ messageId ] = $ this -> createPayload ( $ messageId , $ message -> getExpiry ( ) , $ message -> getDeviceIdentifier ( ) , $ message -> getMessageBody ( ) ) ; } $ errors = $ this -> sendMessages ( $ messageId , $ apnURL ) ; return ! $ errors ; }
Send a MDM or notification message
1,628
protected function sendMessages ( $ firstMessageId , $ apnURL ) { $ errors = array ( ) ; $ messagesCount = count ( $ this -> messages ) ; for ( $ currentMessageId = $ firstMessageId ; $ currentMessageId < $ messagesCount ; $ currentMessageId ++ ) { $ result = $ this -> writeApnStream ( $ apnURL , $ this -> messages [ $ currentMessageId ] ) ; if ( is_array ( $ result ) ) { if ( $ result [ 'status' ] === self :: APNS_SHUTDOWN_CODE ) { $ this -> closeApnStream ( $ apnURL ) ; } $ this -> responses [ ] = $ result ; $ this -> sendMessages ( $ result [ 'identifier' ] + 1 , $ apnURL ) ; $ errors [ ] = $ result ; if ( $ this -> logger ) { $ this -> logger -> error ( json_encode ( $ result ) ) ; } } else { $ this -> responses [ ] = true ; } } return $ errors ; }
Send all notification messages starting from the given ID
1,629
protected function writeApnStream ( $ apnURL , $ payload ) { $ fp = $ this -> getApnStream ( $ apnURL ) ; $ response = ( strlen ( $ payload ) === @ fwrite ( $ fp , $ payload , strlen ( $ payload ) ) ) ; $ readStreams = array ( $ fp ) ; $ null = NULL ; $ streamsReadyToRead = @ stream_select ( $ readStreams , $ null , $ null , 1 , 0 ) ; if ( $ streamsReadyToRead > 0 ) { $ response = @ unpack ( "Ccommand/Cstatus/Nidentifier" , fread ( $ fp , 6 ) ) ; $ this -> closeApnStream ( $ apnURL ) ; } return $ response ; }
Write data to the apn stream that is associated with the given apn URL
1,630
protected function getApnStream ( $ apnURL ) { if ( ! isset ( $ this -> apnStreams [ $ apnURL ] ) ) { $ ctx = $ this -> getStreamContext ( ) ; $ this -> apnStreams [ $ apnURL ] = stream_socket_client ( $ apnURL , $ err , $ errstr , $ this -> timeout , STREAM_CLIENT_CONNECT , $ ctx ) ; if ( ! $ this -> apnStreams [ $ apnURL ] ) { throw new \ RuntimeException ( "Couldn't connect to APN server. Error no $err: $errstr" ) ; } if ( function_exists ( "stream_set_read_buffer" ) ) { stream_set_read_buffer ( $ this -> apnStreams [ $ apnURL ] , 6 ) ; } stream_set_write_buffer ( $ this -> apnStreams [ $ apnURL ] , 0 ) ; stream_set_blocking ( $ this -> apnStreams [ $ apnURL ] , 0 ) ; } return $ this -> apnStreams [ $ apnURL ] ; }
Get an apn stream associated with the given apn URL create one if necessary
1,631
protected function closeApnStream ( $ apnURL ) { if ( isset ( $ this -> apnStreams [ $ apnURL ] ) ) { fclose ( $ this -> apnStreams [ $ apnURL ] ) ; unset ( $ this -> apnStreams [ $ apnURL ] ) ; } }
Close the apn stream associated with the given apn URL
1,632
protected function createPayload ( $ messageId , $ expiry , $ token , $ message ) { if ( $ this -> jsonUnescapedUnicode ) { if ( ! version_compare ( PHP_VERSION , '5.4.0' , '>=' ) ) { throw new \ LogicException ( sprintf ( 'Can\'t use JSON_UNESCAPED_UNICODE option on PHP %s. Support PHP >= 5.4.0' , PHP_VERSION ) ) ; } $ encoding = mb_detect_encoding ( $ message [ 'aps' ] [ 'alert' ] ) ; if ( $ encoding != 'UTF-8' && $ encoding != 'ASCII' ) { throw new \ InvalidArgumentException ( sprintf ( 'Message must be UTF-8 encoding, "%s" given.' , mb_detect_encoding ( $ message [ 'aps' ] [ 'alert' ] ) ) ) ; } $ jsonBody = json_encode ( $ message , JSON_UNESCAPED_UNICODE ) ; } else { $ jsonBody = json_encode ( $ message ) ; } $ token = preg_replace ( "/[^0-9A-Fa-f]/" , "" , $ token ) ; $ payload = chr ( 1 ) . pack ( "N" , $ messageId ) . pack ( "N" , $ expiry ) . pack ( "n" , 32 ) . pack ( "H*" , $ token ) . pack ( "n" , strlen ( $ jsonBody ) ) . $ jsonBody ; return $ payload ; }
Creates the full payload for the notification
1,633
public function createMdmPayload ( $ token , $ magicPushToken ) { $ jsonPayload = json_encode ( array ( 'mdm' => $ magicPushToken ) ) ; $ payload = chr ( 0 ) . chr ( 0 ) . chr ( 32 ) . base64_decode ( $ token ) . chr ( 0 ) . chr ( strlen ( $ jsonPayload ) ) . $ jsonPayload ; return $ payload ; }
Creates a MDM payload
1,634
private function removeCachedPemFile ( ) { $ fs = new Filesystem ( ) ; $ filename = $ this -> cachedir . self :: APNS_CERTIFICATE_FILE ; if ( $ fs -> exists ( dirname ( $ filename ) ) ) { $ fs -> remove ( dirname ( $ filename ) ) ; } }
Remove cache pem file
1,635
public function getDeviceUUIDs ( ) { if ( ! strlen ( $ this -> pem ) ) { throw new \ RuntimeException ( "PEM not provided" ) ; } $ feedbackURL = "ssl://feedback.push.apple.com:2196" ; if ( $ this -> sandbox ) { $ feedbackURL = "ssl://feedback.sandbox.push.apple.com:2196" ; } $ data = "" ; $ ctx = $ this -> getStreamContext ( ) ; $ fp = stream_socket_client ( $ feedbackURL , $ err , $ errstr , $ this -> timeout , STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT , $ ctx ) ; if ( ! $ fp ) { throw new \ RuntimeException ( "Couldn't connect to APNS Feedback service. Error no $err: $errstr" ) ; } while ( ! feof ( $ fp ) ) { $ data .= fread ( $ fp , 4096 ) ; } fclose ( $ fp ) ; if ( ! strlen ( $ data ) ) { return array ( ) ; } $ feedbacks = array ( ) ; $ items = str_split ( $ data , 38 ) ; foreach ( $ items as $ item ) { $ feedback = new Feedback ( ) ; $ feedbacks [ ] = $ feedback -> unpack ( $ item ) ; } return $ feedbacks ; }
Gets an array of device UUID unregistration details from the APN feedback service
1,636
public static function decodeCredential ( string $ json , string $ responseType ) : PublicKeyCredential { $ decoded = json_decode ( $ json , true , 10 ) ; if ( $ decoded === false ) { throw new ParseException ( 'Failed to decode PublicKeyCredential Json' ) ; } if ( ( $ decoded [ 'type' ] ?? null ) !== PublicKeyCredentialType :: PUBLIC_KEY ) { throw new ParseException ( "Expecting type 'public-key'" ) ; } if ( empty ( $ decoded [ 'id' ] ) ) { throw new ParseException ( 'Missing id in json data' ) ; } $ id = $ decoded [ 'id' ] ; if ( ! is_string ( $ id ) ) { throw new ParseException ( 'Id in json data should be string' ) ; } $ rawId = Base64UrlEncoding :: decode ( $ id ) ; $ responseData = $ decoded [ 'response' ] ?? null ; if ( ! is_array ( $ responseData ) ) { throw new ParseException ( 'Expecting array data for response' ) ; } $ response = self :: decodeResponse ( $ responseData , $ responseType ) ; return new PublicKeyCredential ( new ByteBuffer ( $ rawId ) , $ response ) ; }
Parses a JSON string containing a credential returned from the JS credential API s credentials . get or credentials . create . The JSOn structure matches the PublicKeyCredential interface from the WebAuthn specifications closely but since it contains ArrayBuffers it cannot be directly converted to a JSON equivalent . Fields that are ArrayBuffers are assumed to be base64url encoded .
1,637
private function compactIntegerBuffer ( ByteBuffer $ buffer ) { $ length = $ buffer -> getLength ( ) ; $ raw = $ buffer -> getBinaryString ( ) ; for ( $ i = 0 ; $ i < ( $ length - 1 ) ; $ i ++ ) { if ( ord ( $ raw [ $ i ] ) !== 0 ) { break ; } } if ( $ i !== 0 ) { return new ByteBuffer ( \ substr ( $ raw , $ i ) ) ; } return $ buffer ; }
Removes all leading zero bytes from a ByteBuffer but keeps one zero byte if it is the only byte left and the original buffer did not have zero length .
1,638
public function run ( ) { $ lines = $ this -> httpAdapter -> get ( Update :: PUBLIC_SUFFIX_LIST_URL ) ; $ parser = new Parser ( $ lines ) ; $ suffixes = $ parser -> parse ( ) ; $ handle = @ fopen ( $ this -> outputFileName , 'w+' ) ; if ( $ handle === false ) { throw new Exceptions \ IOException ( error_get_last ( ) [ 'message' ] ) ; } if ( ! flock ( $ handle , LOCK_EX ) ) { throw new Exceptions \ IOException ( sprintf ( 'Cannot obtain lock to output file (%s)' , $ this -> outputFileName ) ) ; } $ suffixFile = '<?php' . PHP_EOL . 'return ' . var_export ( $ suffixes , true ) . ';' ; $ writtenBytes = fwrite ( $ handle , $ suffixFile ) ; if ( $ writtenBytes === false || $ writtenBytes !== strlen ( $ suffixFile ) ) { throw new Exceptions \ IOException ( sprintf ( 'Write to output file (%s) failed' , $ this -> outputFileName ) ) ; } flock ( $ handle , LOCK_UN ) ; fclose ( $ handle ) ; }
Fetches actual Public Suffix List and writes obtained suffixes to target file .
1,639
public function parse ( ) { $ suffixes = [ ] ; foreach ( $ this -> lines as $ line ) { if ( Str :: startsWith ( $ line , Parser :: PRIVATE_DOMAINS_STRING ) ) { $ this -> isICANNSuffix = false ; continue ; } if ( Str :: startsWith ( $ line , Parser :: COMMENT_STRING_START ) ) { continue ; } $ line = explode ( ' ' , trim ( $ line ) ) [ 0 ] ; if ( Str :: length ( $ line ) === 0 ) { continue ; } $ suffixes [ $ line ] = $ this -> isICANNSuffix ? Store :: TYPE_ICANN : Store :: TYPE_PRIVATE ; } if ( count ( $ suffixes ) === 0 ) { throw new ParserException ( 'Input array of lines does not have any valid suffix, check input' ) ; } return $ suffixes ; }
Method that parses submitted strings and returns array from valid suffixes .
1,640
public function getType ( $ suffix ) { if ( ! array_key_exists ( $ suffix , $ this -> suffixes ) ) { throw new StoreException ( sprintf ( 'Provided suffix (%s) does not exists in database, check existence of entry with isExists() method ' . 'before' , $ suffix ) ) ; } return $ this -> suffixes [ $ suffix ] ; }
Checks type of suffix entry . Returns true if suffix is ICANN TLD zone .
1,641
public function register ( ) { if ( $ this -> isLumen ( ) ) { $ this -> app -> configure ( 'laravel-facebook-sdk' ) ; } $ this -> mergeConfigFrom ( __DIR__ . '/../config/laravel-facebook-sdk.php' , 'laravel-facebook-sdk' ) ; $ this -> app -> bind ( 'SammyK\LaravelFacebookSdk\LaravelFacebookSdk' , function ( $ app ) { $ config = $ app [ 'config' ] -> get ( 'laravel-facebook-sdk.facebook_config' ) ; if ( ! isset ( $ config [ 'persistent_data_handler' ] ) && isset ( $ app [ 'session.store' ] ) ) { $ config [ 'persistent_data_handler' ] = new LaravelPersistentDataHandler ( $ app [ 'session.store' ] ) ; } if ( ! isset ( $ config [ 'url_detection_handler' ] ) ) { if ( $ this -> isLumen ( ) ) { $ config [ 'url_detection_handler' ] = new LumenUrlDetectionHandler ( $ app [ 'url' ] ) ; } else { $ config [ 'url_detection_handler' ] = new LaravelUrlDetectionHandler ( $ app [ 'url' ] ) ; } } return new LaravelFacebookSdk ( $ app [ 'config' ] , $ app [ 'url' ] , $ config ) ; } ) ; }
Register the service providers .
1,642
public static function createOrUpdateGraphNode ( $ data ) { if ( $ data instanceof GraphObject || $ data instanceof GraphNode ) { $ data = array_dot ( $ data -> asArray ( ) ) ; } $ data = static :: convertGraphNodeDateTimesToStrings ( $ data ) ; if ( ! isset ( $ data [ 'id' ] ) ) { throw new \ InvalidArgumentException ( 'Graph node id is missing' ) ; } $ attributes = [ static :: getGraphNodeKeyName ( ) => $ data [ 'id' ] ] ; $ graph_node = static :: firstOrNewGraphNode ( $ attributes ) ; static :: mapGraphNodeFieldNamesToDatabaseColumnNames ( $ graph_node , $ data ) ; $ graph_node -> save ( ) ; return $ graph_node ; }
Inserts or updates the Graph node to the local database
1,643
public static function fieldToColumnName ( $ field ) { $ model_name = get_class ( new static ( ) ) ; if ( property_exists ( $ model_name , 'graph_node_field_aliases' ) && isset ( static :: $ graph_node_field_aliases [ $ field ] ) ) { return static :: $ graph_node_field_aliases [ $ field ] ; } return $ field ; }
Convert a Graph node field name to a database column name
1,644
public static function mapGraphNodeFieldNamesToDatabaseColumnNames ( Model $ object , array $ fields ) { foreach ( $ fields as $ field => $ value ) { if ( static :: graphNodeFieldIsWhiteListed ( static :: fieldToColumnName ( $ field ) ) ) { $ object -> { static :: fieldToColumnName ( $ field ) } = $ value ; } } }
Map Graph - node field names to local database column name
1,645
private static function convertGraphNodeDateTimesToStrings ( array $ data ) { $ date_format = 'Y-m-d H:i:s' ; $ model_name = get_class ( new static ( ) ) ; if ( property_exists ( $ model_name , 'graph_node_date_time_to_string_format' ) ) { $ date_format = static :: $ graph_node_date_time_to_string_format ; } foreach ( $ data as $ key => $ value ) { if ( $ value instanceof \ DateTime ) { $ data [ $ key ] = $ value -> format ( $ date_format ) ; } } return $ data ; }
Convert instances of \ DateTime to string
1,646
private static function graphNodeFieldIsWhiteListed ( $ key ) { $ model_name = get_class ( new static ( ) ) ; if ( ! property_exists ( $ model_name , 'graph_node_fillable_fields' ) ) { return true ; } return in_array ( $ key , static :: $ graph_node_fillable_fields ) ; }
Check a key for fillableness
1,647
public function getLoginUrl ( array $ scope = [ ] , $ callback_url = '' ) { $ scope = $ this -> getScope ( $ scope ) ; $ callback_url = $ this -> getCallbackUrl ( $ callback_url ) ; return $ this -> getRedirectLoginHelper ( ) -> getLoginUrl ( $ callback_url , $ scope ) ; }
Generate an OAuth 2 . 0 authorization URL for authentication .
1,648
public function getReRequestUrl ( array $ scope , $ callback_url = '' ) { $ scope = $ this -> getScope ( $ scope ) ; $ callback_url = $ this -> getCallbackUrl ( $ callback_url ) ; return $ this -> getRedirectLoginHelper ( ) -> getReRequestUrl ( $ callback_url , $ scope ) ; }
Generate a re - request authorization URL .
1,649
public function getReAuthenticationUrl ( array $ scope = [ ] , $ callback_url = '' ) { $ scope = $ this -> getScope ( $ scope ) ; $ callback_url = $ this -> getCallbackUrl ( $ callback_url ) ; return $ this -> getRedirectLoginHelper ( ) -> getReAuthenticationUrl ( $ callback_url , $ scope ) ; }
Generate a re - authentication authorization URL .
1,650
public function getAccessTokenFromRedirect ( $ callback_url = '' ) { $ callback_url = $ this -> getCallbackUrl ( $ callback_url ) ; return $ this -> getRedirectLoginHelper ( ) -> getAccessToken ( $ callback_url ) ; }
Get an access token from a redirect .
1,651
private function getCallbackUrl ( $ callback_url ) { $ callback_url = $ callback_url ? : $ this -> config_handler -> get ( 'laravel-facebook-sdk.default_redirect_uri' ) ; return $ this -> url -> to ( $ callback_url ) ; }
Get the fallback callback redirect URL if none provided .
1,652
public function initialize ( float $ creditsPerNanosecond , float $ maxBalance ) { $ this -> creditsPerNanosecond = $ creditsPerNanosecond ; $ this -> maxBalance = $ maxBalance ; }
Initializes limiter costs and boundaries
1,653
private function saveState ( $ lastTick , $ balance ) { $ this -> lastTick -> set ( $ lastTick ) ; $ this -> balance -> set ( $ balance ) ; $ this -> cache -> saveDeferred ( $ this -> lastTick ) ; $ this -> cache -> saveDeferred ( $ this -> balance ) ; $ this -> cache -> commit ( ) ; }
Method saves last tick and current balance into cache
1,654
protected function microTime ( $ time ) : int { if ( $ time === null ) { return $ this -> timestampMicro ( ) ; } if ( $ time instanceof \ DateTimeInterface ) { return ( int ) round ( $ time -> format ( 'U.u' ) * 1000000 , 0 ) ; } if ( is_int ( $ time ) ) { return $ time ; } if ( is_float ( $ time ) ) { return ( int ) round ( $ time * 1000000 , 0 ) ; } throw new \ InvalidArgumentException ( sprintf ( 'Time should be one of the types int|float|DateTime|null, got %s.' , gettype ( $ time ) ) ) ; }
Converts time to microtime int - int represents microseconds - float represents seconds
1,655
public function isSampled ( string $ traceId = '' , string $ operation = '' ) { return [ $ this -> rateLimiter -> checkCredit ( 1.0 ) , $ this -> tags ] ; }
Whether or not the new trace should be sampled .
1,656
public function write ( $ buf ) { if ( ! $ this -> isOpen ( ) ) { throw new TTransportException ( 'transport is closed' ) ; } $ ok = @ socket_write ( $ this -> socket , $ buf ) ; if ( $ ok === false ) { throw new TTransportException ( 'socket_write failed' ) ; } }
Writes the given data out .
1,657
private function spanContextToString ( $ traceId , $ spanId , $ parentId , $ flags ) { $ parentId = $ parentId ?? 0 ; return sprintf ( '%x:%x:%x:%x' , $ traceId , $ spanId , $ parentId , $ flags ) ; }
Store a span context to a string .
1,658
private function spanContextFromString ( $ value ) : array { $ parts = explode ( ':' , $ value ) ; if ( count ( $ parts ) != 4 ) { throw new Exception ( 'Malformed tracer state string.' ) ; } return [ CodecUtility :: hexToInt64 ( $ parts [ 0 ] ) , CodecUtility :: hexToInt64 ( $ parts [ 1 ] ) , CodecUtility :: hexToInt64 ( $ parts [ 2 ] ) , $ parts [ 3 ] , ] ; }
Create a span context from a string .
1,659
private function send ( array $ thrifts ) { foreach ( $ this -> chunkSplit ( $ thrifts ) as $ chunk ) { $ this -> client -> emitZipkinBatch ( $ chunk ) ; } }
Emits the thrift - objects .
1,660
private function makePeerAddressTag ( string $ key , Endpoint $ host ) : BinaryAnnotation { return new BinaryAnnotation ( [ "key" => $ key , "value" => '0x01' , "annotation_type" => AnnotationType :: BOOL , "host" => $ host , ] ) ; }
They are modeled as Boolean type with 0x01 as the value .
1,661
private function chunkSplit ( array $ thrifts ) : array { $ actualBufferSize = $ this -> zipkinBatchOverheadLength ; $ chunkId = 0 ; $ chunks = [ ] ; foreach ( $ thrifts as $ thrift ) { $ spanBufferLength = $ this -> getBufferLength ( $ thrift ) ; if ( ! empty ( $ chunks [ $ chunkId ] ) && ( $ actualBufferSize + $ spanBufferLength ) > $ this -> maxBufferLength ) { ++ $ chunkId ; $ actualBufferSize = $ this -> zipkinBatchOverheadLength ; } if ( ! isset ( $ chunks [ $ chunkId ] ) ) { $ chunks [ $ chunkId ] = [ ] ; } $ chunks [ $ chunkId ] [ ] = $ thrift ; $ actualBufferSize += $ spanBufferLength ; } return $ chunks ; }
Splits an array of thrift - objects into several chunks when the buffer limit has been reached .
1,662
private function getBufferLength ( $ thrift ) : int { $ memoryBuffer = new TMemoryBuffer ( ) ; $ thrift -> write ( new TCompactProtocol ( $ memoryBuffer ) ) ; return $ memoryBuffer -> available ( ) ; }
Returns the length of a thrift - object .
1,663
public function getAll ( ) { if ( is_null ( $ this -> components ) ) { $ base_path = $ this -> getBaseComponentPath ( ) ; $ filter = function ( Extension $ module ) use ( $ base_path ) { return strpos ( $ module -> getPath ( ) , $ base_path ) === 0 ; } ; $ this -> components = array_filter ( $ this -> discovery -> scan ( 'module' ) , $ filter ) ; } return $ this -> components ; }
Returns extension objects for all WxT components .
1,664
public function getMainComponents ( ) { $ base_path = $ this -> getBaseComponentPath ( ) ; $ filter = function ( Extension $ module ) use ( $ base_path ) { return dirname ( $ module -> getPath ( ) ) == $ base_path ; } ; return array_filter ( $ this -> getAll ( ) , $ filter ) ; }
Returns extension objects for all main WxT components .
1,665
public function getSubComponents ( ) { $ base_path = $ this -> getBaseComponentPath ( ) ; $ filter = function ( Extension $ module ) use ( $ base_path ) { return strlen ( dirname ( $ module -> getPath ( ) ) ) > strlen ( $ base_path ) ; } ; return array_filter ( $ this -> getAll ( ) , $ filter ) ; }
Returns extension object for all WxT sub - components .
1,666
private function replaceToken ( $ match , $ migrate_executable , $ row , $ destination_property ) { $ tmp = str_replace ( "[" , "" , $ match [ 2 ] ) ; $ tmp = str_replace ( "]" , "" , $ tmp ) ; $ tmp = substr ( $ tmp , 15 ) ; $ uuid = $ tmp ; $ output = '' ; try { if ( ! is_string ( $ uuid ) ) { throw new MigrateException ( 'Unable to grab UUID Link' ) ; } Database :: setActiveConnection ( 'source_migration' ) ; $ db = Database :: getConnection ( ) ; $ query = $ db -> select ( 'node' , 'n' ) -> fields ( 'n' ) -> condition ( 'n.uuid' , $ uuid ) ; $ nid = $ query -> execute ( ) -> fetchCol ( ) ; Database :: setActiveConnection ( ) ; $ nid = $ this -> migrationPlugin -> transform ( $ nid [ 0 ] , $ migrate_executable , $ row , $ destination_property ) ; if ( is_array ( $ nid ) ) { $ nid = current ( $ nid ) ; } $ node = Node :: load ( $ nid ) ; if ( ! $ node ) { throw new MigrateException ( 'Could not load node object' ) ; } $ attrBefore = ! empty ( $ match [ 1 ] ) ? $ match [ 1 ] : '' ; $ attrAfter = ! empty ( $ match [ 3 ] ) ? $ match [ 3 ] : '' ; $ output = ' <a data-entity-substitution="canonical" data-entity-type="node" data-entity-uuid="' . $ node -> uuid ( ) . '" href="/node/' . $ nid . '" ' . $ attrAfter . ' ' . $ attrBefore . '>' ; } catch ( Exception $ e ) { $ msg = t ( 'Unable to render link from %link. Error: %error' , [ '%link' => $ uuid , '%error' => $ e -> getMessage ( ) ] ) ; \ Drupal :: logger ( 'Migration' ) -> error ( $ msg ) ; return '' ; } return $ output ; }
Replace callback to convert a Drupal 7 UUID link into a Drupal 8 UUID Link .
1,667
public function on404 ( ) { $ response = ' <div class="box"> <div class="row"> <div class="col-xs-3 col-sm-2 col-md-2 text-center mrgn-tp-md"> <span class="glyphicon glyphicon-warning-sign glyphicon-error"></span> </div> <div class="col-xs-9 col-sm-10 col-md-10"> <h2 class="mrgn-tp-md">' . $ this -> t ( 'We couldn\'t find that Web page' ) . '</h2> <p class="pagetag"><strong>' . $ this -> t ( 'Error 404' ) . '</strong></p> </div> </div> <p class="mrgn-tp-md">' . $ this -> t ( 'We\'re sorry you ended up here. Sometimes a page gets moved or deleted.' ) . '</p> </div>' ; $ block_id = $ this -> blockContentStorage -> loadByProperties ( [ 'info' => '404' , 'type' => 'basic' , ] ) ; if ( ! empty ( $ block_id ) ) { $ response = $ this -> blockViewBuilder -> view ( reset ( $ block_id ) ) ; } return [ '#type' => 'container' , '#markup' => render ( $ response ) , '#attributes' => [ 'class' => '404 error' , ] , '#weight' => 0 , ] ; }
The default 404 content .
1,668
public function onKernelRequestMenuRouterRebuild ( GetResponseEvent $ event ) { if ( file_exists ( "public://rebuild.dat" ) ) { $ site_path = preg_replace ( '/^sites\//' , '' , $ this -> sitePath ) ; if ( ! file_exists ( 'public://.drushrc' ) && file_exists ( 'public://' ) && is_writable ( 'public://' ) && file_put_contents ( 'public:///.drushrc' , "<?php\n\$options['l'] = 'http://${site_path}';" ) ) { drupal_chmod ( 'public:///.drushrc' , 0444 ) ; } if ( $ this -> routerBuilder -> rebuild ( ) ) { file_unmanaged_delete ( "public://rebuild.dat" ) ; } } }
Rebuilds the menu router if the rebuild . dat file is found .
1,669
public function entityQueueCreate ( $ queue , $ destBid ) { $ entity_subqueue = $ this -> entityManager -> getStorage ( 'entity_subqueue' ) -> load ( $ queue ) ; $ items = $ entity_subqueue -> get ( 'items' ) -> getValue ( ) ; $ items [ ] = [ 'target_id' => $ destBid [ 0 ] ] ; $ entity_subqueue -> set ( 'items' , $ items ) ; $ entity_subqueue -> save ( ) ; }
Add a specific entityqueue .
1,670
public function menuLinkDependency ( $ title , $ link , $ translations , $ destBid , $ weight = 0 , $ menu = 'main' ) { $ menu_link_content = $ this -> entityManager -> getStorage ( 'menu_link_content' ) -> create ( [ 'title' => $ title , 'link' => [ 'uri' => 'internal:/node/' . $ destBid [ 0 ] ] , 'menu_name' => ( ! empty ( $ translations ) ) ? $ menu . '-fr' : $ menu , 'langcode' => ( ! empty ( $ translations ) ) ? 'fr' : 'en' , 'parent' => $ link , 'weight' => $ weight , ] ) ; $ menu_link_content -> save ( ) ; $ this -> database -> update ( 'menu_link_content_data' ) -> fields ( [ 'link__uri' => 'entity:node/' . $ destBid [ 0 ] ] ) -> condition ( 'id' , $ menu_link_content -> id ( ) ) -> execute ( ) ; return $ menu_link_content ; }
Add a menu link with dependency support .
1,671
public function transform ( $ value , MigrateExecutableInterface $ migrate_executable , Row $ row , $ destination_property ) { $ field = empty ( $ this -> configuration [ 'field' ] ) ? 'value' : $ this -> configuration [ 'field' ] ; $ termName = FALSE ; if ( isset ( $ value [ $ field ] ) ) { $ termName = $ value [ $ field ] ; } elseif ( ! empty ( $ row -> getSourceProperty ( $ field ) ) ) { $ termName = $ row -> getSourceProperty ( $ field ) ; } elseif ( is_string ( $ value ) ) { $ termName = $ value ; } if ( ! $ termName ) { return $ termName ; } $ term = $ this -> getTerm ( $ termName , $ row , $ this -> configuration [ 'vocabulary' ] ) ; $ term -> save ( ) ; return $ term -> id ( ) ; }
The main function for the plugin actually doing the data conversion .
1,672
protected function getTerm ( $ name , Row $ row , $ vocabulary ) { $ properties = [ ] ; if ( ! empty ( $ name ) ) { $ properties [ 'name' ] = $ name ; } $ vocabularies = taxonomy_vocabulary_get_names ( ) ; if ( isset ( $ vocabularies [ $ vocabulary ] ) ) { $ properties [ 'vid' ] = $ vocabulary ; } else { return NULL ; } $ terms = \ Drupal :: getContainer ( ) -> get ( 'entity.manager' ) -> getStorage ( 'taxonomy_term' ) -> loadByProperties ( $ properties ) ; $ term = reset ( $ terms ) ; if ( ! empty ( $ term ) ) { if ( $ row -> getDestinationProperty ( 'langcode' ) && $ row -> getDestinationProperty ( 'langcode' ) != LanguageInterface :: LANGCODE_NOT_SPECIFIED ) { if ( ! $ term -> hasTranslation ( $ row -> getDestinationProperty ( 'langcode' ) ) ) { $ term -> addTranslation ( $ row -> getDestinationProperty ( 'langcode' ) ) ; } $ term = $ term -> getTranslation ( $ row -> getDestinationProperty ( 'langcode' ) ) ; } return $ term ; } $ term = Term :: create ( $ properties ) ; if ( $ row -> getDestinationProperty ( 'langcode' ) ) { $ term -> langcode = $ row -> getDestinationProperty ( 'langcode' ) ; } return $ term ; }
Creates a new or returns an existing term for the target vocabulary .
1,673
public function getIncludedFields ( string $ resourceType ) : array { if ( $ this -> includedFields === null ) { $ this -> includedFields = $ this -> setIncludedFields ( ) ; } return isset ( $ this -> includedFields [ $ resourceType ] ) ? array_keys ( $ this -> includedFields [ $ resourceType ] ) : [ ] ; }
Returns a list of field names for the given resource type which should be present in the response .
1,674
public function isIncludedField ( string $ resourceType , string $ field ) : bool { if ( $ this -> includedFields === null ) { $ this -> includedFields = $ this -> setIncludedFields ( ) ; } if ( array_key_exists ( $ resourceType , $ this -> includedFields ) === false ) { return true ; } if ( isset ( $ this -> includedFields [ $ resourceType ] [ "" ] ) ) { return false ; } return isset ( $ this -> includedFields [ $ resourceType ] [ $ field ] ) ; }
Determines if a given field for a given resource type should be present in the response or not .
1,675
public function hasIncludedRelationships ( ) : bool { if ( $ this -> includedRelationships === null ) { $ this -> setIncludedRelationships ( ) ; } return empty ( $ this -> includedRelationships ) === false ; }
Determines if any relationship needs to be included .
1,676
public function getIncludedRelationships ( string $ baseRelationshipPath ) : array { if ( $ this -> includedRelationships === null ) { $ this -> setIncludedRelationships ( ) ; } if ( isset ( $ this -> includedRelationships [ $ baseRelationshipPath ] ) ) { return array_values ( $ this -> includedRelationships [ $ baseRelationshipPath ] ) ; } return [ ] ; }
Returns a list of relationship paths for a given parent path which should be included in the response .
1,677
protected function validateClientGeneratedId ( string $ clientGeneratedId , JsonApiRequestInterface $ request , ExceptionFactoryInterface $ exceptionFactory ) { if ( $ clientGeneratedId !== null ) { throw $ exceptionFactory -> createClientGeneratedIdNotSupportedException ( $ request , $ clientGeneratedId ) ; } }
Validates a client - generated ID .
1,678
protected function getAttributeHydrator ( $ book ) : array { return [ "title" => function ( array $ book , $ attribute , $ data ) { $ book [ "title" ] = $ attribute ; return $ book ; } , "pages" => function ( array & $ book , $ attribute , $ data ) { $ book [ "pages" ] = $ attribute ; } ] ; }
Provides the attribute hydrators .
1,679
protected function getRelationshipHydrator ( $ book ) : array { return [ "authors" => function ( array $ book , ToManyRelationship $ authors , $ data , $ relationshipName ) { if ( $ authors -> isEmpty ( ) ) { $ book [ "authors" ] = [ ] ; } else { $ book [ "authors" ] = BookRepository :: getAuthors ( $ authors -> getResourceIdentifierIds ( ) ) ; } return $ book ; } , "publisher" => function ( array & $ book , ToOneRelationship $ publisher , $ data , $ relationshipName ) { if ( $ publisher -> isEmpty ( ) ) { $ book [ "publisher" ] = null ; } else { $ book [ "publisher" ] = BookRepository :: getPublisher ( ( int ) $ publisher -> getResourceIdentifier ( ) -> getId ( ) ) ; } } ] ; }
Provides the relationship hydrators .
1,680
public function getLinks ( ) : ? DocumentLinks { return DocumentLinks :: createWithoutBaseUri ( ) -> setPagination ( "/users" , $ this -> object , $ this -> request -> getUri ( ) -> getQuery ( ) ) ; }
Provides information about the links member of the current document .
1,681
public function disableIncludes ( ) : void { if ( $ this -> request -> getQueryParam ( "include" ) !== null ) { throw $ this -> exceptionFactory -> createInclusionUnsupportedException ( $ this -> request ) ; } }
Disables inclusion of related resources .
1,682
public function disableSorting ( ) : void { if ( $ this -> request -> getQueryParam ( "sort" ) !== null ) { throw $ this -> exceptionFactory -> createSortingUnsupportedException ( $ this -> request ) ; } }
Disables sorting .
1,683
public function createFixedPageBasedPagination ( int $ defaultPage = 0 ) : FixedPageBasedPagination { return FixedPageBasedPagination :: fromPaginationQueryParams ( $ this -> request -> getPagination ( ) , $ defaultPage ) ; }
Returns a FixedPageBasedPagination class in order to be used for fixed page - based pagination .
1,684
public function createPageBasedPagination ( int $ defaultPage = 0 , int $ defaultSize = 0 ) : PageBasedPagination { return PageBasedPagination :: fromPaginationQueryParams ( $ this -> request -> getPagination ( ) , $ defaultPage , $ defaultSize ) ; }
Returns a PageBasedPagination class in order to be used for page - based pagination .
1,685
public function createOffsetBasedPagination ( int $ defaultOffset = 0 , int $ defaultLimit = 0 ) : OffsetBasedPagination { return OffsetBasedPagination :: fromPaginationQueryParams ( $ this -> request -> getPagination ( ) , $ defaultOffset , $ defaultLimit ) ; }
Returns a OffsetBasedPagination class in order to be used for offset - based pagination .
1,686
public function createFixedCursorBasedPagination ( $ defaultCursor = null ) : FixedCursorBasedPagination { return FixedCursorBasedPagination :: fromPaginationQueryParams ( $ this -> request -> getPagination ( ) , $ defaultCursor ) ; }
Returns a FixedCursorBasedPagination class in order to be used for cursor - based pagination .
1,687
public function createCursorBasedPagination ( $ defaultCursor = null , int $ defaultSize = 0 ) : CursorBasedPagination { return CursorBasedPagination :: fromPaginationQueryParams ( $ this -> request -> getPagination ( ) , $ defaultCursor , $ defaultSize ) ; }
Returns a CursorBasedPagination class in order to be used for cursor - based pagination .
1,688
public function hydrateForUpdate ( JsonApiRequestInterface $ request , ExceptionFactoryInterface $ exceptionFactory , $ domainObject ) { $ data = $ request -> getResource ( ) ; if ( $ data === null ) { throw $ exceptionFactory -> createDataMemberMissingException ( $ request ) ; } $ this -> validateType ( $ data , $ exceptionFactory ) ; $ domainObject = $ this -> hydrateIdForUpdate ( $ domainObject , $ data , $ exceptionFactory ) ; $ this -> validateRequest ( $ request ) ; $ domainObject = $ this -> hydrateAttributes ( $ domainObject , $ data ) ; $ domainObject = $ this -> hydrateRelationships ( $ domainObject , $ data , $ exceptionFactory ) ; return $ domainObject ; }
Hydrates the domain object from the updating request .
1,689
public function ok ( ResourceDocumentInterface $ document , $ object , array $ additionalMeta = [ ] ) : ResponseInterface { return $ this -> getResourceResponse ( $ document , $ object , 200 , $ additionalMeta ) ; }
Returns a 200 Ok response containing a document in the body with the resource .
1,690
public function okWithMeta ( ResourceDocumentInterface $ document , $ object , array $ additionalMeta = [ ] ) : ResponseInterface { return $ this -> getMetaResponse ( $ document , $ object , 200 , $ additionalMeta ) ; }
Returns a 200 Ok response containing a document in the body with the resource metadata .
1,691
public function hydrateForCreate ( JsonApiRequestInterface $ request , ExceptionFactoryInterface $ exceptionFactory , $ domainObject ) { $ data = $ request -> getResource ( ) ; if ( $ data === null ) { throw $ exceptionFactory -> createDataMemberMissingException ( $ request ) ; } $ this -> validateType ( $ data , $ exceptionFactory ) ; $ domainObject = $ this -> hydrateIdForCreate ( $ domainObject , $ data , $ request , $ exceptionFactory ) ; $ this -> validateRequest ( $ request ) ; $ domainObject = $ this -> hydrateAttributes ( $ domainObject , $ data ) ; $ domainObject = $ this -> hydrateRelationships ( $ domainObject , $ data , $ exceptionFactory ) ; return $ domainObject ; }
Hydrates the domain object from the creating request .
1,692
public function getAttributes ( $ book ) : array { return [ "title" => function ( array $ book ) { return $ book [ "title" ] ; } , "isbn13" => function ( array $ book ) { return $ book [ "isbn13" ] ; } , "releaseDate" => function ( array $ book ) { return $ book [ "release_date" ] ; } , "hardCover" => function ( array $ book ) { return $ book [ "hard_cover" ] ; } , "pages" => function ( array $ book ) { return ( int ) $ book [ "pages" ] ; } , ] ; }
Provides information about the attributes member of the current resource .
1,693
public function fromSqlToIso8601Time ( string $ string , ? DateTimeZone $ displayedTimeZone = null ) : string { $ dateTime = DateTime :: createFromFormat ( "Y-m-d H:i:s" , $ string , $ displayedTimeZone ) ; if ( $ dateTime === false ) { return "" ; } return $ dateTime -> format ( DateTime :: ATOM ) ; }
Transforms an SQL compatible date - time string to an ISO 8601 compatible date - time string .
1,694
public function hydrate ( JsonApiRequestInterface $ request , ExceptionFactoryInterface $ exceptionFactory , $ domainObject ) { if ( $ request -> getMethod ( ) === "POST" ) { $ domainObject = $ this -> hydrateForCreate ( $ request , $ exceptionFactory , $ domainObject ) ; } elseif ( $ request -> getMethod ( ) === "PATCH" ) { $ domainObject = $ this -> hydrateForUpdate ( $ request , $ exceptionFactory , $ domainObject ) ; } return $ domainObject ; }
Hydrates the domain object from the request based on the request method .
1,695
private function locateInjectionIndex ( array $ contents , string $ type ) : stdClass { $ action = ( object ) [ 'index' => null , 'type' => self :: ACTION_NOT_FOUND , ] ; foreach ( $ contents as $ index => $ line ) { if ( ! preg_match ( '/^### ' . $ type . '/i' , $ line ) ) { continue ; } $ action -> index = $ index + 2 ; $ action -> type = preg_match ( '/^- Nothing/' , $ contents [ $ action -> index ] ) ? self :: ACTION_REPLACE : self :: ACTION_INJECT ; break ; } return $ action ; }
Locates the location within the changelog where the injection should occur . Also determines if the injection is a replacement or an addition .
1,696
private function injectEntry ( array $ contents , stdClass $ action , string $ entry ) : array { switch ( $ action -> type ) { case self :: ACTION_REPLACE : array_splice ( $ contents , $ action -> index , 1 , $ this -> formatEntry ( $ entry ) ) ; break ; case self :: ACTION_INJECT : array_splice ( $ contents , $ action -> index , 0 , $ this -> formatEntry ( $ entry , self :: APPEND_NEWLINE ) ) ; break ; default : break ; } return $ contents ; }
Injects the new entry at the detected index replacing the line if required .
1,697
private function formatEntry ( string $ entry , bool $ withExtraLine = false ) : string { $ entry = sprintf ( '- %s' , $ entry ) ; $ entry = preg_replace ( "/\n(?!\s{2}|$)/s" , "\n " , $ entry ) ; if ( "\n" !== $ entry [ - 1 ] ) { $ entry .= "\n" ; } if ( $ withExtraLine ) { $ entry .= "\n" ; } return $ entry ; }
Formats the entry for use in the changelog .
1,698
private function createNewConfig ( ) : Config { $ globalPath = $ this -> globalPath ? : getenv ( 'HOME' ) ; $ tokenFile = sprintf ( '%s/.keep-a-changelog/token' , $ globalPath ) ; $ token = is_readable ( $ tokenFile ) ? trim ( file_get_contents ( $ tokenFile ) ) : '' ; return new Config ( $ token ) ; }
Create a new Config instance .
1,699
private function createConfigFromFile ( string $ configFile ) : Config { $ ini = parse_ini_file ( $ configFile ) ; return new Config ( $ ini [ 'token' ] ?? '' , $ ini [ 'provider' ] ?? Config :: PROVIDER_GITHUB ) ; }
Parses the config file and returns a populated Config instance .