public function createFileFromContentAsync(
        $share,
        $path,
        $content,
        CreateFileFromContentOptions $options = null
    ) {
        $stream = Psr7\stream_for($content);
        $size = $stream->getSize();

        if ($options == null) {
            $options = new CreateFileFromContentOptions();
        }

        //create the file first
        $promise = $this->createFileAsync($share, $path, $size, $options);

        //then upload the content
        $range = new Range(0, $size - 1);
        $putOptions = new PutFileRangeOptions($options);
        $useTransactionalMD5 = $options->getUseTransactionalMD5();
        if ($size > Resources::MB_IN_BYTES_4) {
            return $promise->then(function ($response) use (
                $share,
                $path,
                $stream,
                $range,
                $putOptions,
                $useTransactionalMD5
            ) {
                return $this->multiplePutRangeConcurrentAsync(
                    $share,
                    $path,
                    $stream,
                    $range,
                    $putOptions,
                    $useTransactionalMD5
                );
            }, null);
        } else {
            return $promise->then(function ($response) use (
                $share,
                $path,
                $stream,
                $range,
                $putOptions
            ) {
                return $this->putFileRangeAsync(
                    $share,
                    $path,
                    $stream,
                    $range,
                    $putOptions
                );
            }, null);
        }
    }

public
function
createFileFromContentAsync
(
$
share
,
$
path
,
$
content
,
CreateFileFromContentOptions
$
options
=
)
{
$
stream
=
Psr7
\
stream_for
(
$
content
)
;
$
size
=
$
stream
->
getSize
(
)
;
if
(
$
options
==
)
{
$
options
=
new
CreateFileFromContentOptions
(
)
;
}
//create the file first
$
promise
=
$
this
->
createFileAsync
(
$
share
,
$
path
,
$
size
,
$
options
)
;
//then upload the content
$
range
=
new
Range
(
0
,
$
size
1
)
;
$
putOptions
=
new
PutFileRangeOptions
(
$
options
)
;
$
useTransactionalMD5
=
$
options
->
getUseTransactionalMD5
(
)
;
if
(
$
size
>
Resources
::
MB_IN_BYTES_4
)
{
return
$
promise
->
then
(
function
(
$
response
)
use
(
$
share
,
$
path
,
$
stream
,
$
range
,
$
putOptions
,
$
useTransactionalMD5
)
{
return
$
this
->
multiplePutRangeConcurrentAsync
(
$
share
,
$
path
,
$
stream
,
$
range
,
$
putOptions
,
$
useTransactionalMD5
)
;
}
,
)
;
}
else
{
return
$
promise
->
then
(
function
(
$
response
)
use
(
$
share
,
$
path
,
$
stream
,
$
range
,
$
putOptions
)
{
return
$
this
->
putFileRangeAsync
(
$
share
,
$
path
,
$
stream
,
$
range
,
$
putOptions
)
;
}
,
)
;
}
}

Creates a promise to create a file from a provided content.

@param  string                            $share   the share name
@param  string                            $path    the path of the file
@param  StreamInterface|resource|string   $content the content used to
create the file
@param  CreateFileFromContentOptions|null $options optional parameters

@return \GuzzleHttp\Promise\PromiseInterface

Creates a promise to create a file from a provided content .


public function clearFileRange(
        $share,
        $path,
        Range $range,
        FileServiceOptions $options = null
    ) {
        $this->clearFileRangeAsync($share, $path, $range, $options)->wait();
    }

public function clearFileRange ( $ share , $ path , Range $ range , FileServiceOptions $ options = null ) { $ this -> clearFileRangeAsync ( $ share , $ path , $ range , $ options ) -> wait ( ) ; }

Clears range of bytes of a file. If the specified range is not 512-byte
aligned, the operation will write zeros to the start or end of the range
that is not 512-byte aligned and free the rest of the range inside that
is 512-byte aligned.

@param  string                  $share   The share name.
@param  string                  $path    The path of the file.
@param  Range                   $range   The range in the file to
be cleared.
@param  FileServiceOptions|null $options The optional parameters.

@return void

@see https://docs.microsoft.com/en-us/rest/api/storageservices/put-range

Clears range of bytes of a file . If the specified range is not 512 - byte aligned the operation will write zeros to the start or end of the range that is not 512 - byte aligned and free the rest of the range inside that is 512 - byte aligned .


public function clearFileRangeAsync(
        $share,
        $path,
        Range $range,
        FileServiceOptions $options = null
    ) {
        Validate::canCastAsString($share, 'share');
        Validate::canCastAsString($path, 'path');
        Validate::notNullOrEmpty($path, 'path');
        Validate::notNullOrEmpty($share, 'share');

        $method      = Resources::HTTP_PUT;
        $headers     = array();
        $queryParams = array();
        $postParams  = array();
        $path        = $this->createPath($share, $path);

        if (is_null($options)) {
            $options = new FileServiceOptions();
        }

        $this->addOptionalHeader(
            $headers,
            Resources::X_MS_RANGE,
            $range->getRangeString()
        );

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_TIMEOUT,
            $options->getTimeout()
        );

        $this->addOptionalHeader(
            $headers,
            Resources::X_MS_WRITE,
            'Clear'
        );

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_COMP,
            'range'
        );

        return $this->sendAsync(
            $method,
            $headers,
            $queryParams,
            $postParams,
            $path,
            Resources::STATUS_CREATED,
            Resources::EMPTY_STRING,
            $options
        );
    }

public function clearFileRangeAsync ( $ share , $ path , Range $ range , FileServiceOptions $ options = null ) { Validate :: canCastAsString ( $ share , 'share' ) ; Validate :: canCastAsString ( $ path , 'path' ) ; Validate :: notNullOrEmpty ( $ path , 'path' ) ; Validate :: notNullOrEmpty ( $ share , 'share' ) ; $ method = Resources :: HTTP_PUT ; $ headers = array ( ) ; $ queryParams = array ( ) ; $ postParams = array ( ) ; $ path = $ this -> createPath ( $ share , $ path ) ; if ( is_null ( $ options ) ) { $ options = new FileServiceOptions ( ) ; } $ this -> addOptionalHeader ( $ headers , Resources :: X_MS_RANGE , $ range -> getRangeString ( ) ) ; $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_TIMEOUT , $ options -> getTimeout ( ) ) ; $ this -> addOptionalHeader ( $ headers , Resources :: X_MS_WRITE , 'Clear' ) ; $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_COMP , 'range' ) ; return $ this -> sendAsync ( $ method , $ headers , $ queryParams , $ postParams , $ path , Resources :: STATUS_CREATED , Resources :: EMPTY_STRING , $ options ) ; }

Creates promise to clear range of bytes of a file. If the specified range
is not 512-byte aligned, the operation will write zeros to the start or
end of the range that is not 512-byte aligned and free the rest of the
range inside that is 512-byte aligned.

@param  string                  $share   The share name.
@param  string                  $path    The path of the file.
@param  Range                   $range   The range in the file to
be cleared.
@param  FileServiceOptions|null $options The optional parameters.

@return \GuzzleHttp\Promise\PromiseInterface

@see https://docs.microsoft.com/en-us/rest/api/storageservices/put-range

Creates promise to clear range of bytes of a file . If the specified range is not 512 - byte aligned the operation will write zeros to the start or end of the range that is not 512 - byte aligned and free the rest of the range inside that is 512 - byte aligned .


public function listFileRange(
        $share,
        $path,
        Range $range = null,
        FileServiceOptions $options = null
    ) {
        return $this->listFileRangeAsync($share, $path, $range, $options)->wait();
    }

public function listFileRange ( $ share , $ path , Range $ range = null , FileServiceOptions $ options = null ) { return $ this -> listFileRangeAsync ( $ share , $ path , $ range , $ options ) -> wait ( ) ; }

Lists range of bytes of a file.

@param  string                  $share   The share name.
@param  string                  $path    The path of the file.
@param  Range                   $range   The range in the file to
be listed.
@param  FileServiceOptions|null $options The optional parameters.

@return ListFileRangesResult

@see https://docs.microsoft.com/en-us/rest/api/storageservices/list-ranges


public function listFileRangeAsync(
        $share,
        $path,
        Range $range = null,
        FileServiceOptions $options = null
    ) {
        Validate::canCastAsString($share, 'share');
        Validate::canCastAsString($path, 'path');
        Validate::notNullOrEmpty($path, 'path');
        Validate::notNullOrEmpty($share, 'share');

        $method      = Resources::HTTP_GET;
        $headers     = array();
        $queryParams = array();
        $postParams  = array();
        $path        = $this->createPath($share, $path);

        if (is_null($options)) {
            $options = new FileServiceOptions();
        }

        if ($range != null) {
            $this->addOptionalHeader(
                $headers,
                Resources::X_MS_RANGE,
                $range->getRangeString()
            );
        }

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_COMP,
            'rangelist'
        );

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_TIMEOUT,
            $options->getTimeout()
        );

        $dataSerializer = $this->dataSerializer;

        return $this->sendAsync(
            $method,
            $headers,
            $queryParams,
            $postParams,
            $path,
            Resources::STATUS_OK,
            Resources::EMPTY_STRING,
            $options
        )->then(function ($response) use ($dataSerializer) {
            $responseHeaders = HttpFormatter::formatHeaders($response->getHeaders());
            $parsed = $dataSerializer->unserialize($response->getBody());
            return ListFileRangesResult::create($responseHeaders, $parsed);
        }, null);
    }

public function listFileRangeAsync ( $ share , $ path , Range $ range = null , FileServiceOptions $ options = null ) { Validate :: canCastAsString ( $ share , 'share' ) ; Validate :: canCastAsString ( $ path , 'path' ) ; Validate :: notNullOrEmpty ( $ path , 'path' ) ; Validate :: notNullOrEmpty ( $ share , 'share' ) ; $ method = Resources :: HTTP_GET ; $ headers = array ( ) ; $ queryParams = array ( ) ; $ postParams = array ( ) ; $ path = $ this -> createPath ( $ share , $ path ) ; if ( is_null ( $ options ) ) { $ options = new FileServiceOptions ( ) ; } if ( $ range != null ) { $ this -> addOptionalHeader ( $ headers , Resources :: X_MS_RANGE , $ range -> getRangeString ( ) ) ; } $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_COMP , 'rangelist' ) ; $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_TIMEOUT , $ options -> getTimeout ( ) ) ; $ dataSerializer = $ this -> dataSerializer ; return $ this -> sendAsync ( $ method , $ headers , $ queryParams , $ postParams , $ path , Resources :: STATUS_OK , Resources :: EMPTY_STRING , $ options ) -> then ( function ( $ response ) use ( $ dataSerializer ) { $ responseHeaders = HttpFormatter :: formatHeaders ( $ response -> getHeaders ( ) ) ; $ parsed = $ dataSerializer -> unserialize ( $ response -> getBody ( ) ) ; return ListFileRangesResult :: create ( $ responseHeaders , $ parsed ) ; } , null ) ; }

Creates promise to list range of bytes of a file.

@param  string                  $share   The share name.
@param  string                  $path    The path of the file.
@param  Range                   $range   The range in the file to
be listed.
@param  FileServiceOptions|null $options The optional parameters.

@return \GuzzleHttp\Promise\PromiseInterface

@see https://docs.microsoft.com/en-us/rest/api/storageservices/list-ranges

Creates promise to list range of bytes of a file .


public function abortCopy(
        $share,
        $path,
        $copyID,
        FileServiceOptions $options = null
    ) {
        return $this->abortCopyAsync(
            $share,
            $path,
            $copyID,
            $options
        )->wait();
    }

public function abortCopy ( $ share , $ path , $ copyID , FileServiceOptions $ options = null ) { return $ this -> abortCopyAsync ( $ share , $ path , $ copyID , $ options ) -> wait ( ) ; }

Abort a file copy operation

@param string                  $share   name of the share
@param string                  $path    path of the file
@param string                  $copyID  copy operation identifier.
@param FileServiceOptions|null $options optional parameters

@return void

@see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-file


public function abortCopyAsync(
        $share,
        $path,
        $copyID,
        FileServiceOptions $options = null
    ) {
        Validate::canCastAsString($share, 'share');
        Validate::canCastAsString($path, 'path');
        Validate::canCastAsString($copyID, 'copyID');
        Validate::notNullOrEmpty($share, 'share');
        Validate::notNullOrEmpty($path, 'path');
        Validate::notNullOrEmpty($copyID, 'copyID');

        $method      = Resources::HTTP_PUT;
        $headers     = array();
        $postParams  = array();
        $queryParams = array();
        $path        = $this->createPath($share, $path);

        if (is_null($options)) {
            $options = new FileServiceOptions();
        }

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_TIMEOUT,
            $options->getTimeout()
        );

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_COMP,
            'copy'
        );

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_COPY_ID,
            $copyID
        );

        $this->addOptionalHeader(
            $headers,
            Resources::X_MS_COPY_ACTION,
            'abort'
        );

        return $this->sendAsync(
            $method,
            $headers,
            $queryParams,
            $postParams,
            $path,
            Resources::STATUS_NO_CONTENT,
            Resources::EMPTY_STRING,
            $options
        );
    }

public function abortCopyAsync ( $ share , $ path , $ copyID , FileServiceOptions $ options = null ) { Validate :: canCastAsString ( $ share , 'share' ) ; Validate :: canCastAsString ( $ path , 'path' ) ; Validate :: canCastAsString ( $ copyID , 'copyID' ) ; Validate :: notNullOrEmpty ( $ share , 'share' ) ; Validate :: notNullOrEmpty ( $ path , 'path' ) ; Validate :: notNullOrEmpty ( $ copyID , 'copyID' ) ; $ method = Resources :: HTTP_PUT ; $ headers = array ( ) ; $ postParams = array ( ) ; $ queryParams = array ( ) ; $ path = $ this -> createPath ( $ share , $ path ) ; if ( is_null ( $ options ) ) { $ options = new FileServiceOptions ( ) ; } $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_TIMEOUT , $ options -> getTimeout ( ) ) ; $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_COMP , 'copy' ) ; $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_COPY_ID , $ copyID ) ; $ this -> addOptionalHeader ( $ headers , Resources :: X_MS_COPY_ACTION , 'abort' ) ; return $ this -> sendAsync ( $ method , $ headers , $ queryParams , $ postParams , $ path , Resources :: STATUS_NO_CONTENT , Resources :: EMPTY_STRING , $ options ) ; }

Creates promise to abort a file copy operation

@param string                  $share   name of the share
@param string                  $path    path of the file
@param string                  $copyID  copy operation identifier.
@param FileServiceOptions|null $options optional parameters

@return void

@see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-file


public function setType($type)
    {
        Validate::isTrue(
            BatchOperationType::isValid($type),
            Resources::INVALID_BO_TYPE_MSG
        );

        $this->_type = $type;
    }

public function setType ( $ type ) { Validate :: isTrue ( BatchOperationType :: isValid ( $ type ) , Resources :: INVALID_BO_TYPE_MSG ) ; $ this -> _type = $ type ; }

Sets operation type.

@param string $type The operation type. Must be valid type.

@return void


public function addParameter($name, $value)
    {
        Validate::isTrue(
            BatchOperationParameterName::isValid($name),
            Resources::INVALID_BO_PN_MSG
        );
        $this->_params[$name] = $value;
    }

public function addParameter ( $ name , $ value ) { Validate :: isTrue ( BatchOperationParameterName :: isValid ( $ name ) , Resources :: INVALID_BO_PN_MSG ) ; $ this -> _params [ $ name ] = $ value ; }

Adds or sets parameter for the operation.

@param string $name  The param name. Must be valid name.
@param mixed  $value The param value.

@return void

Adds or sets parameter for the operation .


private static function _constructResponses($body, IMimeReaderWriter $mimeSerializer)
    {
        $responses = array();
        $parts     = $mimeSerializer->decodeMimeMultipart($body);
        // Decrease the count of parts to remove the batch response body and just
        // include change sets response body. We may need to undo this action in
        // case that batch response body has useful info.
        $count = count($parts);

        for ($i = 0; $i < $count; $i++) {
            $response = new \stdClass();

            // Split lines
            $lines    = preg_split("/\\r\\n|\\r|\\n/", $parts[$i]);
            // Version Status Reason
            $statusTokens = explode(' ', $lines[0], 3);
            $response->version = $statusTokens[0];
            $response->statusCode = $statusTokens[1];
            $response->reason = $statusTokens[2];

            $headers = array();
            $j       = 1;
            do {
                $headerLine = $lines[$j++];
                $headerTokens = explode(':', $headerLine);
                $headers[trim($headerTokens[0])] =
                    isset($headerTokens[1]) ? trim($headerTokens[1]) : null;
            } while (Resources::EMPTY_STRING != $headerLine);
            $response->headers = $headers;
            $response->body = implode(PHP_EOL, array_slice($lines, $j));
            $responses[] = $response;
        }

        return $responses;
    }

Creates a array of responses from the batch response body.

@param string            $body           The HTTP response body.
@param IMimeReaderWriter $mimeSerializer The MIME reader and writer.

@return array

Creates a array of responses from the batch response body .


private static function _compareUsingContentId($r1, $r2)
    {
        $h1 = array_change_key_case($r1->headers);
        $h2 = array_change_key_case($r2->headers);
        $c1 = Utilities::tryGetValue($h1, Resources::CONTENT_ID, 0);
        $c2 = Utilities::tryGetValue($h2, Resources::CONTENT_ID, 0);

        return intval($c1) >= intval($c2);
    }

private static function _compareUsingContentId ( $ r1 , $ r2 ) { $ h1 = array_change_key_case ( $ r1 -> headers ) ; $ h2 = array_change_key_case ( $ r2 -> headers ) ; $ c1 = Utilities :: tryGetValue ( $ h1 , Resources :: CONTENT_ID , 0 ) ; $ c2 = Utilities :: tryGetValue ( $ h2 , Resources :: CONTENT_ID , 0 ) ; return intval ( $ c1 ) >= intval ( $ c2 ) ; }

Compares between two responses by Content-ID header.

@param mixed $r1 The first response object.
@param mixed $r2 The second response object.

@return boolean

Compares between two responses by Content - ID header .


public static function create(
        $body,
        array $operations,
        array $contexts,
        IODataReaderWriter $odataSerializer,
        IMimeReaderWriter $mimeSerializer
    ) {
        $result       = new BatchResult();
        $responses    = self::_constructResponses($body, $mimeSerializer);
        $callbackName = __CLASS__ . '::_compareUsingContentId';
        $count        = count($responses);
        $entries      = array();
        // Sort $responses based on Content-ID so they match order of $operations.
        uasort($responses, $callbackName);

        for ($i = 0; $i < $count; $i++) {
            $context   = $contexts[$i];
            $response  = $responses[$i];
            $operation = $operations[$i];
            $type      = $operation->getType();
            $body      = $response->body;
            $headers   = HttpFormatter::formatHeaders($response->headers);

            //Throw the error directly if error occurs in the batch operation.
            ServiceRestProxy::throwIfError(
                new Response(
                    $response->statusCode,
                    $response->headers,
                    $response->body,
                    $response->version,
                    $response->reason
                ),
                $context->getStatusCodes()
            );

            switch ($type) {
                case BatchOperationType::INSERT_ENTITY_OPERATION:
                    $entries[] = InsertEntityResult::create(
                        $body,
                        $headers,
                        $odataSerializer
                    );
                    break;
                case BatchOperationType::UPDATE_ENTITY_OPERATION:
                case BatchOperationType::MERGE_ENTITY_OPERATION:
                case BatchOperationType::INSERT_REPLACE_ENTITY_OPERATION:
                case BatchOperationType::INSERT_MERGE_ENTITY_OPERATION:
                    $entries[] = UpdateEntityResult::create($headers);
                    break;
                case BatchOperationType::DELETE_ENTITY_OPERATION:
                    $entries[] = Resources::BATCH_ENTITY_DEL_MSG;
                    break;
                default:
                    throw new \InvalidArgumentException();
            }
        }

        $result->setEntries($entries);

        return $result;
    }

Creates BatchResult object.

@param string             $body            The HTTP response body.
@param array              $operations      The batch operations.
@param array              $contexts        The batch operations context.
@param IODataReaderWriter $odataSerializer The OData reader and writer.
@param IMimeReaderWriter  $mimeSerializer  The MIME reader and writer.

@return \MicrosoftAzure\Storage\Table\Models\BatchResult

@throws \InvalidArgumentException


private static function getInstanceAttributes($targetObject, array $methodArray)
    {
        foreach ($methodArray as $method) {
            if ($method->name == 'getAttributes') {
                $classProperty = $method->invoke($targetObject);
                return $classProperty;
            }
        }
        return null;
    }

private static function getInstanceAttributes ( $ targetObject , array $ methodArray ) { foreach ( $ methodArray as $ method ) { if ( $ method -> name == 'getAttributes' ) { $ classProperty = $ method -> invoke ( $ targetObject ) ; return $ classProperty ; } } return null ; }

Gets the attributes of a specified object if get attributes
method is exposed.

@param object $targetObject The target object.
@param array  $methodArray  The array of method of the target object.

@return mixed

Gets the attributes of a specified object if get attributes method is exposed .


public function serialize(array $array, array $properties = null)
    {
        $xmlVersion   = '1.0';
        $xmlEncoding  = 'UTF-8';
        $standalone   = Utilities::tryGetValue($properties, self::STANDALONE);
        $defaultTag   = Utilities::tryGetValue($properties, self::DEFAULT_TAG);
        $rootName     = Utilities::tryGetValue($properties, self::ROOT_NAME);
        $docNamespace = Utilities::tryGetValue(
            $array,
            Resources::XTAG_NAMESPACE,
            null
        );

        if (!is_array($array)) {
            return false;
        }

        $xmlw = new \XmlWriter();
        $xmlw->openMemory();
        $xmlw->setIndent(true);
        $xmlw->startDocument($xmlVersion, $xmlEncoding, $standalone);

        if (is_null($docNamespace)) {
            $xmlw->startElement($rootName);
        } else {
            foreach ($docNamespace as $uri => $prefix) {
                $xmlw->startElementNS($prefix, $rootName, $uri);
                break;
            }
        }

        unset($array[Resources::XTAG_NAMESPACE]);
        self::arr2xml($xmlw, $array, $defaultTag);

        $xmlw->endElement();

        return $xmlw->outputMemory(true);
    }

public function serialize ( array $ array , array $ properties = null ) { $ xmlVersion = '1.0' ; $ xmlEncoding = 'UTF-8' ; $ standalone = Utilities :: tryGetValue ( $ properties , self :: STANDALONE ) ; $ defaultTag = Utilities :: tryGetValue ( $ properties , self :: DEFAULT_TAG ) ; $ rootName = Utilities :: tryGetValue ( $ properties , self :: ROOT_NAME ) ; $ docNamespace = Utilities :: tryGetValue ( $ array , Resources :: XTAG_NAMESPACE , null ) ; if ( ! is_array ( $ array ) ) { return false ; } $ xmlw = new \ XmlWriter ( ) ; $ xmlw -> openMemory ( ) ; $ xmlw -> setIndent ( true ) ; $ xmlw -> startDocument ( $ xmlVersion , $ xmlEncoding , $ standalone ) ; if ( is_null ( $ docNamespace ) ) { $ xmlw -> startElement ( $ rootName ) ; } else { foreach ( $ docNamespace as $ uri => $ prefix ) { $ xmlw -> startElementNS ( $ prefix , $ rootName , $ uri ) ; break ; } } unset ( $ array [ Resources :: XTAG_NAMESPACE ] ) ; self :: arr2xml ( $ xmlw , $ array , $ defaultTag ) ; $ xmlw -> endElement ( ) ; return $ xmlw -> outputMemory ( true ) ; }

Serializes given array. The array indices must be string to use them as
as element name.

@param array $array      The object to serialize represented in array.
@param array $properties The used properties in the serialization process.

@return string

Serializes given array . The array indices must be string to use them as as element name .


public static function create(array $parsedResponse)
    {
        Validate::hasKey(
            Resources::XTAG_ALLOWED_ORIGINS,
            'parsedResponse',
            $parsedResponse
        );
        Validate::hasKey(
            Resources::XTAG_ALLOWED_METHODS,
            'parsedResponse',
            $parsedResponse
        );
        Validate::hasKey(
            Resources::XTAG_ALLOWED_HEADERS,
            'parsedResponse',
            $parsedResponse
        );
        Validate::hasKey(
            Resources::XTAG_EXPOSED_HEADERS,
            'parsedResponse',
            $parsedResponse
        );
        Validate::hasKey(
            Resources::XTAG_MAX_AGE_IN_SECONDS,
            'parsedResponse',
            $parsedResponse
        );

        // Get the values from the parsed response.
        $allowedOrigins  = array_filter(explode(
            ',',
            $parsedResponse[Resources::XTAG_ALLOWED_ORIGINS]
        ));
        $allowedMethods  = array_filter(explode(
            ',',
            $parsedResponse[Resources::XTAG_ALLOWED_METHODS]
        ));
        $allowedHeaders  = array_filter(explode(
            ',',
            $parsedResponse[Resources::XTAG_ALLOWED_HEADERS]
        ));
        $exposedHeaders  = array_filter(explode(
            ',',
            $parsedResponse[Resources::XTAG_EXPOSED_HEADERS]
        ));
        $maxAgeInSeconds = intval(
            $parsedResponse[Resources::XTAG_MAX_AGE_IN_SECONDS]
        );

        return new CORS(
            $allowedOrigins,
            $allowedMethods,
            $allowedHeaders,
            $exposedHeaders,
            $maxAgeInSeconds
        );
    }

Create an instance with parsed XML response with 'CORS' root.

@param  array  $parsedResponse The response used to create an instance.

@internal

@return CORS

Create an instance with parsed XML response with CORS root .


public function getServicePropertiesAsync(
        ServiceOptions $options = null
    ) {
        $method      = Resources::HTTP_GET;
        $headers     = array();
        $queryParams = array();
        $postParams  = array();
        $path        = Resources::EMPTY_STRING;

        if (is_null($options)) {
            $options = new ServiceOptions();
        }

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_REST_TYPE,
            'service'
        );
        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_COMP,
            'properties'
        );

        $dataSerializer = $this->dataSerializer;

        return $this->sendAsync(
            $method,
            $headers,
            $queryParams,
            $postParams,
            $path,
            Resources::STATUS_OK,
            Resources::EMPTY_STRING,
            $options
        )->then(function ($response) use ($dataSerializer) {
            $parsed = $dataSerializer->unserialize($response->getBody());
            return GetServicePropertiesResult::create($parsed);
        }, null);
    }

public function getServicePropertiesAsync ( ServiceOptions $ options = null ) { $ method = Resources :: HTTP_GET ; $ headers = array ( ) ; $ queryParams = array ( ) ; $ postParams = array ( ) ; $ path = Resources :: EMPTY_STRING ; if ( is_null ( $ options ) ) { $ options = new ServiceOptions ( ) ; } $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_REST_TYPE , 'service' ) ; $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_COMP , 'properties' ) ; $ dataSerializer = $ this -> dataSerializer ; return $ this -> sendAsync ( $ method , $ headers , $ queryParams , $ postParams , $ path , Resources :: STATUS_OK , Resources :: EMPTY_STRING , $ options ) -> then ( function ( $ response ) use ( $ dataSerializer ) { $ parsed = $ dataSerializer -> unserialize ( $ response -> getBody ( ) ) ; return GetServicePropertiesResult :: create ( $ parsed ) ; } , null ) ; }

Creates promise to get the properties of the service.

@param ServiceOptions $options The optional parameters.

@return \GuzzleHttp\Promise\PromiseInterface

@see http://msdn.microsoft.com/en-us/library/windowsazure/hh452239.aspx

Creates promise to get the properties of the service .


public function setServiceProperties(
        ServiceProperties $serviceProperties,
        ServiceOptions $options = null
    ) {
        $this->setServicePropertiesAsync($serviceProperties, $options)->wait();
    }

public function setServiceProperties ( ServiceProperties $ serviceProperties , ServiceOptions $ options = null ) { $ this -> setServicePropertiesAsync ( $ serviceProperties , $ options ) -> wait ( ) ; }

Sets the properties of the service.

It's recommended to use getServiceProperties, alter the returned object and
then use setServiceProperties with this altered object.

@param ServiceProperties $serviceProperties The service properties.
@param ServiceOptions    $options           The optional parameters.

@return void

@see http://msdn.microsoft.com/en-us/library/windowsazure/hh452235.aspx


public function setServicePropertiesAsync(
        ServiceProperties $serviceProperties,
        ServiceOptions $options = null
    ) {
        Validate::isTrue(
            $serviceProperties instanceof ServiceProperties,
            Resources::INVALID_SVC_PROP_MSG
        );

        $method      = Resources::HTTP_PUT;
        $headers     = array();
        $queryParams = array();
        $postParams  = array();
        $path        = Resources::EMPTY_STRING;
        $body        = $serviceProperties->toXml($this->dataSerializer);

        if (is_null($options)) {
            $options = new ServiceOptions();
        }

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_REST_TYPE,
            'service'
        );
        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_COMP,
            'properties'
        );
        $this->addOptionalHeader(
            $headers,
            Resources::CONTENT_TYPE,
            Resources::URL_ENCODED_CONTENT_TYPE
        );

        $options->setLocationMode(LocationMode::PRIMARY_ONLY);

        return $this->sendAsync(
            $method,
            $headers,
            $queryParams,
            $postParams,
            $path,
            Resources::STATUS_ACCEPTED,
            $body,
            $options
        );
    }

public function setServicePropertiesAsync ( ServiceProperties $ serviceProperties , ServiceOptions $ options = null ) { Validate :: isTrue ( $ serviceProperties instanceof ServiceProperties , Resources :: INVALID_SVC_PROP_MSG ) ; $ method = Resources :: HTTP_PUT ; $ headers = array ( ) ; $ queryParams = array ( ) ; $ postParams = array ( ) ; $ path = Resources :: EMPTY_STRING ; $ body = $ serviceProperties -> toXml ( $ this -> dataSerializer ) ; if ( is_null ( $ options ) ) { $ options = new ServiceOptions ( ) ; } $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_REST_TYPE , 'service' ) ; $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_COMP , 'properties' ) ; $ this -> addOptionalHeader ( $ headers , Resources :: CONTENT_TYPE , Resources :: URL_ENCODED_CONTENT_TYPE ) ; $ options -> setLocationMode ( LocationMode :: PRIMARY_ONLY ) ; return $ this -> sendAsync ( $ method , $ headers , $ queryParams , $ postParams , $ path , Resources :: STATUS_ACCEPTED , $ body , $ options ) ; }

Creates the promise to set the properties of the service.

It's recommended to use getServiceProperties, alter the returned object and
then use setServiceProperties with this altered object.

@param ServiceProperties $serviceProperties The service properties.
@param ServiceOptions    $options           The optional parameters.

@return \GuzzleHttp\Promise\PromiseInterface

@see http://msdn.microsoft.com/en-us/library/windowsazure/hh452235.aspx

Creates the promise to set the properties of the service .


public function getServiceStatsAsync(ServiceOptions $options = null)
    {
        $method      = Resources::HTTP_GET;
        $headers     = array();
        $queryParams = array();
        $postParams  = array();
        $path        = Resources::EMPTY_STRING;

        if (is_null($options)) {
            $options = new ServiceOptions();
        }

        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_REST_TYPE,
            'service'
        );
        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_COMP,
            'stats'
        );

        $dataSerializer = $this->dataSerializer;

        $options->setLocationMode(LocationMode::SECONDARY_ONLY);

        return $this->sendAsync(
            $method,
            $headers,
            $queryParams,
            $postParams,
            $path,
            Resources::STATUS_OK,
            Resources::EMPTY_STRING,
            $options
        )->then(function ($response) use ($dataSerializer) {
            $parsed = $dataSerializer->unserialize($response->getBody());
            return GetServiceStatsResult::create($parsed);
        }, null);
    }

public function getServiceStatsAsync ( ServiceOptions $ options = null ) { $ method = Resources :: HTTP_GET ; $ headers = array ( ) ; $ queryParams = array ( ) ; $ postParams = array ( ) ; $ path = Resources :: EMPTY_STRING ; if ( is_null ( $ options ) ) { $ options = new ServiceOptions ( ) ; } $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_REST_TYPE , 'service' ) ; $ this -> addOptionalQueryParam ( $ queryParams , Resources :: QP_COMP , 'stats' ) ; $ dataSerializer = $ this -> dataSerializer ; $ options -> setLocationMode ( LocationMode :: SECONDARY_ONLY ) ; return $ this -> sendAsync ( $ method , $ headers , $ queryParams , $ postParams , $ path , Resources :: STATUS_OK , Resources :: EMPTY_STRING , $ options ) -> then ( function ( $ response ) use ( $ dataSerializer ) { $ parsed = $ dataSerializer -> unserialize ( $ response -> getBody ( ) ) ; return GetServiceStatsResult :: create ( $ parsed ) ; } , null ) ; }

Creates promise that retrieves statistics related to replication for the
service. The operation will only be sent to secondary location endpoint.

@param  ServiceOptions|null $options The options this operation sends with.

@return \GuzzleHttp\Promise\PromiseInterface

Creates promise that retrieves statistics related to replication for the service . The operation will only be sent to secondary location endpoint .


public static function create(array $parsedResponse, $location = '')
    {
        $result               = new ListQueuesResult();
        $serviceEndpoint      = Utilities::tryGetKeysChainValue(
            $parsedResponse,
            Resources::XTAG_ATTRIBUTES,
            Resources::XTAG_SERVICE_ENDPOINT
        );
        $result->setAccountName(Utilities::tryParseAccountNameFromUrl(
            $serviceEndpoint
        ));
        $result->setPrefix(Utilities::tryGetValue(
            $parsedResponse,
            Resources::QP_PREFIX
        ));
        $result->setMarker(Utilities::tryGetValue(
            $parsedResponse,
            Resources::QP_MARKER
        ));

        $nextMarker = Utilities::tryGetValue($parsedResponse, Resources::QP_NEXT_MARKER);

        if ($nextMarker != null) {
            $result->setContinuationToken(
                new MarkerContinuationToken(
                    $nextMarker,
                    $location
                )
            );
        }

        $result->setMaxResults(Utilities::tryGetValue(
            $parsedResponse,
            Resources::QP_MAX_RESULTS
        ));
        $queues      = array();
        $rawQueues            = array();

        if (!empty($parsedResponse['Queues'])) {
            $rawQueues = Utilities::getArray($parsedResponse['Queues']['Queue']);
        }

        foreach ($rawQueues as $value) {
            $queue    = new Queue($value['Name'], $serviceEndpoint . $value['Name']);
            $metadata = Utilities::tryGetValue($value, Resources::QP_METADATA);
            $queue->setMetadata(is_null($metadata) ? array() : $metadata);
            $queues[] = $queue;
        }
        $result->setQueues($queues);
        return $result;
    }

public static function create ( array $ parsedResponse , $ location = '' ) { $ result = new ListQueuesResult ( ) ; $ serviceEndpoint = Utilities :: tryGetKeysChainValue ( $ parsedResponse , Resources :: XTAG_ATTRIBUTES , Resources :: XTAG_SERVICE_ENDPOINT ) ; $ result -> setAccountName ( Utilities :: tryParseAccountNameFromUrl ( $ serviceEndpoint ) ) ; $ result -> setPrefix ( Utilities :: tryGetValue ( $ parsedResponse , Resources :: QP_PREFIX ) ) ; $ result -> setMarker ( Utilities :: tryGetValue ( $ parsedResponse , Resources :: QP_MARKER ) ) ; $ nextMarker = Utilities :: tryGetValue ( $ parsedResponse , Resources :: QP_NEXT_MARKER ) ; if ( $ nextMarker != null ) { $ result -> setContinuationToken ( new MarkerContinuationToken ( $ nextMarker , $ location ) ) ; } $ result -> setMaxResults ( Utilities :: tryGetValue ( $ parsedResponse , Resources :: QP_MAX_RESULTS ) ) ; $ queues = array ( ) ; $ rawQueues = array ( ) ; if ( ! empty ( $ parsedResponse [ 'Queues' ] ) ) { $ rawQueues = Utilities :: getArray ( $ parsedResponse [ 'Queues' ] [ 'Queue' ] ) ; } foreach ( $ rawQueues as $ value ) { $ queue = new Queue ( $ value [ 'Name' ] , $ serviceEndpoint . $ value [ 'Name' ] ) ; $ metadata = Utilities :: tryGetValue ( $ value , Resources :: QP_METADATA ) ; $ queue -> setMetadata ( is_null ( $ metadata ) ? array ( ) : $ metadata ) ; $ queues [ ] = $ queue ; } $ result -> setQueues ( $ queues ) ; return $ result ; }

Creates ListQueuesResult object from parsed XML response.

@param array  $parsedResponse XML response parsed into array.
@param string $location       Contains the location for the previous
request.

@internal

@return ListQueuesResult

Creates ListQueuesResult object from parsed XML response .


protected function setQueues(array $queues)
    {
        $this->_queues = array();
        foreach ($queues as $queue) {
            $this->_queues[] = clone $queue;
        }
    }

protected function setQueues ( array $ queues ) { $ this -> _queues = array ( ) ; foreach ( $ queues as $ queue ) { $ this -> _queues [ ] = clone $ queue ; } }

Sets queues.

@param array $queues list of queues

@internal

@return void


public static function tryGetSecondaryEndpointFromPrimaryEndpoint($uri)
    {
        $splitTokens = explode('.', $uri);
        if (count($splitTokens) > 0 && $splitTokens[0] != '') {
            $schemaAccountToken = $splitTokens[0];
            $schemaAccountSplitTokens = explode('/', $schemaAccountToken);
            if (count($schemaAccountSplitTokens) > 0 &&
                $schemaAccountSplitTokens[0] != '') {
                $accountName = $schemaAccountSplitTokens[
                    count($schemaAccountSplitTokens) - 1
                ];
                $schemaAccountSplitTokens[count($schemaAccountSplitTokens) - 1] =
                    $accountName . Resources::SECONDARY_STRING;

                $splitTokens[0] = implode('/', $schemaAccountSplitTokens);
                $secondaryUri = implode('.', $splitTokens);
                return $secondaryUri;
            }
        }
        return null;
    }

Parse secondary endpoint url string from a primary endpoint url.

Return null if the primary endpoint url is invalid.

@param string $uri The primary endpoint url string.

@return null|string

Parse secondary endpoint url string from a primary endpoint url .


public static function serialize(
        array $array,
        $rootName,
        $defaultTag = null,
        $standalone = null
    ) {
        $xmlVersion  = '1.0';
        $xmlEncoding = 'UTF-8';

        if (!is_array($array)) {
            return false;
        }

        $xmlw = new \XmlWriter();
        $xmlw->openMemory();
        $xmlw->startDocument($xmlVersion, $xmlEncoding, $standalone);

        $xmlw->startElement($rootName);

        self::_arr2xml($xmlw, $array, $defaultTag);

        $xmlw->endElement();

        return $xmlw->outputMemory(true);
    }

public static function serialize ( array $ array , $ rootName , $ defaultTag = null , $ standalone = null ) { $ xmlVersion = '1.0' ; $ xmlEncoding = 'UTF-8' ; if ( ! is_array ( $ array ) ) { return false ; } $ xmlw = new \ XmlWriter ( ) ; $ xmlw -> openMemory ( ) ; $ xmlw -> startDocument ( $ xmlVersion , $ xmlEncoding , $ standalone ) ; $ xmlw -> startElement ( $ rootName ) ; self :: _arr2xml ( $ xmlw , $ array , $ defaultTag ) ; $ xmlw -> endElement ( ) ; return $ xmlw -> outputMemory ( true ) ; }

Serializes given array into xml. The array indices must be string to use
them as XML tags.

@param array  $array      object to serialize represented in array.
@param string $rootName   name of the XML root element.
@param string $defaultTag default tag for non-tagged elements.
@param string $standalone adds 'standalone' header tag, values 'yes'/'no'

@return string

Serializes given array into xml . The array indices must be string to use them as XML tags .


public static function toBoolean($obj, $skipNull = false)
    {
        if ($skipNull && is_null($obj)) {
            return null;
        }

        return filter_var($obj, FILTER_VALIDATE_BOOLEAN);
    }

public static function toBoolean ( $ obj , $ skipNull = false ) { if ( $ skipNull && is_null ( $ obj ) ) { return null ; } return filter_var ( $ obj , FILTER_VALIDATE_BOOLEAN ) ; }

Converts string into boolean value.

@param string $obj       boolean value in string format.
@param bool   $skipNull  If $skipNull is set, will return NULL directly
when $obj is NULL.

@return bool


public static function rfc1123ToDateTime($date)
    {
        $timeZone = new \DateTimeZone('GMT');
        $format   = Resources::AZURE_DATE_FORMAT;

        return \DateTime::createFromFormat($format, $date, $timeZone);
    }

public static function rfc1123ToDateTime ( $ date ) { $ timeZone = new \ DateTimeZone ( 'GMT' ) ; $ format = Resources :: AZURE_DATE_FORMAT ; return \ DateTime :: createFromFormat ( $ format , $ date , $ timeZone ) ; }

Converts a given date string into \DateTime object

@param string $date windows azure date ins string representation.

@return \DateTime

Converts a given date string into \ DateTime object


public static function isoDate(\DateTimeInterface $date)
    {
        $date = clone $date;
        $date = $date->setTimezone(new \DateTimeZone('UTC'));

        return str_replace('+00:00', 'Z', $date->format('c'));
    }

public static function isoDate ( \ DateTimeInterface $ date ) { $ date = clone $ date ; $ date = $ date -> setTimezone ( new \ DateTimeZone ( 'UTC' ) ) ; return str_replace ( '+00:00' , 'Z' , $ date -> format ( 'c' ) ) ; }

Generate ISO 8601 compliant date string in UTC time zone

@param \DateTimeInterface $date The date value to convert

@return string


public static function convertToDateTime($value)
    {
        if ($value instanceof \DateTime) {
            return $value;
        }

        if (substr($value, -1) == 'Z') {
            $value = substr($value, 0, strlen($value) - 1);
        }

        return new \DateTime($value, new \DateTimeZone('UTC'));
    }

public static function convertToDateTime ( $ value ) { if ( $ value instanceof \ DateTime ) { return $ value ; } if ( substr ( $ value , - 1 ) == 'Z' ) { $ value = substr ( $ value , 0 , strlen ( $ value ) - 1 ) ; } return new \ DateTime ( $ value , new \ DateTimeZone ( 'UTC' ) ) ; }

Converts a string to a \DateTime object. Returns false on failure.

@param string $value The string value to parse.

@return \DateTime

Converts a string to a \ DateTime object . Returns false on failure .


public static function base256ToDec($number)
    {
        Validate::canCastAsString($number, 'number');

        $result = 0;
        $base   = 1;
        for ($i = strlen($number) - 1; $i >= 0; $i--) {
            $result = bcadd($result, bcmul(ord($number[$i]), $base));
            $base   = bcmul($base, 256);
        }

        return $result;
    }

public static function base256ToDec ( $ number ) { Validate :: canCastAsString ( $ number , 'number' ) ; $ result = 0 ; $ base = 1 ; for ( $ i = strlen ( $ number ) - 1 ; $ i >= 0 ; $ i -- ) { $ result = bcadd ( $ result , bcmul ( ord ( $ number [ $ i ] ) , $ base ) ) ; $ base = bcmul ( $ base , 256 ) ; } return $ result ; }

Convert base 256 number to decimal number.

@param string $number Base 256 number

@return string Decimal number

Convert base 256 number to decimal number .


public static function allZero($content)
    {
        $size = strlen($content);

        // If all Zero, skip this range
        for ($i = 0; $i < $size; $i++) {
            if (ord($content[$i]) != 0) {
                return false;
            }
        }

        return true;
    }

public
static
function
allZero
(
$
content
)
{
$
size
=
strlen
(
$
content
)
;
// If all Zero, skip this range
for
(
$
i
=
0
;
$
i
<
$
size
;
$
i
++
)
{
if
(
ord
(
$
content
[
$
i
]
)
!=
0
)
{
return
false
;
}
}
return
true
;
}

Check if all the bytes are zero.

@param string $content The content.
@return bool


public static function appendDelimiter($string, $delimiter)
    {
        if (!self::endsWith($string, $delimiter)) {
            $string .= $delimiter;
        }

        return $string;
    }

public static function appendDelimiter ( $ string , $ delimiter ) { if ( ! self :: endsWith ( $ string , $ delimiter ) ) { $ string .= $ delimiter ; } return $ string ; }

Append the delimiter to the string. The delimiter will not be added if
the string already ends with this delimiter.

@param string $string    The string to add delimiter to.
@param string $delimiter The delimiter to be added.

@return string

Append the delimiter to the string . The delimiter will not be added if the string already ends with this delimiter .


public static function requestSentToSecondary(
        \Psr\Http\Message\RequestInterface $request,
        array $options
    ) {
        $uri = $request->getUri();
        $secondaryUri = $options[Resources::ROS_SECONDARY_URI];
        $isSecondary = false;
        if (strpos((string)$uri, (string)$secondaryUri) !== false) {
            $isSecondary = true;
        }
        return $isSecondary;
    }

public static function requestSentToSecondary ( \ Psr \ Http \ Message \ RequestInterface $ request , array $ options ) { $ uri = $ request -> getUri ( ) ; $ secondaryUri = $ options [ Resources :: ROS_SECONDARY_URI ] ; $ isSecondary = false ; if ( strpos ( ( string ) $ uri , ( string ) $ secondaryUri ) !== false ) { $ isSecondary = true ; } return $ isSecondary ; }

Static function used to determine if the request is performed against
secondary endpoint.

@param  Psr\Http\Message\RequestInterface $request The request performed.
@param  array                             $options The options of the
request. Must contain
Resources::ROS_SECONDARY_URI

@return boolean

Static function used to determine if the request is performed against secondary endpoint .


public static function getLocationFromHeaders(array $headers)
    {
        $value = Utilities::tryGetValue(
            $headers,
            Resources::X_MS_CONTINUATION_LOCATION_MODE
        );

        $result = '';
        if (\is_string($value)) {
            $result = $value;
        } elseif (!empty($value)) {
            $result = $value[0];
        }
        return $result;
    }

public static function getLocationFromHeaders ( array $ headers ) { $ value = Utilities :: tryGetValue ( $ headers , Resources :: X_MS_CONTINUATION_LOCATION_MODE ) ; $ result = '' ; if ( \ is_string ( $ value ) ) { $ result = $ value ; } elseif ( ! empty ( $ value ) ) { $ result = $ value [ 0 ] ; } return $ result ; }

Gets the location value from the headers.

@param  array  $headers request/response headers.

@return string

Gets the location value from the headers .


public static function calculateContentMD5($content)
    {
        Validate::notNull($content, 'content');
        Validate::canCastAsString($content, 'content');

        return base64_encode(md5($content, true));
    }

public static function calculateContentMD5 ( $ content ) { Validate :: notNull ( $ content , 'content' ) ; Validate :: canCastAsString ( $ content , 'content' ) ; return base64_encode ( md5 ( $ content , true ) ) ; }

Calculates the content MD5 which is base64 encoded. This should be align
with the server calculated MD5.

@param  string $content the content to be calculated.

@return string

Calculates the content MD5 which is base64 encoded . This should be align with the server calculated MD5 .


protected static function validateResourceType($resourceType)
    {
        Validate::isTrue(
            $resourceType == Resources::RESOURCE_TYPE_SHARE ||
            $resourceType == Resources::RESOURCE_TYPE_FILE,
            Resources::INVALID_RESOURCE_TYPE
        );
    }

protected static function validateResourceType ( $ resourceType ) { Validate :: isTrue ( $ resourceType == Resources :: RESOURCE_TYPE_SHARE || $ resourceType == Resources :: RESOURCE_TYPE_FILE , Resources :: INVALID_RESOURCE_TYPE ) ; }

Validate if the resource type is for the class.

@param  string $resourceType the resource type to be validated.

@throws \InvalidArgumentException

@internal

@return void

Validate if the resource type is for the class .


public static function create(array $headers)
    {
        $result = new UpdateMessageResult();
        $result->setPopReceipt(Utilities::tryGetValueInsensitive(
            Resources::X_MS_POPRECEIPT,
            $headers
        ));
        $timeNextVisible = Utilities::tryGetValueInsensitive(
            Resources::X_MS_TIME_NEXT_VISIBLE,
            $headers
        );
        $date   = Utilities::rfc1123ToDateTime($timeNextVisible);
        $result->setTimeNextVisible($date);

        return $result;
    }

public static function create ( array $ headers ) { $ result = new UpdateMessageResult ( ) ; $ result -> setPopReceipt ( Utilities :: tryGetValueInsensitive ( Resources :: X_MS_POPRECEIPT , $ headers ) ) ; $ timeNextVisible = Utilities :: tryGetValueInsensitive ( Resources :: X_MS_TIME_NEXT_VISIBLE , $ headers ) ; $ date = Utilities :: rfc1123ToDateTime ( $ timeNextVisible ) ; $ result -> setTimeNextVisible ( $ date ) ; return $ result ; }

Creates an instance with the given response headers.

@param  array  $headers The response headers used to create the instance.

@internal

@return UpdateMessageResult

Creates an instance with the given response headers .


public static function create(
        $type = self::GENERAL_RETRY_TYPE,
        $numberOfRetries = Resources::DEFAULT_NUMBER_OF_RETRIES,
        $interval = Resources::DEFAULT_RETRY_INTERVAL,
        $accumulationMethod = self::LINEAR_INTERVAL_ACCUMULATION,
        $retryConnect = false
    ) {
        //Validate the input parameters
        //type
        Validate::isTrue(
            $type == self::GENERAL_RETRY_TYPE ||
            $type == self::APPEND_BLOB_RETRY_TYPE,
            sprintf(
                Resources::INVALID_PARAM_GENERAL,
                'type'
            )
        );
        //numberOfRetries
        Validate::isTrue(
            $numberOfRetries > 0,
            sprintf(
                Resources::INVALID_NEGATIVE_PARAM,
                'numberOfRetries'
            )
        );
        //interval
        Validate::isTrue(
            $interval > 0,
            sprintf(
                Resources::INVALID_NEGATIVE_PARAM,
                'interval'
            )
        );
        //accumulationMethod
        Validate::isTrue(
            $accumulationMethod == self::LINEAR_INTERVAL_ACCUMULATION ||
            $accumulationMethod == self::EXPONENTIAL_INTERVAL_ACCUMULATION,
            sprintf(
                Resources::INVALID_PARAM_GENERAL,
                'accumulationMethod'
            )
        );
        //retryConnect
        Validate::isBoolean($retryConnect);

        //Get the interval calculator according to the type of the
        //accumulation method.
        $intervalCalculator =
            $accumulationMethod == self::LINEAR_INTERVAL_ACCUMULATION ?
            self::createLinearDelayCalculator($interval) :
            self::createExponentialDelayCalculator($interval);

        //Get the retry decider according to the type of the retry and
        //the number of retries.
        $retryDecider = self::createRetryDecider($type, $numberOfRetries, $retryConnect);

        //construct the retry middle ware.
        return new RetryMiddleware($intervalCalculator, $retryDecider);
    }

Create the retry handler for the Guzzle client, according to the given
attributes.

@param  string $type                The type that controls the logic of
the decider of the retry handler.
Possible value can be
self::GENERAL_RETRY_TYPE or
self::APPEND_BLOB_RETRY_TYPE
@param  int    $numberOfRetries     The maximum number of retries.
@param  int    $interval            The minimum interval between each retry
@param  string $accumulationMethod  If the interval increases linearly or
exponentially.
Possible value can be
self::LINEAR_INTERVAL_ACCUMULATION or
self::EXPONENTIAL_INTERVAL_ACCUMULATION
@param  bool   $retryConnect        Whether to retry on connection failures.
@return RetryMiddleware             A RetryMiddleware object that contains
the logic of how the request should be
handled after a response.

Create the retry handler for the Guzzle client according to the given attributes .


protected static function createRetryDecider($type, $maxRetries, $retryConnect)
    {
        return function (
            $retries,
            $request,
            $response = null,
            $exception = null,
            $isSecondary = false
        ) use (
            $type,
            $maxRetries,
            $retryConnect
        ) {
            //Exceeds the retry limit. No retry.
            if ($retries >= $maxRetries) {
                return false;
            }

            if (!$response) {
                if (!$exception || !($exception instanceof RequestException)) {
                    return false;
                } elseif ($exception instanceof ConnectException) {
                    return $retryConnect;
                } else {
                    $response = $exception->getResponse();
                }
            }

            if ($type == self::GENERAL_RETRY_TYPE) {
                return self::generalRetryDecider(
                    $response->getStatusCode(),
                    $isSecondary
                );
            } else {
                return self::appendBlobRetryDecider(
                    $response->getStatusCode(),
                    $isSecondary
                );
            }

            return true;
        };
    }

protected
static
function
createRetryDecider
(
$
type
,
$
maxRetries
,
$
retryConnect
)
{
return
function
(
$
retries
,
$
request
,
$
response
=
,
$
exception
=
,
$
isSecondary
=
false
)
use
(
$
type
,
$
maxRetries
,
$
retryConnect
)
{
//Exceeds the retry limit. No retry.
if
(
$
retries
>=
$
maxRetries
)
{
return
false
;
}
if
(
!
$
response
)
{
if
(
!
$
exception
||
!
(
$
exception
instanceof
RequestException
)
)
{
return
false
;
}
elseif
(
$
exception
instanceof
ConnectException
)
{
return
$
retryConnect
;
}
else
{
$
response
=
$
exception
->
getResponse
(
)
;
}
}
if
(
$
type
==
self
::
GENERAL_RETRY_TYPE
)
{
return
self
::
generalRetryDecider
(
$
response
->
getStatusCode
(
)
,
$
isSecondary
)
;
}
else
{
return
self
::
appendBlobRetryDecider
(
$
response
->
getStatusCode
(
)
,
$
isSecondary
)
;
}
return
true
;
}
;
}

Create the retry decider for the retry handler. It will return a callable
that accepts the number of retries, the request, the response and the
exception, and return the decision for a retry.

@param  string $type         The type of the retry handler.
@param  int    $maxRetries   The maximum number of retries to be done.
@param  bool   $retryConnect Whether to retry on connection failures.

@return callable     The callable that will return if the request should
be retried.

Create the retry decider for the retry handler . It will return a callable that accepts the number of retries the request the response and the exception and return the decision for a retry .


protected static function generalRetryDecider($statusCode, $isSecondary)
    {
        $retry = false;
        if ($statusCode == 408) {
            $retry = true;
        } elseif ($statusCode >= 500) {
            if ($statusCode != 501 && $statusCode != 505) {
                $retry = true;
            }
        } elseif ($isSecondary && $statusCode == 404) {
            $retry = true;
        }
        return $retry;
    }

protected static function generalRetryDecider ( $ statusCode , $ isSecondary ) { $ retry = false ; if ( $ statusCode == 408 ) { $ retry = true ; } elseif ( $ statusCode >= 500 ) { if ( $ statusCode != 501 && $ statusCode != 505 ) { $ retry = true ; } } elseif ( $ isSecondary && $ statusCode == 404 ) { $ retry = true ; } return $ retry ; }

Decide if the given status code indicate the request should be retried.

@param  int $statusCode status code of the previous request.

@return bool            true if the request should be retried.

Decide if the given status code indicate the request should be retried .


protected function addOptionalQueryParam(array &$queryParameters, $key, $value)
    {
        Validate::isArray($queryParameters, 'queryParameters');
        Validate::canCastAsString($key, 'key');
        Validate::canCastAsString($value, 'value');

        if (!is_null($value) && Resources::EMPTY_STRING !== $value) {
            $queryParameters[$key] = $value;
        }
    }

protected function addOptionalQueryParam ( array & $ queryParameters , $ key , $ value ) { Validate :: isArray ( $ queryParameters , 'queryParameters' ) ; Validate :: canCastAsString ( $ key , 'key' ) ; Validate :: canCastAsString ( $ value , 'value' ) ; if ( ! is_null ( $ value ) && Resources :: EMPTY_STRING !== $ value ) { $ queryParameters [ $ key ] = $ value ; } }

Adds optional query parameter.

Doesn't add the value if it satisfies empty().

@param array  &$queryParameters The query parameters.
@param string $key              The query variable name.
@param string $value            The query variable value.

@return void


protected function addOptionalHeader(array &$headers, $key, $value)
    {
        Validate::isArray($headers, 'headers');
        Validate::canCastAsString($key, 'key');
        Validate::canCastAsString($value, 'value');

        if (!is_null($value) && Resources::EMPTY_STRING !== $value) {
            $headers[$key] = $value;
        }
    }

protected function addOptionalHeader ( array & $ headers , $ key , $ value ) { Validate :: isArray ( $ headers , 'headers' ) ; Validate :: canCastAsString ( $ key , 'key' ) ; Validate :: canCastAsString ( $ value , 'value' ) ; if ( ! is_null ( $ value ) && Resources :: EMPTY_STRING !== $ value ) { $ headers [ $ key ] = $ value ; } }

Adds optional header.

Doesn't add the value if it satisfies empty().

@param array  &$headers The HTTP header parameters.
@param string $key      The HTTP header name.
@param string $value    The HTTP header value.

@return void


public static function create(
        array $headers,
        StreamInterface $body,
        array $metadata
    ) {
        $result = new GetFileResult();
        $result->setContentStream($body->detach());
        $result->setProperties(FileProperties::createFromHttpHeaders($headers));
        $result->setMetadata(is_null($metadata) ? array() : $metadata);

        return $result;
    }

public static function create ( array $ headers , StreamInterface $ body , array $ metadata ) { $ result = new GetFileResult ( ) ; $ result -> setContentStream ( $ body -> detach ( ) ) ; $ result -> setProperties ( FileProperties :: createFromHttpHeaders ( $ headers ) ) ; $ result -> setMetadata ( is_null ( $ metadata ) ? array ( ) : $ metadata ) ; return $ result ; }

Creates GetFileResult from getFile call.

@param array           $headers  The HTTP response headers.
@param StreamInterface $body     The response body.
@param array           $metadata The file metadata.

@internal

@return GetFileResult

Creates GetFileResult from getFile call .


private static function serializeHeaders(array $headers)
    {
        $resultString = "Headers:\n";
        foreach ($headers as $key => $value) {
            $resultString .= sprintf("%s: %s\n", $key, $value[0]);
        }

        return $resultString;
    }

private
static
function
serializeHeaders
(
array
$
headers
)
{
$
resultString
=
"Headers:\n"
;
foreach
(
$
headers
as
$
key
=>
$
value
)
{
$
resultString
.=
sprintf
(
"%s: %s\n"
,
$
key
,
$
value
[
0
]
)
;
}
return
$
resultString
;
}

Serialize the message headers.

@param  array  $headers The headers to be serialized.

@return string


private static function serializeRequestException(RequestException $e)
    {
        $resultString = sprintf("Reason:\n%s\n", $e);
        if ($e->hasResponse()) {
            $resultString .= self::serializeResponse($e->getResponse());
        }

        return $resultString;
    }

private static function serializeRequestException ( RequestException $ e ) { $ resultString = sprintf ( "Reason:\n%s\n" , $ e ) ; if ( $ e -> hasResponse ( ) ) { $ resultString .= self :: serializeResponse ( $ e -> getResponse ( ) ) ; } return $ resultString ; }

Serialize the request exception.

@param  RequestException $e the request exception to be serialized.

@return string


public static function create($parsedResponse)
    {
        $result = new CreateMessageResult();

        if (!empty($parsedResponse) &&
            !empty($parsedResponse[Resources::QP_QUEUE_MESSAGE])
        ) {
            $result->setQueueMessage(
                QueueMessage::createFromCreateMessage(
                    $parsedResponse[Resources::QP_QUEUE_MESSAGE]
                )
            );
        }

        return $result;
    }

public static function create ( $ parsedResponse ) { $ result = new CreateMessageResult ( ) ; if ( ! empty ( $ parsedResponse ) && ! empty ( $ parsedResponse [ Resources :: QP_QUEUE_MESSAGE ] ) ) { $ result -> setQueueMessage ( QueueMessage :: createFromCreateMessage ( $ parsedResponse [ Resources :: QP_QUEUE_MESSAGE ] ) ) ; } return $ result ; }

Creates CreateMessageResult object from parsed XML response.

@param array $parsedResponse XML response parsed into array.

@internal

@return CreateMessageResult

Creates CreateMessageResult object from parsed XML response .


public static function create($body, $headers, $odataSerializer)
    {
        $result = new InsertEntityResult();
        $entity = $odataSerializer->parseEntity($body);
        $entity->setETag(Utilities::tryGetValue($headers, Resources::ETAG));
        $result->setEntity($entity);

        return $result;
    }

public static function create ( $ body , $ headers , $ odataSerializer ) { $ result = new InsertEntityResult ( ) ; $ entity = $ odataSerializer -> parseEntity ( $ body ) ; $ entity -> setETag ( Utilities :: tryGetValue ( $ headers , Resources :: ETAG ) ) ; $ result -> setEntity ( $ entity ) ; return $ result ; }

Create InsertEntityResult object from HTTP response parts.

@param string              $body            The HTTP response body.
@param array               $headers         The HTTP response headers.
@param IODataReaderWriter  $odataSerializer The OData reader and writer.

@internal

@return InsertEntityResult

Create InsertEntityResult object from HTTP response parts .


public static function create(array $headers, array $entities)
    {
        $result  = new QueryEntitiesResult();
        $headers = array_change_key_case($headers);
        $nextPK  = Utilities::tryGetValue(
            $headers,
            Resources::X_MS_CONTINUATION_NEXTPARTITIONKEY
        );
        $nextRK  = Utilities::tryGetValue(
            $headers,
            Resources::X_MS_CONTINUATION_NEXTROWKEY
        );

        if ($nextRK != null && $nextPK != null) {
            $result->setContinuationToken(
                new TableContinuationToken(
                    '',
                    $nextPK,
                    $nextRK,
                    Utilities::getLocationFromHeaders($headers)
                )
            );
        }

        $result->setEntities($entities);

        return $result;
    }

public static function create ( array $ headers , array $ entities ) { $ result = new QueryEntitiesResult ( ) ; $ headers = array_change_key_case ( $ headers ) ; $ nextPK = Utilities :: tryGetValue ( $ headers , Resources :: X_MS_CONTINUATION_NEXTPARTITIONKEY ) ; $ nextRK = Utilities :: tryGetValue ( $ headers , Resources :: X_MS_CONTINUATION_NEXTROWKEY ) ; if ( $ nextRK != null && $ nextPK != null ) { $ result -> setContinuationToken ( new TableContinuationToken ( '' , $ nextPK , $ nextRK , Utilities :: getLocationFromHeaders ( $ headers ) ) ) ; } $ result -> setEntities ( $ entities ) ; return $ result ; }

Creates new QueryEntitiesResult instance.

@param array $headers  The HTTP response headers.
@param array $entities The entities.

@internal

@return QueryEntitiesResult

Creates new QueryEntitiesResult instance .


public static function formatHeaders(array $headers)
    {
        $result = array();
        foreach ($headers as $key => $value) {
            if (is_array($value) && count($value) == 1) {
                $result[strtolower($key)] = $value[0];
            } else {
                $result[strtolower($key)] = $value;
            }
        }

        return $result;
    }

public static function formatHeaders ( array $ headers ) { $ result = array ( ) ; foreach ( $ headers as $ key => $ value ) { if ( is_array ( $ value ) && count ( $ value ) == 1 ) { $ result [ strtolower ( $ key ) ] = $ value [ 0 ] ; } else { $ result [ strtolower ( $ key ) ] = $ value ; } } return $ result ; }

Convert a http headers array into an uniformed format for further process

@param array $headers headers for format

@return array


public static function create(array $parsed)
    {
        $result = new File();
        $name = Utilities::tryGetValue($parsed, Resources::QP_NAME);
        $result->setName($name);
        $properties = Utilities::tryGetValue($parsed, Resources::QP_PROPERTIES);
        $length = \intval(Utilities::tryGetValue($properties, Resources::QP_CONTENT_LENGTH));
        $result->setLength($length);
        return $result;
    }

public static function create ( array $ parsed ) { $ result = new File ( ) ; $ name = Utilities :: tryGetValue ( $ parsed , Resources :: QP_NAME ) ; $ result -> setName ( $ name ) ; $ properties = Utilities :: tryGetValue ( $ parsed , Resources :: QP_PROPERTIES ) ; $ length = \ intval ( Utilities :: tryGetValue ( $ properties , Resources :: QP_CONTENT_LENGTH ) ) ; $ result -> setLength ( $ length ) ; return $ result ; }

Creates a File object using the parsed array.

@param  array $parsed The parsed array that contains the object information.

@return File

Creates a File object using the parsed array .


public function apply(callable $handler)
    {
        $result = $handler;
        foreach ($this->middlewares as $middleware) {
            $result = $middleware($result);
        }

        return $result;
    }

public function apply ( callable $ handler ) { $ result = $ handler ; foreach ( $ this -> middlewares as $ middleware ) { $ result = $ middleware ( $ result ) ; } return $ result ; }

Apply the middlewares to the handler.

@param  callable $handler the handler to which the middleware applies.

@return callable


public function getAvailableIncludes()
    {
        if ($this->relations == ['*']) {
            return $this->resolveScopedIncludes($this->getCurrentScope());
        }

        return array_keys($this->normalizeRelations($this->relations));
    }

public function getAvailableIncludes ( ) { if ( $ this -> relations == [ '*' ] ) { return $ this -> resolveScopedIncludes ( $ this -> getCurrentScope ( ) ) ; } return array_keys ( $ this -> normalizeRelations ( $ this -> relations ) ) ; }

Overrides Fractal's getter for available includes.

@return array

Overrides Fractal s getter for available includes .


protected function callIncludeMethod(Scope $scope, $identifier, $data)
    {
        $parameters = iterator_to_array($scope->getManager()->getIncludeParams($scope->getIdentifier($identifier)));

        return $this->includeResource($identifier, $data, $parameters);
    }

protected function callIncludeMethod ( Scope $ scope , $ identifier , $ data ) { $ parameters = iterator_to_array ( $ scope -> getManager ( ) -> getIncludeParams ( $ scope -> getIdentifier ( $ identifier ) ) ) ; return $ this -> includeResource ( $ identifier , $ data , $ parameters ) ; }

Overrides Fractal's method for including a relation.

@param  \League\Fractal\Scope $scope
@param  string                $identifier
@param  mixed                 $data
@return \League\Fractal\Resource\ResourceInterface

Overrides Fractal s method for including a relation .


protected function resolveScopedIncludes(Scope $scope): array
    {
        $level = count($scope->getParentScopes());
        $includes = $scope->getManager()->getRequestedIncludes();

        return collect($includes)->map(function ($include) {
            return explode('.', $include);
        })->filter(function ($include) use ($level) {
            return count($include) > $level;
        })->pluck($level)->unique()->all();
    }

protected function resolveScopedIncludes ( Scope $ scope ) : array { $ level = count ( $ scope -> getParentScopes ( ) ) ; $ includes = $ scope -> getManager ( ) -> getRequestedIncludes ( ) ; return collect ( $ includes ) -> map ( function ( $ include ) { return explode ( '.' , $ include ) ; } ) -> filter ( function ( $ include ) use ( $ level ) { return count ( $ include ) > $ level ; } ) -> pluck ( $ level ) -> unique ( ) -> all ( ) ; }

Resolve scoped includes for the given scope.

@param  \League\Fractal\Scope $scope
@return array

Resolve scoped includes for the given scope .


public function error($errorCode = null, string $message = null)
    {
        $this->errorCode = $errorCode;
        $this->message = $message;

        return $this;
    }

public function error ( $ errorCode = null , string $ message = null ) { $ this -> errorCode = $ errorCode ; $ this -> message = $ message ; return $ this ; }

Set the error code and message.

@param  mixed|null  $errorCode
@param  string|null $message
@return $this


public function data(array $data = null)
    {
        $this->data = array_merge((array) $this->data, (array) $data);

        return $this;
    }

public function data ( array $ data = null ) { $ this -> data = array_merge ( ( array ) $ this -> data , ( array ) $ data ) ; return $ this ; }

Add additional data to the error.

@param  array|null $data
@return $this


public function serializer($serializer)
    {
        if (is_string($serializer)) {
            $serializer = new $serializer;
        }

        if (! $serializer instanceof ErrorSerializer) {
            throw new InvalidErrorSerializerException;
        }

        $this->serializer = $serializer;

        return $this;
    }

public function serializer ( $ serializer ) { if ( is_string ( $ serializer ) ) { $ serializer = new $ serializer ; } if ( ! $ serializer instanceof ErrorSerializer ) { throw new InvalidErrorSerializerException ; } $ this -> serializer = $ serializer ; return $ this ; }

Set the error serializer.

@param  \Flugg\Responder\Contracts\ErrorSerializer|string $serializer
@return $this
@throws \Flugg\Responder\Exceptions\InvalidErrorSerializerException


protected function getOutput(): array
    {
        return $this->errorFactory->make($this->serializer, $this->errorCode, $this->message, $this->data);
    }

protected function getOutput ( ) : array { return $ this -> errorFactory -> make ( $ this -> serializer , $ this -> errorCode , $ this -> message , $ this -> data ) ; }

Get the serialized response output.

@return array


public function resource($data = null, $transformer = null, string $resourceKey = null)
    {
        $this->resource = $this->resourceFactory->make($data, $transformer, $resourceKey);

        if ($data instanceof CursorPaginator) {
            $this->cursor($this->paginatorFactory->makeCursor($data));
        } elseif ($data instanceof LengthAwarePaginator) {
            $this->paginator($this->paginatorFactory->make($data));
        }

        return $this;
    }

public function resource ( $ data = null , $ transformer = null , string $ resourceKey = null ) { $ this -> resource = $ this -> resourceFactory -> make ( $ data , $ transformer , $ resourceKey ) ; if ( $ data instanceof CursorPaginator ) { $ this -> cursor ( $ this -> paginatorFactory -> makeCursor ( $ data ) ) ; } elseif ( $ data instanceof LengthAwarePaginator ) { $ this -> paginator ( $ this -> paginatorFactory -> make ( $ data ) ) ; } return $ this ; }

Make a resource from the given data and transformer and set the resource key.

@param  mixed                                                          $data
@param  \Flugg\Responder\Transformers\Transformer|callable|string|null $transformer
@param  string|null                                                    $resourceKey
@return $this

Make a resource from the given data and transformer and set the resource key .


public function cursor(Cursor $cursor)
    {
        if ($this->resource instanceof CollectionResource) {
            $this->resource->setCursor($cursor);
        }

        return $this;
    }

public function cursor ( Cursor $ cursor ) { if ( $ this -> resource instanceof CollectionResource ) { $ this -> resource -> setCursor ( $ cursor ) ; } return $ this ; }

Manually set the cursor on the resource.

@param  \League\Fractal\Pagination\Cursor $cursor
@return $this

Manually set the cursor on the resource .


public function paginator(IlluminatePaginatorAdapter $paginator)
    {
        if ($this->resource instanceof CollectionResource) {
            $this->resource->setPaginator($paginator);
        }

        return $this;
    }

public function paginator ( IlluminatePaginatorAdapter $ paginator ) { if ( $ this -> resource instanceof CollectionResource ) { $ this -> resource -> setPaginator ( $ paginator ) ; } return $ this ; }

Manually set the paginator on the resource.

@param  \League\Fractal\Pagination\IlluminatePaginatorAdapter $paginator
@return $this

Manually set the paginator on the resource .


public function with($relations)
    {
        $relations = is_array($relations) ? $relations : func_get_args();

        foreach ($relations as $relation => $constraint) {
            if (is_numeric($relation)) {
                $relation = $constraint;
                $constraint = null;
            }

            $this->with = array_merge($this->with, [$relation => $constraint]);
        }

        return $this;
    }

public function with ( $ relations ) { $ relations = is_array ( $ relations ) ? $ relations : func_get_args ( ) ; foreach ( $ relations as $ relation => $ constraint ) { if ( is_numeric ( $ relation ) ) { $ relation = $ constraint ; $ constraint = null ; } $ this -> with = array_merge ( $ this -> with , [ $ relation => $ constraint ] ) ; } return $ this ; }

Include relations to the transform.

@param  string[]|string $relations
@return $this


public function without($relations)
    {
        $this->without = array_merge($this->without, is_array($relations) ? $relations : func_get_args());

        return $this;
    }

public function without ( $ relations ) { $ this -> without = array_merge ( $ this -> without , is_array ( $ relations ) ? $ relations : func_get_args ( ) ) ; return $ this ; }

Exclude relations from the transform.

@param  string[]|string $relations
@return $this


public function only($fields)
    {
        $this->only = array_merge($this->only, is_array($fields) ? $fields : func_get_args());

        return $this;
    }

public function only ( $ fields ) { $ this -> only = array_merge ( $ this -> only , is_array ( $ fields ) ? $ fields : func_get_args ( ) ) ; return $ this ; }

Filter fields to output using sparse fieldsets.

@param  string[]|string $fields
@return $this

Filter fields to output using sparse fieldsets .


public function serializer($serializer)
    {
        if (is_string($serializer)) {
            $serializer = new $serializer;
        }

        if (! $serializer instanceof SerializerAbstract) {
            throw new InvalidSuccessSerializerException;
        }

        $this->serializer = $serializer;

        return $this;
    }

public function serializer ( $ serializer ) { if ( is_string ( $ serializer ) ) { $ serializer = new $ serializer ; } if ( ! $ serializer instanceof SerializerAbstract ) { throw new InvalidSuccessSerializerException ; } $ this -> serializer = $ serializer ; return $ this ; }

Set the serializer.

@param  \League\Fractal\Serializer\SerializerAbstract|string $serializer
@return $this
@throws \Flugg\Responder\Exceptions\InvalidSuccessSerializerException


public function transform()
    {
        $this->prepareRelations($this->resource->getData(), $this->resource->getTransformer());

        return $this->transformFactory->make($this->resource ?: new NullResource, $this->serializer, [
            'includes' => $this->with,
            'excludes' => $this->without,
            'fieldsets' => $this->only,
        ]);
    }

public function transform ( ) { $ this -> prepareRelations ( $ this -> resource -> getData ( ) , $ this -> resource -> getTransformer ( ) ) ; return $ this -> transformFactory -> make ( $ this -> resource ? : new NullResource , $ this -> serializer , [ 'includes' => $ this -> with , 'excludes' => $ this -> without , 'fieldsets' => $ this -> only , ] ) ; }

Transform and serialize the data and return the transformed array.

@return array|null

Transform and serialize the data and return the transformed array .


protected function prepareRelations($data, $transformer)
    {
        if ($transformer instanceof Transformer) {
            $relations = $transformer->relations($this->with);
            $defaultRelations = $this->removeExcludedRelations($transformer->defaultRelations($this->with));
            $this->with = array_merge($relations, $defaultRelations);
        }

        if ($data instanceof Model || $data instanceof Collection) {
            $this->eagerLoadRelations($data, $this->with, $transformer);
        }

        $this->with = array_keys($this->with);
    }

protected function prepareRelations ( $ data , $ transformer ) { if ( $ transformer instanceof Transformer ) { $ relations = $ transformer -> relations ( $ this -> with ) ; $ defaultRelations = $ this -> removeExcludedRelations ( $ transformer -> defaultRelations ( $ this -> with ) ) ; $ this -> with = array_merge ( $ relations , $ defaultRelations ) ; } if ( $ data instanceof Model || $ data instanceof Collection ) { $ this -> eagerLoadRelations ( $ data , $ this -> with , $ transformer ) ; } $ this -> with = array_keys ( $ this -> with ) ; }

Prepare requested relations for the transformation.

@param  mixed                                                          $data
@param  \Flugg\Responder\Transformers\Transformer|callable|string|null $transformer
@return void

Prepare requested relations for the transformation .


protected function eagerLoadRelations($data, array $requested, $transformer)
    {
        $relations = collect(array_keys($requested))->reduce(function ($eagerLoads, $relation) use ($requested, $transformer) {
            $identifier = camel_case($this->stripParametersFromRelation($relation));

            if (method_exists($transformer, 'include' . ucfirst($identifier))) {
                return $eagerLoads;
            }

            return array_merge($eagerLoads, [$identifier => $requested[$relation] ?: function () { }]);
        }, []);

        $data->load($relations);
    }

protected function eagerLoadRelations ( $ data , array $ requested , $ transformer ) { $ relations = collect ( array_keys ( $ requested ) ) -> reduce ( function ( $ eagerLoads , $ relation ) use ( $ requested , $ transformer ) { $ identifier = camel_case ( $ this -> stripParametersFromRelation ( $ relation ) ) ; if ( method_exists ( $ transformer , 'include' . ucfirst ( $ identifier ) ) ) { return $ eagerLoads ; } return array_merge ( $ eagerLoads , [ $ identifier => $ requested [ $ relation ] ? : function ( ) { } ] ) ; } , [ ] ) ; $ data -> load ( $ relations ) ; }

Eager load all requested relations except the ones defined as an "include" method
in the transformers. We also strip away any parameters from the relation name
and normalize relations by swapping "null" constraints to empty closures.

@param  mixed                                                          $data
@param  array                                                          $requested
@param  \Flugg\Responder\Transformers\Transformer|callable|string|null $transformer
@return void

Eager load all requested relations except the ones defined as an include method in the transformers . We also strip away any parameters from the relation name and normalize relations by swapping null constraints to empty closures .


public function paginator(PaginatorInterface $paginator)
    {
        $pagination = parent::paginator($paginator)['pagination'];

        return [
            'pagination' => [
                'count' => $pagination['count'],
                'total' => $pagination['total'],
                'perPage' => $pagination['per_page'],
                'currentPage' => $pagination['current_page'],
                'totalPages' => $pagination['total_pages'],
                'links' => $pagination['links'],
            ],
        ];
    }

public function paginator ( PaginatorInterface $ paginator ) { $ pagination = parent :: paginator ( $ paginator ) [ 'pagination' ] ; return [ 'pagination' => [ 'count' => $ pagination [ 'count' ] , 'total' => $ pagination [ 'total' ] , 'perPage' => $ pagination [ 'per_page' ] , 'currentPage' => $ pagination [ 'current_page' ] , 'totalPages' => $ pagination [ 'total_pages' ] , 'links' => $ pagination [ 'links' ] , ] , ] ; }

Format pagination data.

@param  \League\Fractal\Pagination\PaginatorInterface $paginator
@return array


public function cursor(CursorInterface $cursor)
    {
        return [
            'cursor' => [
                'current' => $cursor->getCurrent(),
                'previous' => $cursor->getPrev(),
                'next' => $cursor->getNext(),
                'count' => (int) $cursor->getCount(),
            ],
        ];
    }

public function cursor ( CursorInterface $ cursor ) { return [ 'cursor' => [ 'current' => $ cursor -> getCurrent ( ) , 'previous' => $ cursor -> getPrev ( ) , 'next' => $ cursor -> getNext ( ) , 'count' => ( int ) $ cursor -> getCount ( ) , ] , ] ; }

Format cursor data.

@param  \League\Fractal\Pagination\CursorInterface $cursor
@return array


public function mergeIncludes($transformedData, $includedData)
    {
        foreach (array_keys($includedData) as $key) {
            $includedData[$key] = $includedData[$key]['data'];
        }

        return array_merge($transformedData, $includedData);
    }

public function mergeIncludes ( $ transformedData , $ includedData ) { foreach ( array_keys ( $ includedData ) as $ key ) { $ includedData [ $ key ] = $ includedData [ $ key ] [ 'data' ] ; } return array_merge ( $ transformedData , $ includedData ) ; }

Merge includes into data.

@param  array $transformedData
@param  array $includedData
@return array


public function bind($transformable, string $resourceKey)
    {
        $this->bindings = array_merge($this->bindings, is_array($transformable) ? $transformable : [
            $transformable => $resourceKey,
        ]);
    }

public function bind ( $ transformable , string $ resourceKey ) { $ this -> bindings = array_merge ( $ this -> bindings , is_array ( $ transformable ) ? $ transformable : [ $ transformable => $ resourceKey , ] ) ; }

Register a transformable to resource key binding.

@param  string|array $transformable
@param  string       $resourceKey
@return void

Register a transformable to resource key binding .


public function resolve($data)
    {
        $transformable = $this->resolveTransformableItem($data);

        if (is_object($transformable) && key_exists(get_class($transformable), $this->bindings)) {
            return $this->bindings[get_class($transformable)];
        }

        if ($transformable instanceof Model) {
            return $this->resolveFromModel($transformable);
        }

        return 'data';
    }

public function resolve ( $ data ) { $ transformable = $ this -> resolveTransformableItem ( $ data ) ; if ( is_object ( $ transformable ) && key_exists ( get_class ( $ transformable ) , $ this -> bindings ) ) { return $ this -> bindings [ get_class ( $ transformable ) ] ; } if ( $ transformable instanceof Model ) { return $ this -> resolveFromModel ( $ transformable ) ; } return 'data' ; }

Resolve a resource key from the given data.

@param  mixed $data
@return string

Resolve a resource key from the given data .


protected function resolveTransformableItem($data)
    {
        if (is_array($data) || $data instanceof Traversable) {
            foreach ($data as $item) {
                return $item;
            }
        }

        return $data;
    }

protected function resolveTransformableItem ( $ data ) { if ( is_array ( $ data ) || $ data instanceof Traversable ) { foreach ( $ data as $ item ) { return $ item ; } } return $ data ; }

Resolve a transformable item from the given data.

@param  mixed $data
@return mixed

Resolve a transformable item from the given data .


protected function resolveTransformer(string $transformer)
    {
        $transformerResolver = $this->resolveContainer()->make(TransformerResolver::class);

        return $transformerResolver->resolve($transformer);
    }

protected function resolveTransformer ( string $ transformer ) { $ transformerResolver = $ this -> resolveContainer ( ) -> make ( TransformerResolver :: class ) ; return $ transformerResolver -> resolve ( $ transformer ) ; }

Resolve a transformer from a class name string.

@param  string $transformer
@return mixed

Resolve a transformer from a class name string .


public function render($request, Exception $exception)
    {
        if ($request->wantsJson()) {
            $this->convertDefaultException($exception);

            if ($exception instanceof HttpException) {
                return $this->renderResponse($exception);
            }
        }

        return parent::render($request, $exception);
    }

public function render ( $ request , Exception $ exception ) { if ( $ request -> wantsJson ( ) ) { $ this -> convertDefaultException ( $ exception ) ; if ( $ exception instanceof HttpException ) { return $ this -> renderResponse ( $ exception ) ; } } return parent :: render ( $ request , $ exception ) ; }

Render an exception into an HTTP response.

@param  \Illuminate\Http\Request $request
@param  \Exception               $exception
@return \Symfony\Component\HttpFoundation\Response

Render an exception into an HTTP response .


public function make(ErrorSerializer $serializer, $errorCode = null, string $message = null, array $data = null): array
    {
        if (isset($errorCode) && ! isset($message)) {
            $message = $this->messageResolver->resolve($errorCode);
        }

        return $serializer->format($errorCode, $message, $data);
    }

public function make ( ErrorSerializer $ serializer , $ errorCode = null , string $ message = null , array $ data = null ) : array { if ( isset ( $ errorCode ) && ! isset ( $ message ) ) { $ message = $ this -> messageResolver -> resolve ( $ errorCode ) ; } return $ serializer -> format ( $ errorCode , $ message , $ data ) ; }

Make an error array from the given error code and message.

@param  \Flugg\Responder\Contracts\ErrorSerializer $serializer
@param  mixed|null                                 $errorCode
@param  string|null                                $message
@param  array|null                                 $data
@return array

Make an error array from the given error code and message .


public function make(ResourceInterface $resource, SerializerAbstract $serializer, array $options = [])
    {
        $options = $this->parseOptions($options, $resource);

        return $this->manager->setSerializer($serializer)
            ->parseIncludes($options['includes'])
            ->parseExcludes($options['excludes'])
            ->parseFieldsets($options['fieldsets'])
            ->createData($resource)
            ->toArray();
    }

public function make ( ResourceInterface $ resource , SerializerAbstract $ serializer , array $ options = [ ] ) { $ options = $ this -> parseOptions ( $ options , $ resource ) ; return $ this -> manager -> setSerializer ( $ serializer ) -> parseIncludes ( $ options [ 'includes' ] ) -> parseExcludes ( $ options [ 'excludes' ] ) -> parseFieldsets ( $ options [ 'fieldsets' ] ) -> createData ( $ resource ) -> toArray ( ) ; }

Transform the given resource, and serialize the data with the given serializer.

@param  \League\Fractal\Resource\ResourceInterface    $resource
@param  \League\Fractal\Serializer\SerializerAbstract $serializer
@param  array                                         $options
@return array|null

Transform the given resource and serialize the data with the given serializer .


protected function parseOptions(array $options, ResourceInterface $resource): array
    {
        $options = array_merge([
            'includes' => [],
            'excludes' => [],
            'fieldsets' => [],
        ], $options);

        if (! empty($options['fieldsets'])) {
            if (is_null($resourceKey = $resource->getResourceKey())) {
                throw new LogicException('Filtering fields using sparse fieldsets require resource key to be set.');
            }

            $options['fieldsets'] = $this->parseFieldsets($options['fieldsets'], $resourceKey, $options['includes']);
        }

        return $options;
    }

Parse the transformation options.

@param  array                                      $options
@param  \League\Fractal\Resource\ResourceInterface $resource
@return array


protected function parseFieldsets(array $fieldsets, string $resourceKey, array $includes): array
    {
        $includes = array_map(function ($include) use ($resourceKey) {
            return "$resourceKey.$include";
        }, $includes);

        foreach ($fieldsets as $key => $fields) {
            if (is_numeric($key)) {
                unset($fieldsets[$key]);
                $key = $resourceKey;
            }

            $fields = $this->parseFieldset($key, (array) $fields, $includes);
            $fieldsets[$key] = array_unique(array_merge(key_exists($key, $fieldsets) ? (array) $fieldsets[$key] : [], $fields));
        }

        return array_map(function ($fields) {
            return implode(',', $fields);
        }, $fieldsets);
    }

protected function parseFieldsets ( array $ fieldsets , string $ resourceKey , array $ includes ) : array { $ includes = array_map ( function ( $ include ) use ( $ resourceKey ) { return "$resourceKey.$include" ; } , $ includes ) ; foreach ( $ fieldsets as $ key => $ fields ) { if ( is_numeric ( $ key ) ) { unset ( $ fieldsets [ $ key ] ) ; $ key = $ resourceKey ; } $ fields = $ this -> parseFieldset ( $ key , ( array ) $ fields , $ includes ) ; $ fieldsets [ $ key ] = array_unique ( array_merge ( key_exists ( $ key , $ fieldsets ) ? ( array ) $ fieldsets [ $ key ] : [ ] , $ fields ) ) ; } return array_map ( function ( $ fields ) { return implode ( ',' , $ fields ) ; } , $ fieldsets ) ; }

Parse the fieldsets for Fractal.

@param  array  $fieldsets
@param  string $resourceKey
@param  array  $includes
@return array


protected function parseFieldset(string $key, array $fields, array $includes): array
    {
        $childIncludes = array_reduce($includes, function ($segments, $include) use ($key) {
            return array_merge($segments, $this->resolveChildIncludes($key, $include));
        }, []);

        return array_merge($fields, array_unique($childIncludes));
    }

protected function parseFieldset ( string $ key , array $ fields , array $ includes ) : array { $ childIncludes = array_reduce ( $ includes , function ( $ segments , $ include ) use ( $ key ) { return array_merge ( $ segments , $ this -> resolveChildIncludes ( $ key , $ include ) ) ; } , [ ] ) ; return array_merge ( $ fields , array_unique ( $ childIncludes ) ) ; }

Parse the given fieldset and append any related resource keys.

@param  string $key
@param  array  $fields
@param  array  $includes
@return array

Parse the given fieldset and append any related resource keys .


protected function resolveChildIncludes($key, string $include): array
    {
        if (count($segments = explode('.', $include)) <= 1) {
            return [];
        }

        $relation = $key === array_shift($segments) ? [$segments[0]] : [];

        return array_merge($relation, $this->resolveChildIncludes($key, implode('.', $segments)));
    }

protected function resolveChildIncludes ( $ key , string $ include ) : array { if ( count ( $ segments = explode ( '.' , $ include ) ) <= 1 ) { return [ ] ; } $ relation = $ key === array_shift ( $ segments ) ? [ $ segments [ 0 ] ] : [ ] ; return array_merge ( $ relation , $ this -> resolveChildIncludes ( $ key , implode ( '.' , $ segments ) ) ) ; }

Resolve included segments that are a direct child to the given resource key.

@param  string $key
@param  string $include
@return array

Resolve included segments that are a direct child to the given resource key .


public function register($errorCode, string $message)
    {
        $this->messages = array_merge($this->messages, is_array($errorCode) ? $errorCode : [
            $errorCode => $message,
        ]);
    }

public function register ( $ errorCode , string $ message ) { $ this -> messages = array_merge ( $ this -> messages , is_array ( $ errorCode ) ? $ errorCode : [ $ errorCode => $ message , ] ) ; }

Register a message mapped to an error code.

@param  mixed  $errorCode
@param  string $message
@return void

Register a message mapped to an error code .


public function resolve($errorCode)
    {
        if (key_exists($errorCode, $this->messages)) {
            return $this->messages[$errorCode];
        }

        if ($this->translator->has($errorCode = "errors.$errorCode")) {
            return $this->translator->trans($errorCode);
        }

        return null;
    }

public function resolve ( $ errorCode ) { if ( key_exists ( $ errorCode , $ this -> messages ) ) { return $ this -> messages [ $ errorCode ] ; } if ( $ this -> translator -> has ( $ errorCode = "errors.$errorCode" ) ) { return $ this -> translator -> trans ( $ errorCode ) ; } return null ; }

Resolve a message from the given error code.

@param  mixed $errorCode
@return string|null

Resolve a message from the given error code .


protected function cleanArray(array $data)
    {
        $parameters = [];

        foreach ($data as $key => $value) {
            $parameters[in_array($key, $this->except) ? $key : snake_case($key)] = $value;
        }

        return $parameters;
    }

protected function cleanArray ( array $ data ) { $ parameters = [ ] ; foreach ( $ data as $ key => $ value ) { $ parameters [ in_array ( $ key , $ this -> except ) ? $ key : snake_case ( $ key ) ] = $ value ; } return $ parameters ; }

Clean the data in the given array.

@param  array $data
@return array


public function bind($transformable, $transformer = null)
    {
        $this->bindings = array_merge($this->bindings, is_array($transformable) ? $transformable : [
            $transformable => $transformer,
        ]);
    }

public function bind ( $ transformable , $ transformer = null ) { $ this -> bindings = array_merge ( $ this -> bindings , is_array ( $ transformable ) ? $ transformable : [ $ transformable => $ transformer , ] ) ; }

Register a transformable to transformer binding.

@param  string|array         $transformable
@param  string|callback|null $transformer
@return void

Register a transformable to transformer binding .


public function resolveFromData($data)
    {
        $transformer = $this->resolveTransformer($this->resolveTransformableItem($data));

        return $this->resolve($transformer);
    }

public function resolveFromData ( $ data ) { $ transformer = $ this -> resolveTransformer ( $ this -> resolveTransformableItem ( $ data ) ) ; return $ this -> resolve ( $ transformer ) ; }

Resolve a transformer from the given data.

@param  mixed $data
@return \Flugg\Responder\Transformers\Transformer|callable

Resolve a transformer from the given data .