idx
int64
0
241k
question
stringlengths
92
3.54k
target
stringlengths
5
803
len_question
int64
27
891
len_target
int64
3
240
100
private function parseEndpoint ( $ endpoint ) { $ parsed = parse_url ( $ endpoint ) ; // parse_url() will correctly parse full URIs with schemes if ( isset ( $ parsed [ 'host' ] ) ) { return $ parsed ; } // parse_url() will put host & path in 'path' if scheme is not provided if ( isset ( $ parsed [ 'path' ] ) ) { $ split = explode ( '/' , $ parsed [ 'path' ] , 2 ) ; $ parsed [ 'host' ] = $ split [ 0 ] ; if ( isset ( $ split [ 1 ] ) ) { $ parsed [ 'path' ] = $ split [ 1 ] ; } else { $ parsed [ 'path' ] = '' ; } return $ parsed ; } throw new UnresolvedEndpointException ( "The supplied endpoint '" . "{$endpoint}' is invalid." ) ; }
Parses an endpoint returned from the discovery API into an array with host and path keys .
195
19
101
private function predictEndpoint ( ) { return static function ( callable $ handler ) { return function ( CommandInterface $ command , RequestInterface $ request = null ) use ( $ handler ) { if ( $ command -> getName ( ) === 'Predict' ) { $ request = $ request -> withUri ( new Uri ( $ command [ 'PredictEndpoint' ] ) ) ; } return $ handler ( $ command , $ request ) ; } ; } ; }
Changes the endpoint of the Predict operation to the provided endpoint .
98
12
102
public static function isBucketDnsCompatible ( $ bucket ) { $ bucketLen = strlen ( $ bucket ) ; return ( $ bucketLen >= 3 && $ bucketLen <= 63 ) && // Cannot look like an IP address ! filter_var ( $ bucket , FILTER_VALIDATE_IP ) && preg_match ( '/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/' , $ bucket ) ; }
Determine if a string is a valid name for a DNS compatible Amazon S3 bucket .
110
19
103
private function getLocationConstraintMiddleware ( ) { $ region = $ this -> getRegion ( ) ; return static function ( callable $ handler ) use ( $ region ) { return function ( Command $ command , $ request = null ) use ( $ handler , $ region ) { if ( $ command -> getName ( ) === 'CreateBucket' ) { $ locationConstraint = isset ( $ command [ 'CreateBucketConfiguration' ] [ 'LocationConstraint' ] ) ? $ command [ 'CreateBucketConfiguration' ] [ 'LocationConstraint' ] : null ; if ( $ locationConstraint === 'us-east-1' ) { unset ( $ command [ 'CreateBucketConfiguration' ] ) ; } elseif ( 'us-east-1' !== $ region && empty ( $ locationConstraint ) ) { $ command [ 'CreateBucketConfiguration' ] = [ 'LocationConstraint' => $ region ] ; } } return $ handler ( $ command , $ request ) ; } ; } ; }
Provides a middleware that removes the need to specify LocationConstraint on CreateBucket .
225
20
104
private function getSaveAsParameter ( ) { return static function ( callable $ handler ) { return function ( Command $ command , $ request = null ) use ( $ handler ) { if ( $ command -> getName ( ) === 'GetObject' && isset ( $ command [ 'SaveAs' ] ) ) { $ command [ '@http' ] [ 'sink' ] = $ command [ 'SaveAs' ] ; unset ( $ command [ 'SaveAs' ] ) ; } return $ handler ( $ command , $ request ) ; } ; } ; }
Provides a middleware that supports the SaveAs parameter .
120
12
105
private function getHeadObjectMiddleware ( ) { return static function ( callable $ handler ) { return function ( CommandInterface $ command , RequestInterface $ request = null ) use ( $ handler ) { if ( $ command -> getName ( ) === 'HeadObject' && ! isset ( $ command [ '@http' ] [ 'decode_content' ] ) ) { $ command [ '@http' ] [ 'decode_content' ] = false ; } return $ handler ( $ command , $ request ) ; } ; } ; }
Provides a middleware that disables content decoding on HeadObject commands .
115
15
106
private function decorateWithHashes ( Stream $ stream , array & $ data ) { // Decorate source with a hashing stream $ hash = new PhpHash ( 'sha256' ) ; return new HashingStream ( $ stream , $ hash , function ( $ result ) use ( & $ data ) { $ data [ 'ContentSHA256' ] = bin2hex ( $ result ) ; } ) ; }
Decorates a stream with a sha256 linear hashing stream .
86
14
107
public function appendInit ( callable $ middleware , $ name = null ) { $ this -> add ( self :: INIT , $ name , $ middleware ) ; }
Append a middleware to the init step .
36
10
108
public function prependInit ( callable $ middleware , $ name = null ) { $ this -> add ( self :: INIT , $ name , $ middleware , true ) ; }
Prepend a middleware to the init step .
39
10
109
public function appendValidate ( callable $ middleware , $ name = null ) { $ this -> add ( self :: VALIDATE , $ name , $ middleware ) ; }
Append a middleware to the validate step .
38
10
110
public function prependValidate ( callable $ middleware , $ name = null ) { $ this -> add ( self :: VALIDATE , $ name , $ middleware , true ) ; }
Prepend a middleware to the validate step .
41
10
111
public function appendBuild ( callable $ middleware , $ name = null ) { $ this -> add ( self :: BUILD , $ name , $ middleware ) ; }
Append a middleware to the build step .
36
10
112
public function prependBuild ( callable $ middleware , $ name = null ) { $ this -> add ( self :: BUILD , $ name , $ middleware , true ) ; }
Prepend a middleware to the build step .
39
10
113
public function appendSign ( callable $ middleware , $ name = null ) { $ this -> add ( self :: SIGN , $ name , $ middleware ) ; }
Append a middleware to the sign step .
35
10
114
public function prependSign ( callable $ middleware , $ name = null ) { $ this -> add ( self :: SIGN , $ name , $ middleware , true ) ; }
Prepend a middleware to the sign step .
38
10
115
public function appendAttempt ( callable $ middleware , $ name = null ) { $ this -> add ( self :: ATTEMPT , $ name , $ middleware ) ; }
Append a middleware to the attempt step .
37
10
116
public function prependAttempt ( callable $ middleware , $ name = null ) { $ this -> add ( self :: ATTEMPT , $ name , $ middleware , true ) ; }
Prepend a middleware to the attempt step .
40
10
117
public function before ( $ findName , $ withName , callable $ middleware ) { $ this -> splice ( $ findName , $ withName , $ middleware , true ) ; }
Add a middleware before the given middleware by name .
41
12
118
public function remove ( $ nameOrInstance ) { if ( is_callable ( $ nameOrInstance ) ) { $ this -> removeByInstance ( $ nameOrInstance ) ; } elseif ( is_string ( $ nameOrInstance ) ) { $ this -> removeByName ( $ nameOrInstance ) ; } }
Remove a middleware by name or by instance from the list .
67
13
119
private function sortMiddleware ( ) { $ this -> sorted = [ ] ; if ( ! $ this -> interposeFn ) { foreach ( $ this -> steps as $ step ) { foreach ( $ step as $ fn ) { $ this -> sorted [ ] = $ fn [ 0 ] ; } } return ; } $ ifn = $ this -> interposeFn ; // Interpose the interposeFn into the handler stack. foreach ( $ this -> steps as $ stepName => $ step ) { foreach ( $ step as $ fn ) { $ this -> sorted [ ] = $ ifn ( $ stepName , $ fn [ 1 ] ) ; $ this -> sorted [ ] = $ fn [ 0 ] ; } } }
Sort the middleware and interpose if needed in the sorted list .
157
14
120
private function add ( $ step , $ name , callable $ middleware , $ prepend = false ) { $ this -> sorted = null ; if ( $ prepend ) { $ this -> steps [ $ step ] [ ] = [ $ middleware , $ name ] ; } else { array_unshift ( $ this -> steps [ $ step ] , [ $ middleware , $ name ] ) ; } if ( $ name ) { $ this -> named [ $ name ] = $ step ; } }
Add a middleware to a step .
105
8
121
public function each ( callable $ handleResult ) { return Promise \ coroutine ( function ( ) use ( $ handleResult ) { $ nextToken = null ; do { $ command = $ this -> createNextCommand ( $ this -> args , $ nextToken ) ; $ result = ( yield $ this -> client -> executeAsync ( $ command ) ) ; $ nextToken = $ this -> determineNextToken ( $ result ) ; $ retVal = $ handleResult ( $ result ) ; if ( $ retVal !== null ) { yield Promise \ promise_for ( $ retVal ) ; } } while ( $ nextToken ) ; } ) ; }
Runs a paginator asynchronously and uses a callback to handle results .
135
16
122
public function search ( $ expression ) { // Apply JMESPath expression on each result, but as a flat sequence. return flatmap ( $ this , function ( Result $ result ) use ( $ expression ) { return ( array ) $ result -> search ( $ expression ) ; } ) ; }
Returns an iterator that iterates over the values of applying a JMESPath search to each result yielded by the iterator as a flat sequence .
60
28
123
public function resolve ( array $ shapeRef ) { $ shape = $ shapeRef [ 'shape' ] ; if ( ! isset ( $ this -> definitions [ $ shape ] ) ) { throw new \ InvalidArgumentException ( 'Shape not found: ' . $ shape ) ; } $ isSimple = count ( $ shapeRef ) == 1 ; if ( $ isSimple && isset ( $ this -> simple [ $ shape ] ) ) { return $ this -> simple [ $ shape ] ; } $ definition = $ shapeRef + $ this -> definitions [ $ shape ] ; $ definition [ 'name' ] = $ definition [ 'shape' ] ; unset ( $ definition [ 'shape' ] ) ; $ result = Shape :: create ( $ definition , $ this ) ; if ( $ isSimple ) { $ this -> simple [ $ shape ] = $ result ; } return $ result ; }
Resolve a shape reference
186
5
124
protected function encrypt ( Stream $ plaintext , array $ cipherOptions , MaterialsProvider $ provider , MetadataEnvelope $ envelope ) { $ materialsDescription = $ provider -> getMaterialsDescription ( ) ; $ cipherOptions = array_intersect_key ( $ cipherOptions , self :: $ allowedOptions ) ; if ( empty ( $ cipherOptions [ 'Cipher' ] ) ) { throw new \ InvalidArgumentException ( 'An encryption cipher must be' . ' specified in the "cipher_options".' ) ; } if ( ! self :: isSupportedCipher ( $ cipherOptions [ 'Cipher' ] ) ) { throw new \ InvalidArgumentException ( 'The cipher requested is not' . ' supported by the SDK.' ) ; } if ( empty ( $ cipherOptions [ 'KeySize' ] ) ) { $ cipherOptions [ 'KeySize' ] = 256 ; } if ( ! is_int ( $ cipherOptions [ 'KeySize' ] ) ) { throw new \ InvalidArgumentException ( 'The cipher "KeySize" must be' . ' an integer.' ) ; } if ( ! MaterialsProvider :: isSupportedKeySize ( $ cipherOptions [ 'KeySize' ] ) ) { throw new \ InvalidArgumentException ( 'The cipher "KeySize" requested' . ' is not supported by AES (128, 192, or 256).' ) ; } $ cipherOptions [ 'Iv' ] = $ provider -> generateIv ( $ this -> getCipherOpenSslName ( $ cipherOptions [ 'Cipher' ] , $ cipherOptions [ 'KeySize' ] ) ) ; $ cek = $ provider -> generateCek ( $ cipherOptions [ 'KeySize' ] ) ; list ( $ encryptingStream , $ aesName ) = $ this -> getEncryptingStream ( $ plaintext , $ cek , $ cipherOptions ) ; // Populate envelope data $ envelope [ MetadataEnvelope :: CONTENT_KEY_V2_HEADER ] = $ provider -> encryptCek ( $ cek , $ materialsDescription ) ; unset ( $ cek ) ; $ envelope [ MetadataEnvelope :: IV_HEADER ] = base64_encode ( $ cipherOptions [ 'Iv' ] ) ; $ envelope [ MetadataEnvelope :: KEY_WRAP_ALGORITHM_HEADER ] = $ provider -> getWrapAlgorithmName ( ) ; $ envelope [ MetadataEnvelope :: CONTENT_CRYPTO_SCHEME_HEADER ] = $ aesName ; $ envelope [ MetadataEnvelope :: UNENCRYPTED_CONTENT_LENGTH_HEADER ] = strlen ( $ plaintext ) ; $ envelope [ MetadataEnvelope :: UNENCRYPTED_CONTENT_MD5_HEADER ] = base64_encode ( md5 ( $ plaintext ) ) ; $ envelope [ MetadataEnvelope :: MATERIALS_DESCRIPTION_HEADER ] = json_encode ( $ materialsDescription ) ; if ( ! empty ( $ cipherOptions [ 'Tag' ] ) ) { $ envelope [ MetadataEnvelope :: CRYPTO_TAG_LENGTH_HEADER ] = strlen ( $ cipherOptions [ 'Tag' ] ) * 8 ; } return $ encryptingStream ; }
Builds an AesStreamInterface and populates encryption metadata into the supplied envelope .
708
17
125
public function getPartition ( $ region , $ service ) { foreach ( $ this -> partitions as $ partition ) { if ( $ partition -> isRegionMatch ( $ region , $ service ) ) { return $ partition ; } } return $ this -> getPartitionByName ( $ this -> defaultPartition ) ; }
Returns the partition containing the provided region or the default partition if no match is found .
67
17
126
public function getPartitionByName ( $ name ) { foreach ( $ this -> partitions as $ partition ) { if ( $ name === $ partition -> getName ( ) ) { return $ partition ; } } }
Returns the partition with the provided name or null if no partition with the provided name can be found .
45
20
127
public static function mergePrefixData ( $ data , $ prefixData ) { $ prefixGroups = $ prefixData [ 'prefix-groups' ] ; foreach ( $ data [ "partitions" ] as $ index => $ partition ) { foreach ( $ prefixGroups as $ current => $ old ) { $ serviceData = Env :: search ( "services.{$current}" , $ partition ) ; if ( ! empty ( $ serviceData ) ) { foreach ( $ old as $ prefix ) { if ( empty ( Env :: search ( "services.{$prefix}" , $ partition ) ) ) { $ data [ "partitions" ] [ $ index ] [ "services" ] [ $ prefix ] = $ serviceData ; } } } } } return $ data ; }
Copy endpoint data for other prefixes used by a given service
167
12
128
public static function env ( ) { return function ( ) { // Use credentials from environment variables, if available $ key = getenv ( self :: ENV_KEY ) ; $ secret = getenv ( self :: ENV_SECRET ) ; if ( $ key && $ secret ) { return Promise \ promise_for ( new Credentials ( $ key , $ secret , getenv ( self :: ENV_SESSION ) ? : NULL ) ) ; } return self :: reject ( 'Could not find environment variable ' . 'credentials in ' . self :: ENV_KEY . '/' . self :: ENV_SECRET ) ; } ; }
Provider that creates credentials from environment variables AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN .
137
33
129
public static function ini ( $ profile = null , $ filename = null ) { $ filename = $ filename ? : ( self :: getHomeDir ( ) . '/.aws/credentials' ) ; $ profile = $ profile ? : ( getenv ( self :: ENV_PROFILE ) ? : 'default' ) ; return function ( ) use ( $ profile , $ filename ) { if ( ! is_readable ( $ filename ) ) { return self :: reject ( "Cannot read credentials from $filename" ) ; } $ data = \ Aws \ parse_ini_file ( $ filename , true , INI_SCANNER_RAW ) ; if ( $ data === false ) { return self :: reject ( "Invalid credentials file: $filename" ) ; } if ( ! isset ( $ data [ $ profile ] ) ) { return self :: reject ( "'$profile' not found in credentials file" ) ; } if ( ! isset ( $ data [ $ profile ] [ 'aws_access_key_id' ] ) || ! isset ( $ data [ $ profile ] [ 'aws_secret_access_key' ] ) ) { return self :: reject ( "No credentials present in INI profile " . "'$profile' ($filename)" ) ; } if ( empty ( $ data [ $ profile ] [ 'aws_session_token' ] ) ) { $ data [ $ profile ] [ 'aws_session_token' ] = isset ( $ data [ $ profile ] [ 'aws_security_token' ] ) ? $ data [ $ profile ] [ 'aws_security_token' ] : null ; } return Promise \ promise_for ( new Credentials ( $ data [ $ profile ] [ 'aws_access_key_id' ] , $ data [ $ profile ] [ 'aws_secret_access_key' ] , $ data [ $ profile ] [ 'aws_session_token' ] ) ) ; } ; }
Credentials provider that creates credentials using an ini file stored in the current user s home directory .
416
21
130
public static function process ( $ profile = null , $ filename = null ) { $ filename = $ filename ? : ( self :: getHomeDir ( ) . '/.aws/credentials' ) ; $ profile = $ profile ? : ( getenv ( self :: ENV_PROFILE ) ? : 'default' ) ; return function ( ) use ( $ profile , $ filename ) { if ( ! is_readable ( $ filename ) ) { return self :: reject ( "Cannot read process credentials from $filename" ) ; } $ data = \ Aws \ parse_ini_file ( $ filename , true , INI_SCANNER_RAW ) ; if ( $ data === false ) { return self :: reject ( "Invalid credentials file: $filename" ) ; } if ( ! isset ( $ data [ $ profile ] ) ) { return self :: reject ( "'$profile' not found in credentials file" ) ; } if ( ! isset ( $ data [ $ profile ] [ 'credential_process' ] ) ) { return self :: reject ( "No credential_process present in INI profile " . "'$profile' ($filename)" ) ; } $ credentialProcess = $ data [ $ profile ] [ 'credential_process' ] ; $ json = shell_exec ( $ credentialProcess ) ; $ processData = json_decode ( $ json , true ) ; // Only support version 1 if ( isset ( $ processData [ 'Version' ] ) ) { if ( $ processData [ 'Version' ] !== 1 ) { return self :: reject ( "credential_process does not return Version == 1" ) ; } } if ( ! isset ( $ processData [ 'AccessKeyId' ] ) || ! isset ( $ processData [ 'SecretAccessKey' ] ) ) { return self :: reject ( "credential_process does not return valid credentials" ) ; } if ( isset ( $ processData [ 'Expiration' ] ) ) { try { $ expiration = new DateTimeResult ( $ processData [ 'Expiration' ] ) ; } catch ( \ Exception $ e ) { return self :: reject ( "credential_process returned invalid expiration" ) ; } $ now = new DateTimeResult ( ) ; if ( $ expiration < $ now ) { return self :: reject ( "credential_process returned expired credentials" ) ; } } else { $ processData [ 'Expiration' ] = null ; } if ( empty ( $ processData [ 'SessionToken' ] ) ) { $ processData [ 'SessionToken' ] = null ; } return Promise \ promise_for ( new Credentials ( $ processData [ 'AccessKeyId' ] , $ processData [ 'SecretAccessKey' ] , $ processData [ 'SessionToken' ] , $ processData [ 'Expiration' ] ) ) ; } ; }
Credentials provider that creates credentials using a process configured in ini file stored in the current user s home directory .
613
24
131
public static function requestBuilder ( callable $ serializer ) { return function ( callable $ handler ) use ( $ serializer ) { return function ( CommandInterface $ command ) use ( $ serializer , $ handler ) { return $ handler ( $ command , $ serializer ( $ command ) ) ; } ; } ; }
Builds an HTTP request for a command .
67
9
132
public static function signer ( callable $ credProvider , callable $ signatureFunction ) { return function ( callable $ handler ) use ( $ signatureFunction , $ credProvider ) { return function ( CommandInterface $ command , RequestInterface $ request ) use ( $ handler , $ signatureFunction , $ credProvider ) { $ signer = $ signatureFunction ( $ command ) ; return $ credProvider ( ) -> then ( function ( CredentialsInterface $ creds ) use ( $ handler , $ command , $ signer , $ request ) { return $ handler ( $ command , $ signer -> signRequest ( $ request , $ creds ) ) ; } ) ; } ; } ; }
Creates a middleware that signs requests for a command .
143
12
133
public static function tap ( callable $ fn ) { return function ( callable $ handler ) use ( $ fn ) { return function ( CommandInterface $ command , RequestInterface $ request = null ) use ( $ handler , $ fn ) { $ fn ( $ command , $ request ) ; return $ handler ( $ command , $ request ) ; } ; } ; }
Creates a middleware that invokes a callback at a given step .
75
15
134
public static function invocationId ( ) { return function ( callable $ handler ) { return function ( CommandInterface $ command , RequestInterface $ request ) use ( $ handler ) { return $ handler ( $ command , $ request -> withHeader ( 'aws-sdk-invocation-id' , md5 ( uniqid ( gethostname ( ) , true ) ) ) ) ; } ; } ; }
Middleware wrapper function that adds an invocation id header to requests which is only applied after the build step .
85
21
135
public static function contentType ( array $ operations ) { return function ( callable $ handler ) use ( $ operations ) { return function ( CommandInterface $ command , RequestInterface $ request = null ) use ( $ handler , $ operations ) { if ( ! $ request -> hasHeader ( 'Content-Type' ) && in_array ( $ command -> getName ( ) , $ operations , true ) && ( $ uri = $ request -> getBody ( ) -> getMetadata ( 'uri' ) ) ) { $ request = $ request -> withHeader ( 'Content-Type' , Psr7 \ mimetype_from_filename ( $ uri ) ? : 'application/octet-stream' ) ; } return $ handler ( $ command , $ request ) ; } ; } ; }
Middleware wrapper function that adds a Content - Type header to requests . This is only done when the Content - Type has not already been set and the request body s URI is available . It then checks the file extension of the URI to determine the mime - type .
167
54
136
public static function history ( History $ history ) { return function ( callable $ handler ) use ( $ history ) { return function ( CommandInterface $ command , RequestInterface $ request = null ) use ( $ handler , $ history ) { $ ticket = $ history -> start ( $ command , $ request ) ; return $ handler ( $ command , $ request ) -> then ( function ( $ result ) use ( $ history , $ ticket ) { $ history -> finish ( $ ticket , $ result ) ; return $ result ; } , function ( $ reason ) use ( $ history , $ ticket ) { $ history -> finish ( $ ticket , $ reason ) ; return Promise \ rejection_for ( $ reason ) ; } ) ; } ; } ; }
Tracks command and request history using a history container .
153
11
137
public static function mapRequest ( callable $ f ) { return function ( callable $ handler ) use ( $ f ) { return function ( CommandInterface $ command , RequestInterface $ request = null ) use ( $ handler , $ f ) { return $ handler ( $ command , $ f ( $ request ) ) ; } ; } ; }
Creates a middleware that applies a map function to requests as they pass through the middleware .
70
20
138
public static function mapCommand ( callable $ f ) { return function ( callable $ handler ) use ( $ f ) { return function ( CommandInterface $ command , RequestInterface $ request = null ) use ( $ handler , $ f ) { return $ handler ( $ f ( $ command ) , $ request ) ; } ; } ; }
Creates a middleware that applies a map function to commands as they pass through the middleware .
70
20
139
public static function mapResult ( callable $ f ) { return function ( callable $ handler ) use ( $ f ) { return function ( CommandInterface $ command , RequestInterface $ request = null ) use ( $ handler , $ f ) { return $ handler ( $ command , $ request ) -> then ( $ f ) ; } ; } ; }
Creates a middleware that applies a map function to results .
72
13
140
private function determineState ( ) { // If the state was provided via config, then just use it. if ( $ this -> config [ 'state' ] instanceof UploadState ) { return $ this -> config [ 'state' ] ; } // Otherwise, construct a new state from the provided identifiers. $ required = $ this -> info [ 'id' ] ; $ id = [ $ required [ 'upload_id' ] => null ] ; unset ( $ required [ 'upload_id' ] ) ; foreach ( $ required as $ key => $ param ) { if ( ! $ this -> config [ $ key ] ) { throw new IAE ( 'You must provide a value for "' . $ key . '" in ' . 'your config for the MultipartUploader for ' . $ this -> client -> getApi ( ) -> getServiceFullName ( ) . '.' ) ; } $ id [ $ param ] = $ this -> config [ $ key ] ; } $ state = new UploadState ( $ id ) ; $ state -> setPartSize ( $ this -> determinePartSize ( ) ) ; return $ state ; }
Based on the config and service - specific workflow info creates a Promise for an UploadState object .
240
19
141
private function checkExistenceWithCommand ( CommandInterface $ command ) { try { $ this -> execute ( $ command ) ; return true ; } catch ( S3Exception $ e ) { if ( $ e -> getAwsErrorCode ( ) == 'AccessDenied' ) { return true ; } if ( $ e -> getStatusCode ( ) >= 500 ) { throw $ e ; } return false ; } }
Determines whether or not a resource exists using a command
86
12
142
private function decorateWithHashes ( Stream $ stream , array & $ data ) { // Make sure that a tree hash is calculated. $ stream = new HashingStream ( $ stream , new TreeHash ( ) , function ( $ result ) use ( & $ data ) { $ data [ 'checksum' ] = bin2hex ( $ result ) ; } ) ; // Make sure that a linear SHA256 hash is calculated. $ stream = new HashingStream ( $ stream , new PhpHash ( 'sha256' ) , function ( $ result ) use ( & $ data ) { $ data [ 'ContentSHA256' ] = bin2hex ( $ result ) ; } ) ; return $ stream ; }
Decorates a stream with a tree AND linear sha256 hashing stream .
149
16
143
private static function parseRange ( $ range , $ partSize ) { // Strip away the prefix and suffix. if ( strpos ( $ range , 'bytes' ) !== false ) { $ range = substr ( $ range , 6 , - 2 ) ; } // Split that range into it's parts. list ( $ firstByte , $ lastByte ) = explode ( '-' , $ range ) ; // Calculate and return range index and range size return [ intval ( $ firstByte / $ partSize ) + 1 , $ lastByte - $ firstByte + 1 , ] ; }
Parses a Glacier range string into a size and part number .
122
14
144
public function build ( Shape $ shape , array $ args ) { $ result = json_encode ( $ this -> format ( $ shape , $ args ) ) ; return $ result == '[]' ? '{}' : $ result ; }
Builds the JSON body based on an array of arguments .
51
12
145
private function getContext ( ) { if ( ! $ this -> context ) { $ key = isset ( $ this -> options [ 'key' ] ) ? $ this -> options [ 'key' ] : null ; $ this -> context = hash_init ( $ this -> algo , $ key ? HASH_HMAC : 0 , $ key ) ; } return $ this -> context ; }
Get a hash context or create one if needed
83
9
146
private function getArgsForAttempt ( $ attempt ) { $ args = $ this -> args ; // Determine the delay. $ delay = ( $ attempt === 1 ) ? $ this -> config [ 'initDelay' ] : $ this -> config [ 'delay' ] ; if ( is_callable ( $ delay ) ) { $ delay = $ delay ( $ attempt ) ; } // Set the delay. (Note: handlers except delay in milliseconds.) if ( ! isset ( $ args [ '@http' ] ) ) { $ args [ '@http' ] = [ ] ; } $ args [ '@http' ] [ 'delay' ] = $ delay * 1000 ; return $ args ; }
Gets the operation arguments for the attempt including the delay .
148
12
147
private function determineState ( $ result ) { foreach ( $ this -> config [ 'acceptors' ] as $ acceptor ) { $ matcher = 'matches' . ucfirst ( $ acceptor [ 'matcher' ] ) ; if ( $ this -> { $ matcher } ( $ result , $ acceptor ) ) { return $ acceptor [ 'state' ] ; } } return $ result instanceof \ Exception ? 'failed' : 'retry' ; }
Determines the state of the waiter attempt based on the result of polling the resource . A waiter can have the state of success failed or retry .
102
31
148
public function promise ( ) { // If the promise has been created, just return it. if ( ! $ this -> promise ) { // Create an upload/download promise for the transfer. $ this -> promise = $ this -> sourceMetadata [ 'scheme' ] === 'file' ? $ this -> createUploadPromise ( ) : $ this -> createDownloadPromise ( ) ; } return $ this -> promise ; }
Transfers the files .
88
6
149
private function getS3Args ( $ path ) { $ parts = explode ( '/' , str_replace ( 's3://' , '' , $ path ) , 2 ) ; $ args = [ 'Bucket' => $ parts [ 0 ] ] ; if ( isset ( $ parts [ 1 ] ) ) { $ args [ 'Key' ] = $ parts [ 1 ] ; } return $ args ; }
Creates an array that contains Bucket and Key by parsing the filename .
87
14
150
public function resolve ( array $ args , HandlerList $ list ) { $ args [ 'config' ] = [ ] ; foreach ( $ this -> argDefinitions as $ key => $ a ) { // Add defaults, validate required values, and skip if not set. if ( ! isset ( $ args [ $ key ] ) ) { if ( isset ( $ a [ 'default' ] ) ) { // Merge defaults in when not present. if ( is_callable ( $ a [ 'default' ] ) && ( is_array ( $ a [ 'default' ] ) || $ a [ 'default' ] instanceof \ Closure ) ) { $ args [ $ key ] = $ a [ 'default' ] ( $ args ) ; } else { $ args [ $ key ] = $ a [ 'default' ] ; } } elseif ( empty ( $ a [ 'required' ] ) ) { continue ; } else { $ this -> throwRequired ( $ args ) ; } } // Validate the types against the provided value. foreach ( $ a [ 'valid' ] as $ check ) { if ( isset ( self :: $ typeMap [ $ check ] ) ) { $ fn = self :: $ typeMap [ $ check ] ; if ( $ fn ( $ args [ $ key ] ) ) { goto is_valid ; } } elseif ( $ args [ $ key ] instanceof $ check ) { goto is_valid ; } } $ this -> invalidType ( $ key , $ args [ $ key ] ) ; // Apply the value is_valid : if ( isset ( $ a [ 'fn' ] ) ) { $ a [ 'fn' ] ( $ args [ $ key ] , $ args , $ list ) ; } if ( $ a [ 'type' ] === 'config' ) { $ args [ 'config' ] [ $ key ] = $ args [ $ key ] ; } } return $ args ; }
Resolves client configuration options and attached event listeners . Check for missing keys in passed arguments
412
17
151
private function getArgMessage ( $ name , $ args = [ ] , $ useRequired = false ) { $ arg = $ this -> argDefinitions [ $ name ] ; $ msg = '' ; $ modifiers = [ ] ; if ( isset ( $ arg [ 'valid' ] ) ) { $ modifiers [ ] = implode ( '|' , $ arg [ 'valid' ] ) ; } if ( isset ( $ arg [ 'choice' ] ) ) { $ modifiers [ ] = 'One of ' . implode ( ', ' , $ arg [ 'choice' ] ) ; } if ( $ modifiers ) { $ msg .= '(' . implode ( '; ' , $ modifiers ) . ')' ; } $ msg = wordwrap ( "{$name}: {$msg}" , 75 , "\n " ) ; if ( $ useRequired && is_callable ( $ arg [ 'required' ] ) ) { $ msg .= "\n\n " ; $ msg .= str_replace ( "\n" , "\n " , call_user_func ( $ arg [ 'required' ] , $ args ) ) ; } elseif ( isset ( $ arg [ 'doc' ] ) ) { $ msg .= wordwrap ( "\n\n {$arg['doc']}" , 75 , "\n " ) ; } return $ msg ; }
Creates a verbose error message for an invalid argument .
290
12
152
private function invalidType ( $ name , $ provided ) { $ expected = implode ( '|' , $ this -> argDefinitions [ $ name ] [ 'valid' ] ) ; $ msg = "Invalid configuration value " . "provided for \"{$name}\". Expected {$expected}, but got " . describe_type ( $ provided ) . "\n\n" . $ this -> getArgMessage ( $ name ) ; throw new IAE ( $ msg ) ; }
Throw when an invalid type is encountered .
102
8
153
private function throwRequired ( array $ args ) { $ missing = [ ] ; foreach ( $ this -> argDefinitions as $ k => $ a ) { if ( empty ( $ a [ 'required' ] ) || isset ( $ a [ 'default' ] ) || isset ( $ args [ $ k ] ) ) { continue ; } $ missing [ ] = $ this -> getArgMessage ( $ k , $ args , true ) ; } $ msg = "Missing required client configuration options: \n\n" ; $ msg .= implode ( "\n\n" , $ missing ) ; throw new IAE ( $ msg ) ; }
Throws an exception for missing required arguments .
138
9
154
private function sendEventData ( array $ eventData ) { $ socket = $ this -> prepareSocket ( ) ; $ datagram = json_encode ( $ eventData ) ; $ result = socket_write ( $ socket , $ datagram , strlen ( $ datagram ) ) ; if ( $ result === false ) { $ this -> prepareSocket ( true ) ; } return $ result ; }
Sends formatted monitoring event data via the UDP socket connection to the CSM agent endpoint .
83
18
155
private function unwrappedOptions ( ) { if ( ! ( $ this -> options instanceof ConfigurationInterface ) ) { $ this -> options = ConfigurationProvider :: unwrap ( $ this -> options ) ; } return $ this -> options ; }
Unwraps options if needed and returns them .
49
10
156
private function searchByPost ( ) { return static function ( callable $ handler ) { return function ( CommandInterface $ c , RequestInterface $ r = null ) use ( $ handler ) { if ( $ c -> getName ( ) !== 'Search' ) { return $ handler ( $ c , $ r ) ; } return $ handler ( $ c , self :: convertGetToPost ( $ r ) ) ; } ; } ; }
Use POST for search command
91
5
157
public static function convertGetToPost ( RequestInterface $ r ) { if ( $ r -> getMethod ( ) === 'POST' ) { return $ r ; } $ query = $ r -> getUri ( ) -> getQuery ( ) ; $ req = $ r -> withMethod ( 'POST' ) -> withBody ( Psr7 \ stream_for ( $ query ) ) -> withHeader ( 'Content-Length' , strlen ( $ query ) ) -> withHeader ( 'Content-Type' , 'application/x-www-form-urlencoded' ) -> withUri ( $ r -> getUri ( ) -> withQuery ( '' ) ) ; return $ req ; }
Converts default GET request to a POST request
147
9
158
public function validate ( $ name , Shape $ shape , array $ input ) { $ this -> dispatch ( $ shape , $ input ) ; if ( $ this -> errors ) { $ message = sprintf ( "Found %d error%s while validating the input provided for the " . "%s operation:\n%s" , count ( $ this -> errors ) , count ( $ this -> errors ) > 1 ? 's' : '' , $ name , implode ( "\n" , $ this -> errors ) ) ; $ this -> errors = [ ] ; throw new \ InvalidArgumentException ( $ message ) ; } }
Validates the given input against the schema .
131
9
159
public function getObjectAsync ( array $ args ) { $ provider = $ this -> getMaterialsProvider ( $ args ) ; unset ( $ args [ '@MaterialsProvider' ] ) ; $ instructionFileSuffix = $ this -> getInstructionFileSuffix ( $ args ) ; unset ( $ args [ '@InstructionFileSuffix' ] ) ; $ strategy = $ this -> getMetadataStrategy ( $ args , $ instructionFileSuffix ) ; unset ( $ args [ '@MetadataStrategy' ] ) ; $ saveAs = null ; if ( ! empty ( $ args [ 'SaveAs' ] ) ) { $ saveAs = $ args [ 'SaveAs' ] ; } $ promise = $ this -> client -> getObjectAsync ( $ args ) -> then ( function ( $ result ) use ( $ provider , $ instructionFileSuffix , $ strategy , $ args ) { if ( $ strategy === null ) { $ strategy = $ this -> determineGetObjectStrategy ( $ result , $ instructionFileSuffix ) ; } $ envelope = $ strategy -> load ( $ args + [ 'Metadata' => $ result [ 'Metadata' ] ] ) ; $ provider = $ provider -> fromDecryptionEnvelope ( $ envelope ) ; $ result [ 'Body' ] = $ this -> decrypt ( $ result [ 'Body' ] , $ provider , $ envelope , isset ( $ args [ '@CipherOptions' ] ) ? $ args [ '@CipherOptions' ] : [ ] ) ; return $ result ; } ) -> then ( function ( $ result ) use ( $ saveAs ) { if ( ! empty ( $ saveAs ) ) { file_put_contents ( $ saveAs , ( string ) $ result [ 'Body' ] , LOCK_EX ) ; } return $ result ; } ) ; return $ promise ; }
Promises to retrieve an object from S3 and decrypt the data in the Body field .
403
18
160
private function parseClass ( ) { $ klass = get_class ( $ this ) ; if ( $ klass === __CLASS__ ) { return [ '' , 'Aws\Exception\AwsException' ] ; } $ service = substr ( $ klass , strrpos ( $ klass , '\\' ) + 1 , - 6 ) ; return [ strtolower ( $ service ) , "Aws\\{$service}\\Exception\\{$service}Exception" ] ; }
Parse the class name and setup the custom exception class of the client and return the service name of the client and exception_class .
106
27
161
public function getMember ( $ name ) { $ members = $ this -> getMembers ( ) ; if ( ! isset ( $ members [ $ name ] ) ) { throw new \ InvalidArgumentException ( 'Unknown member ' . $ name ) ; } return $ members [ $ name ] ; }
Retrieve a member by name .
62
7
162
public static function wrap ( Service $ service , callable $ bytesGenerator = null ) { return function ( callable $ handler ) use ( $ service , $ bytesGenerator ) { return new self ( $ handler , $ service , $ bytesGenerator ) ; } ; }
Creates a middleware that populates operation parameter with trait idempotencyToken enabled with a random UUIDv4
57
25
163
private static function getUuidV4 ( $ bytes ) { // set version to 0100 $ bytes [ 6 ] = chr ( ord ( $ bytes [ 6 ] ) & 0x0f | 0x40 ) ; // set bits 6-7 to 10 $ bytes [ 8 ] = chr ( ord ( $ bytes [ 8 ] ) & 0x3f | 0x80 ) ; return vsprintf ( '%s%s-%s-%s-%s-%s%s%s' , str_split ( bin2hex ( $ bytes ) , 4 ) ) ; }
This function generates a random UUID v4 string which is used as auto filled token value .
127
19
164
public function formatErrors ( AnalysisResult $ analysisResult , OutputStyle $ style ) : int { $ style -> writeln ( '<?xml version="1.0" encoding="UTF-8"?>' ) ; $ style -> writeln ( '<checkstyle>' ) ; foreach ( $ this -> groupByFile ( $ analysisResult ) as $ relativeFilePath => $ errors ) { $ style -> writeln ( sprintf ( '<file name="%s">' , $ this -> escape ( $ relativeFilePath ) ) ) ; foreach ( $ errors as $ error ) { $ style -> writeln ( sprintf ( ' <error line="%d" column="1" severity="error" message="%s" />' , $ this -> escape ( ( string ) $ error -> getLine ( ) ) , $ this -> escape ( ( string ) $ error -> getMessage ( ) ) ) ) ; } $ style -> writeln ( '</file>' ) ; } $ notFileSpecificErrors = $ analysisResult -> getNotFileSpecificErrors ( ) ; if ( count ( $ notFileSpecificErrors ) > 0 ) { $ style -> writeln ( '<file>' ) ; foreach ( $ notFileSpecificErrors as $ error ) { $ style -> writeln ( sprintf ( ' <error severity="error" message="%s" />' , $ this -> escape ( $ error ) ) ) ; } $ style -> writeln ( '</file>' ) ; } $ style -> writeln ( '</checkstyle>' ) ; return $ analysisResult -> hasErrors ( ) ? 1 : 0 ; }
Formats the errors and outputs them to the console .
351
11
165
private function groupByFile ( AnalysisResult $ analysisResult ) : array { $ files = [ ] ; /** @var \PHPStan\Analyser\Error $fileSpecificError */ foreach ( $ analysisResult -> getFileSpecificErrors ( ) as $ fileSpecificError ) { $ relativeFilePath = $ this -> relativePathHelper -> getRelativePath ( $ fileSpecificError -> getFile ( ) ) ; $ files [ $ relativeFilePath ] [ ] = $ fileSpecificError ; } return $ files ; }
Group errors by file
110
4
166
protected function registerLogService ( ) { $ logger = Log :: createLogger ( $ this -> config -> get ( 'log.file' ) , 'yansongda.pay' , $ this -> config -> get ( 'log.level' , 'warning' ) , $ this -> config -> get ( 'log.type' , 'daily' ) , $ this -> config -> get ( 'log.max_file' , 30 ) ) ; Log :: setLogger ( $ logger ) ; }
Register log service .
106
4
167
public function refund ( $ order ) : Collection { $ this -> payload = Support :: filterPayload ( $ this -> payload , $ order , true ) ; Events :: dispatch ( Events :: METHOD_CALLED , new Events \ MethodCalled ( 'Wechat' , 'Refund' , $ this -> gateway , $ this -> payload ) ) ; return Support :: requestApi ( 'secapi/pay/refund' , $ this -> payload , true ) ; }
Refund an order .
100
5
168
public function download ( array $ params ) : string { unset ( $ this -> payload [ 'spbill_create_ip' ] ) ; $ this -> payload = Support :: filterPayload ( $ this -> payload , $ params , true ) ; Events :: dispatch ( Events :: METHOD_CALLED , new Events \ MethodCalled ( 'Wechat' , 'Download' , $ this -> gateway , $ this -> payload ) ) ; $ result = Support :: getInstance ( ) -> post ( 'pay/downloadbill' , Support :: getInstance ( ) -> toXml ( $ this -> payload ) ) ; if ( is_array ( $ result ) ) { throw new GatewayException ( 'Get Wechat API Error: ' . $ result [ 'return_msg' ] , $ result ) ; } return $ result ; }
Download the bill .
175
4
169
public static function getSignContent ( $ data ) : string { $ buff = '' ; foreach ( $ data as $ k => $ v ) { $ buff .= ( $ k != 'sign' && $ v != '' && ! is_array ( $ v ) ) ? $ k . '=' . $ v . '&' : '' ; } Log :: debug ( 'Wechat Generate Sign Content Before Trim' , [ $ data , $ buff ] ) ; return trim ( $ buff , '&' ) ; }
Generate sign content .
111
5
170
public static function decryptRefundContents ( $ contents ) : string { return openssl_decrypt ( base64_decode ( $ contents ) , 'AES-256-ECB' , md5 ( self :: $ instance -> key ) , OPENSSL_RAW_DATA ) ; }
Decrypt refund contents .
61
5
171
public static function toXml ( $ data ) : string { if ( ! is_array ( $ data ) || count ( $ data ) <= 0 ) { throw new InvalidArgumentException ( 'Convert To Xml Error! Invalid Array!' ) ; } $ xml = '<xml>' ; foreach ( $ data as $ key => $ val ) { $ xml .= is_numeric ( $ val ) ? '<' . $ key . '>' . $ val . '</' . $ key . '>' : '<' . $ key . '><![CDATA[' . $ val . ']]></' . $ key . '>' ; } $ xml .= '</xml>' ; return $ xml ; }
Convert array to xml .
160
6
172
public static function fromXml ( $ xml ) : array { if ( ! $ xml ) { throw new InvalidArgumentException ( 'Convert To Array Error! Invalid Xml!' ) ; } libxml_disable_entity_loader ( true ) ; return json_decode ( json_encode ( simplexml_load_string ( $ xml , 'SimpleXMLElement' , LIBXML_NOCDATA ) , JSON_UNESCAPED_UNICODE ) , true ) ; }
Convert xml to array .
106
6
173
public function getConfig ( $ key = null , $ default = null ) { if ( is_null ( $ key ) ) { return $ this -> config -> all ( ) ; } if ( $ this -> config -> has ( $ key ) ) { return $ this -> config [ $ key ] ; } return $ default ; }
Get service config .
68
4
174
public function cancel ( $ order ) : Collection { $ this -> payload [ 'method' ] = 'alipay.trade.cancel' ; $ this -> payload [ 'biz_content' ] = json_encode ( is_array ( $ order ) ? $ order : [ 'out_trade_no' => $ order ] ) ; $ this -> payload [ 'sign' ] = Support :: generateSign ( $ this -> payload ) ; Events :: dispatch ( Events :: METHOD_CALLED , new Events \ MethodCalled ( 'Alipay' , 'Cancel' , $ this -> gateway , $ this -> payload ) ) ; return Support :: requestApi ( $ this -> payload ) ; }
Cancel an order .
151
5
175
public function success ( ) : Response { Events :: dispatch ( Events :: METHOD_CALLED , new Events \ MethodCalled ( 'Alipay' , 'Success' , $ this -> gateway ) ) ; return Response :: create ( 'success' ) ; }
Reply success to alipay .
56
7
176
public static function getSignContent ( array $ data , $ verify = false ) : string { $ data = self :: encoding ( $ data , $ data [ 'charset' ] ?? 'gb2312' , 'utf-8' ) ; ksort ( $ data ) ; $ stringToBeSigned = '' ; foreach ( $ data as $ k => $ v ) { if ( $ verify && $ k != 'sign' && $ k != 'sign_type' ) { $ stringToBeSigned .= $ k . '=' . $ v . '&' ; } if ( ! $ verify && $ v !== '' && ! is_null ( $ v ) && $ k != 'sign' && '@' != substr ( $ v , 0 , 1 ) ) { $ stringToBeSigned .= $ k . '=' . $ v . '&' ; } } Log :: debug ( 'Alipay Generate Sign Content Before Trim' , [ $ data , $ stringToBeSigned ] ) ; return trim ( $ stringToBeSigned , '&' ) ; }
Get signContent that is to be signed .
237
9
177
protected function setHttpOptions ( ) : self { if ( $ this -> config -> has ( 'http' ) && is_array ( $ this -> config -> get ( 'http' ) ) ) { $ this -> config -> forget ( 'http.base_uri' ) ; $ this -> httpOptions = $ this -> config -> get ( 'http' ) ; } return $ this ; }
Set Http options .
82
5
178
protected function preOrder ( $ payload ) : Collection { $ payload [ 'sign' ] = Support :: generateSign ( $ payload ) ; Events :: dispatch ( Events :: METHOD_CALLED , new Events \ MethodCalled ( 'Wechat' , 'PreOrder' , '' , $ payload ) ) ; return Support :: requestApi ( 'pay/unifiedorder' , $ payload ) ; }
Schedule an order .
85
5
179
public function render ( ) { $ results = '' ; foreach ( $ this -> toArray ( ) as $ column => $ attributes ) { $ results .= $ this -> createField ( $ column , $ attributes ) ; } return $ results ; }
Render the migration to formatted script .
52
7
180
public function parse ( $ schema ) { $ this -> schema = $ schema ; $ parsed = [ ] ; foreach ( $ this -> getSchemas ( ) as $ schemaArray ) { $ column = $ this -> getColumn ( $ schemaArray ) ; $ attributes = $ this -> getAttributes ( $ column , $ schemaArray ) ; $ parsed [ $ column ] = $ attributes ; } return $ parsed ; }
Parse a string to array of formatted schema .
86
10
181
public function getAttributes ( $ column , $ schema ) { $ fields = str_replace ( $ column . ':' , '' , $ schema ) ; return $ this -> hasCustomAttribute ( $ column ) ? $ this -> getCustomAttribute ( $ column ) : explode ( ':' , $ fields ) ; }
Get column attributes .
64
4
182
public function down ( ) { $ results = '' ; foreach ( $ this -> toArray ( ) as $ column => $ attributes ) { $ results .= $ this -> createField ( $ column , $ attributes , 'remove' ) ; } return $ results ; }
Render down migration fields .
56
5
183
public function parse ( $ rules ) { $ this -> rules = $ rules ; $ parsed = [ ] ; foreach ( $ this -> getRules ( ) as $ rulesArray ) { $ column = $ this -> getColumn ( $ rulesArray ) ; $ attributes = $ this -> getAttributes ( $ column , $ rulesArray ) ; $ parsed [ $ column ] = $ attributes ; } return $ parsed ; }
Parse a string to array of formatted rules .
85
10
184
public function getFillable ( ) { if ( ! $ this -> fillable ) { return '[]' ; } $ results = '[' . PHP_EOL ; foreach ( $ this -> getSchemaParser ( ) -> toArray ( ) as $ column => $ value ) { $ results .= "\t\t'{$column}'," . PHP_EOL ; } return $ results . "\t" . ']' ; }
Get the fillable attributes .
93
6
185
public function getCacheRepository ( ) { if ( is_null ( $ this -> cacheRepository ) ) { $ this -> cacheRepository = app ( config ( 'repository.cache.repository' , 'cache' ) ) ; } return $ this -> cacheRepository ; }
Return instance of Cache Repository
63
6
186
protected function serializeCriteria ( ) { try { return serialize ( $ this -> getCriteria ( ) ) ; } catch ( Exception $ e ) { return serialize ( $ this -> getCriteria ( ) -> map ( function ( $ criterion ) { return $ this -> serializeCriterion ( $ criterion ) ; } ) ) ; } }
Serialize the criteria making sure the Closures are taken care of .
73
14
187
protected function serializeCriterion ( $ criterion ) { try { serialize ( $ criterion ) ; return $ criterion ; } catch ( Exception $ e ) { // We want to take care of the closure serialization errors, // other than that we will simply re-throw the exception. if ( $ e -> getMessage ( ) !== "Serialization of 'Closure' is not allowed" ) { throw $ e ; } $ r = new ReflectionObject ( $ criterion ) ; return [ 'hash' => md5 ( ( string ) $ r ) , 'properties' => $ r -> getProperties ( ) , ] ; } }
Serialize single criterion with customized serialization of Closures .
132
12
188
public function versionCompare ( $ frameworkVersion , $ compareVersion , $ operator = null ) { // Lumen (5.5.2) (Laravel Components 5.5.*) $ lumenPattern = '/Lumen \((\d\.\d\.[\d|\*])\)( \(Laravel Components (\d\.\d\.[\d|\*])\))?/' ; if ( preg_match ( $ lumenPattern , $ frameworkVersion , $ matches ) ) { $ frameworkVersion = isset ( $ matches [ 3 ] ) ? $ matches [ 3 ] : $ matches [ 1 ] ; // Prefer Laravel Components version. } return version_compare ( $ frameworkVersion , $ compareVersion , $ operator ) ; }
Version compare function that can compare both Laravel and Lumen versions .
163
14
189
public function getRules ( ) { if ( ! $ this -> rules ) { return '[]' ; } $ results = '[' . PHP_EOL ; foreach ( $ this -> getSchemaParser ( ) -> toArray ( ) as $ column => $ value ) { $ results .= "\t\t'{$column}'\t=>'\t{$value}'," . PHP_EOL ; } return $ results . "\t" . ']' ; }
Get the rules .
102
4
190
public function getValidator ( ) { $ validatorGenerator = new ValidatorGenerator ( [ 'name' => $ this -> name , ] ) ; $ validator = $ validatorGenerator -> getRootNamespace ( ) . '\\' . $ validatorGenerator -> getName ( ) ; return 'use ' . str_replace ( [ "\\" , '/' ] , '\\' , $ validator ) . 'Validator;' ; }
Gets validator full class name
99
7
191
public function getRepository ( ) { $ repositoryGenerator = new RepositoryInterfaceGenerator ( [ 'name' => $ this -> name , ] ) ; $ repository = $ repositoryGenerator -> getRootNamespace ( ) . '\\' . $ repositoryGenerator -> getName ( ) ; return 'use ' . str_replace ( [ "\\" , '/' ] , '\\' , $ repository ) . 'Repository;' ; }
Gets repository full class name
95
6
192
public function getEloquentRepository ( ) { $ repositoryGenerator = new RepositoryEloquentGenerator ( [ 'name' => $ this -> name , ] ) ; $ repository = $ repositoryGenerator -> getRootNamespace ( ) . '\\' . $ repositoryGenerator -> getName ( ) ; return str_replace ( [ "\\" , '/' ] , '\\' , $ repository ) . 'RepositoryEloquent' ; }
Gets eloquent repository full class name
101
8
193
public function validator ( ) { if ( isset ( $ this -> rules ) && ! is_null ( $ this -> rules ) && is_array ( $ this -> rules ) && ! empty ( $ this -> rules ) ) { if ( class_exists ( 'Prettus\Validator\LaravelValidator' ) ) { $ validator = app ( 'Prettus\Validator\LaravelValidator' ) ; if ( $ validator instanceof ValidatorInterface ) { $ validator -> setRules ( $ this -> rules ) ; return $ validator ; } } else { throw new Exception ( trans ( 'repository::packages.prettus_laravel_validation_required' ) ) ; } } return null ; }
Specify Validator class name of Prettus \ Validator \ Contracts \ ValidatorInterface
164
19
194
public function first ( $ columns = [ '*' ] ) { $ this -> applyCriteria ( ) ; $ this -> applyScope ( ) ; $ results = $ this -> model -> first ( $ columns ) ; $ this -> resetModel ( ) ; return $ this -> parserResult ( $ results ) ; }
Retrieve first data of repository
65
6
195
public function find ( $ id , $ columns = [ '*' ] ) { $ this -> applyCriteria ( ) ; $ this -> applyScope ( ) ; $ model = $ this -> model -> findOrFail ( $ id , $ columns ) ; $ this -> resetModel ( ) ; return $ this -> parserResult ( $ model ) ; }
Find data by id
73
4
196
public function findWhereIn ( $ field , array $ values , $ columns = [ '*' ] ) { $ this -> applyCriteria ( ) ; $ this -> applyScope ( ) ; $ model = $ this -> model -> whereIn ( $ field , $ values ) -> get ( $ columns ) ; $ this -> resetModel ( ) ; return $ this -> parserResult ( $ model ) ; }
Find data by multiple values in one field
84
8
197
public function findWhereNotIn ( $ field , array $ values , $ columns = [ '*' ] ) { $ this -> applyCriteria ( ) ; $ this -> applyScope ( ) ; $ model = $ this -> model -> whereNotIn ( $ field , $ values ) -> get ( $ columns ) ; $ this -> resetModel ( ) ; return $ this -> parserResult ( $ model ) ; }
Find data by excluding multiple values in one field
86
9
198
public function whereHas ( $ relation , $ closure ) { $ this -> model = $ this -> model -> whereHas ( $ relation , $ closure ) ; return $ this ; }
Load relation with closure
37
4
199
public function pushCriteria ( $ criteria ) { if ( is_string ( $ criteria ) ) { $ criteria = new $ criteria ; } if ( ! $ criteria instanceof CriteriaInterface ) { throw new RepositoryException ( "Class " . get_class ( $ criteria ) . " must be an instance of Prettus\\Repository\\Contracts\\CriteriaInterface" ) ; } $ this -> criteria -> push ( $ criteria ) ; return $ this ; }
Push Criteria for filter the query
98
7