public static function assertExactMetaWithoutData(
        $status,
        $contentType,
        $content,
        array $expected,
        bool $strict = true,
        string $message = ''
    ): Document
    {
        return self::assertJsonApi($status, $contentType, $content, self::STATUS_OK, $message)
            ->assertNotExists('/data', $message)
            ->assertExactMeta($expected, $strict, $message);
    }

public static function assertExactMetaWithoutData ( $ status , $ contentType , $ content , array $ expected , bool $ strict = true , string $ message = '' ) : Document { return self :: assertJsonApi ( $ status , $ contentType , $ content , self :: STATUS_OK , $ message ) -> assertNotExists ( '/data' , $ message ) -> assertExactMeta ( $ expected , $ strict , $ message ) ; }

Assert an exact top-level meta response without data.

@param $status
@param $contentType
@param $content
@param array $expected
@param bool $strict
@param string $message
@return Document

Assert an exact top - level meta response without data .


public static function assertExactErrorStatus(
        $status,
        $contentType,
        $content,
        array $error,
        bool $strict = true,
        string $message = ''
    ): Document
    {
        $expectedStatus = $error['status'] ?? null;

        if (!$expectedStatus) {
            throw new \InvalidArgumentException('Expecting error to have a status member.');
        }

        return self::assertExactError(
            $status,
            $contentType,
            $content,
            (int) $expectedStatus,
            $error,
            $strict,
            $message
        );
    }

Assert the document contains an exact single error that matches the supplied error and has a status member.

@param $status
@param $contentType
@param $content
@param array $error
@param bool $strict
@param string $message
@return Document

Assert the document contains an exact single error that matches the supplied error and has a status member .


public static function assertHasExactError(
        $status,
        $contentType,
        $content,
        int $expectedStatus,
        array $error,
        bool $strict = true,
        string $message = ''
    ): Document
    {
        if (empty($error)) {
            $error = ['status' => (string) $status];
        }

        return self::assertJsonApi($status, $contentType, $content, $expectedStatus, $message)
            ->assertHasExactError($error, $strict, $message);
    }

public static function assertHasExactError ( $ status , $ contentType , $ content , int $ expectedStatus , array $ error , bool $ strict = true , string $ message = '' ) : Document { if ( empty ( $ error ) ) { $ error = [ 'status' => ( string ) $ status ] ; } return self :: assertJsonApi ( $ status , $ contentType , $ content , $ expectedStatus , $ message ) -> assertHasExactError ( $ error , $ strict , $ message ) ; }

Assert the HTTP message contains the supplied error within its errors member.

@param $status
@param $contentType
@param $content
@param int $expectedStatus
@param array $error
@param bool $strict
@param string $message
@return Document

Assert the HTTP message contains the supplied error within its errors member .


public static function assertErrors(
        $status,
        $contentType,
        $content,
        int $expectedStatus,
        array $errors,
        bool $strict = true,
        string $message = ''
    ): Document
    {
        return self::assertJsonApi($status, $contentType, $content, $expectedStatus, $message)
            ->assertErrors($errors, $strict, $message);
    }

public static function assertErrors ( $ status , $ contentType , $ content , int $ expectedStatus , array $ errors , bool $ strict = true , string $ message = '' ) : Document { return self :: assertJsonApi ( $ status , $ contentType , $ content , $ expectedStatus , $ message ) -> assertErrors ( $ errors , $ strict , $ message ) ; }

Assert the HTTP status contains the supplied errors.

@param $status
@param $contentType
@param $content
@param int $expectedStatus
@param array $errors
@param bool $strict
@param string $message
@return Document

Assert the HTTP status contains the supplied errors .


public function getDocument(): Document
    {
        if (!$this->document) {
            $this->document = HttpAssert::assertContent(
                $this->getContentType(),
                $this->getContent()
            );
        }

        return $this->document;
    }

public function getDocument ( ) : Document { if ( ! $ this -> document ) { $ this -> document = HttpAssert :: assertContent ( $ this -> getContentType ( ) , $ this -> getContent ( ) ) ; } return $ this -> document ; }

Get the JSON API document.

@return Document


public function willSeeType(string $type): self
    {
        if (empty($type)) {
            throw new \InvalidArgumentException('Expected type must be a non-empty string.');
        }

        $this->expectedType = $type;

        return $this;
    }

Set the expected resource type for the data member of the JSON document.

@param string $type
@return $this

Set the expected resource type for the data member of the JSON document .


public function assertFetchedOneExact($expected, bool $strict = true): self
    {
        $this->document = HttpAssert::assertFetchedExact(
            $this->getStatusCode(),
            $this->getContentType(),
            $this->getContent(),
            $this->identifier($expected),
            $strict
        );

        return $this;
    }

public function assertFetchedOneExact ( $ expected , bool $ strict = true ) : self { $ this -> document = HttpAssert :: assertFetchedExact ( $ this -> getStatusCode ( ) , $ this -> getContentType ( ) , $ this -> getContent ( ) , $ this -> identifier ( $ expected ) , $ strict ) ; return $ this ; }

Assert that an exact resource was fetched.

@param UrlRoutable|string|int|array $expected
the expected resource.
@param bool $strict
@return $this

Assert that an exact resource was fetched .


public function assertUpdated(array $expected = null, bool $strict = true): self
    {
        if (is_null($expected)) {
            return $this->assertNoContent();
        }

        return $this->assertFetchedOne($expected, $strict);
    }

public function assertUpdated ( array $ expected = null , bool $ strict = true ) : self { if ( is_null ( $ expected ) ) { return $ this -> assertNoContent ( ) ; } return $ this -> assertFetchedOne ( $ expected , $ strict ) ; }

Assert response is a JSON API resource updated response.

For a resource update, we typically expect either:

- 200 OK with resource content; or
- 204 No Content

Alternatively a top-level meta only response is acceptable. If this is expected,
it can be asserted using `assertMetaWithoutData`.

@param array $expected
array representation of the expected resource, or null for a no-content response
@param bool $strict
@return $this

Assert response is a JSON API resource updated response .


public function assertDeleted(array $expected = null, bool $strict = true): self
    {
        if (is_null($expected)) {
            return $this->assertNoContent();
        }

        return $this->assertMetaWithoutData($expected, $strict);
    }

public function assertDeleted ( array $ expected = null , bool $ strict = true ) : self { if ( is_null ( $ expected ) ) { return $ this -> assertNoContent ( ) ; } return $ this -> assertMetaWithoutData ( $ expected , $ strict ) ; }

Assert response is a JSON API resource deleted response.

The JSON API spec says that:

- A server MUST return a 204 No Content status code if a deletion request is successful
and no content is returned.
- A server MUST return a 200 OK status code if a deletion request is successful and the server responds
with only top-level meta data.

@param array|null $expected
the expected top-level meta, or null for no content response.
@param bool $strict
@return $this

Assert response is a JSON API resource deleted response .


public function assertIsIncluded(string $type, $id): self
    {
        $identifier = $this->identifier(compact('type', 'id'));

        $this->getDocument()->assertIncludedContainsResource(
            $identifier['type'],
            $identifier['id']
        );

        return $this;
    }

public function assertIsIncluded ( string $ type , $ id ) : self { $ identifier = $ this -> identifier ( compact ( 'type' , 'id' ) ) ; $ this -> getDocument ( ) -> assertIncludedContainsResource ( $ identifier [ 'type' ] , $ identifier [ 'id' ] ) ; return $ this ; }

Assert that the expected resource is included in the document.

@param string $type
@param UrlRoutable|string|int|null $id
@return $this

Assert that the expected resource is included in the document .


public function assertIncludes($expected, bool $strict = true): self
    {
        $this->getDocument()->assertIncludedContainsHash(
            $this->identifier($expected),
            $strict
        );

        return $this;
    }

public function assertIncludes ( $ expected , bool $ strict = true ) : self { $ this -> getDocument ( ) -> assertIncludedContainsHash ( $ this -> identifier ( $ expected ) , $ strict ) ; return $ this ; }

Assert that the included member contains the supplied resource.

@param UrlRoutable|string|int|array $expected
@param bool $strict
@return $this

Assert that the included member contains the supplied resource .


public function assertMeta(array $expected, bool $strict = true): self
    {
        $this->getDocument()->assertMeta($expected, $strict);

        return $this;
    }

public function assertMeta ( array $ expected , bool $ strict = true ) : self { $ this -> getDocument ( ) -> assertMeta ( $ expected , $ strict ) ; return $ this ; }

Assert that the top-level meta matches the expected values.

@param array $expected
@param bool $strict
@return $this

Assert that the top - level meta matches the expected values .


public function assertExactMeta(array $expected, bool $strict = true): self
    {
        $this->getDocument()->assertExactMeta($expected, $strict);

        return $this;
    }

public function assertExactMeta ( array $ expected , bool $ strict = true ) : self { $ this -> getDocument ( ) -> assertExactMeta ( $ expected , $ strict ) ; return $ this ; }

Assert that the top-level meta is exactly the expected meta.

@param array $expected
@param bool $strict
@return $this

Assert that the top - level meta is exactly the expected meta .


public function assertExactLinks(array $expected, bool $strict = true): self
    {
        $this->getDocument()->assertExactLinks($expected, $strict);

        return $this;
    }

public function assertExactLinks ( array $ expected , bool $ strict = true ) : self { $ this -> getDocument ( ) -> assertExactLinks ( $ expected , $ strict ) ; return $ this ; }

Assert that the top-level links are exactly the expected links.

@param array $expected
@param bool $strict
@return $this

Assert that the top - level links are exactly the expected links .


public function assertExactErrors(int $status, array $errors, bool $strict = true): self
    {
        $this->document = HttpAssert::assertExactErrors(
            $this->getStatusCode(),
            $this->getContentType(),
            $this->getContent(),
            $status,
            $errors,
            $strict
        );

        return $this;
    }

public function assertExactErrors ( int $ status , array $ errors , bool $ strict = true ) : self { $ this -> document = HttpAssert :: assertExactErrors ( $ this -> getStatusCode ( ) , $ this -> getContentType ( ) , $ this -> getContent ( ) , $ status , $ errors , $ strict ) ; return $ this ; }

Assert the HTTP status contains the supplied exact errors.

@param int $status
@param array $errors
@param bool $strict
@return $this

Assert the HTTP status contains the supplied exact errors .


public static function assertResource(
        $document,
        string $type,
        string $id,
        string $pointer = '/data',
        string $message = ''
    ): void
    {
        self::assertHash($document, compact('type', 'id'), $pointer, true, $message);
    }

public static function assertResource ( $ document , string $ type , string $ id , string $ pointer = '/data' , string $ message = '' ) : void { self :: assertHash ( $ document , compact ( 'type' , 'id' ) , $ pointer , true , $ message ) ; }

Assert that the value at the pointer has the expected JSON API resource.

@param array|string $document
the JSON API document.
@param string $type
the expected resource object type.
@param string $id
the expected resource object id.
@param string $pointer
the JSON pointer to where the resource object is expected in the document.
@param string $message

Assert that the value at the pointer has the expected JSON API resource .


public static function assertIdentifier(
        $document,
        string $type,
        string $id,
        string $pointer = '/data',
        string $message = ''
    ): void
    {
        $expected = compact('type', 'id');

        PHPUnitAssert::assertThat(
            $document,
            new IdentifierInDocument($expected, $pointer, true),
            $message
        );
    }

public static function assertIdentifier ( $ document , string $ type , string $ id , string $ pointer = '/data' , string $ message = '' ) : void { $ expected = compact ( 'type' , 'id' ) ; PHPUnitAssert :: assertThat ( $ document , new IdentifierInDocument ( $ expected , $ pointer , true ) , $ message ) ; }

Assert that the value at the pointer has the expected JSON API resource identifier.

@param array|string $document
the JSON API document.
@param string $type
the expected resource object type.
@param string $id
the expected resource object id.
@param string $pointer
the JSON pointer to where the resource object is expected in the document.
@param string $message

Assert that the value at the pointer has the expected JSON API resource identifier .


public static function assertExact(
        $document,
        $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        PHPUnitAssert::assertThat(
            $document,
            new ExactInDocument($expected, $pointer, $strict),
            $message
        );
    }

public static function assertExact ( $ document , $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { PHPUnitAssert :: assertThat ( $ document , new ExactInDocument ( $ expected , $ pointer , $ strict ) , $ message ) ; }

Assert that the expected value is in the document at the specified path.

@param array|string $document
the JSON API document.
@param mixed $expected
the expected value.
@param string $pointer
the JSON pointer to where the object is expected to exist within the document.
@param bool $strict
whether strict comparison should be used.
@param string $message
@return void

Assert that the expected value is in the document at the specified path .


public static function assertNotExact(
        $document,
        $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        $constraint = new LogicalNot(
            new ExactInDocument($expected, $pointer, $strict)
        );

        PHPUnitAssert::assertThat($document, $constraint, $message);
    }

public static function assertNotExact ( $ document , $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { $ constraint = new LogicalNot ( new ExactInDocument ( $ expected , $ pointer , $ strict ) ) ; PHPUnitAssert :: assertThat ( $ document , $ constraint , $ message ) ; }

Assert that the value at the specified path is not the expected value.

@param $document
@param $expected
@param string $pointer
@param bool $strict
@param string $message
@return void

Assert that the value at the specified path is not the expected value .


public static function assertList(
        $document,
        array $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        PHPUnitAssert::assertThat(
            $document,
            new OnlySubsetsInList($expected, $pointer, $strict),
            $message
        );
    }

public static function assertList ( $ document , array $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { PHPUnitAssert :: assertThat ( $ document , new OnlySubsetsInList ( $ expected , $ pointer , $ strict ) , $ message ) ; }

Assert that a list in the document only contains the specified hashes.

This assertion does not check that the expected and actual lists are in the same order.
To assert the order, use `assertListInOrder`.

@param $document
@param array $expected
@param string $pointer
@param bool $strict
@param string $message
@return void

Assert that a list in the document only contains the specified hashes .


public static function assertExactList(
        $document,
        array $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        PHPUnitAssert::assertThat(
            $document,
            new OnlyExactInList($expected, $pointer, $strict),
            $message
        );
    }

public static function assertExactList ( $ document , array $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { PHPUnitAssert :: assertThat ( $ document , new OnlyExactInList ( $ expected , $ pointer , $ strict ) , $ message ) ; }

Assert that a list in the document only contains the specified values.

This assertion does not check that the expected and actual lists are in the same order.
To assert the order, use `assertExactListInOrder`.

@param $document
@param array $expected
@param string $pointer
@param bool $strict
@param string $message
@return void

Assert that a list in the document only contains the specified values .


public static function assertListInOrder(
        $document,
        array $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        PHPUnitAssert::assertThat(
            $document,
            new SubsetInDocument($expected, $pointer, $strict),
            $message
        );
    }

public static function assertListInOrder ( $ document , array $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { PHPUnitAssert :: assertThat ( $ document , new SubsetInDocument ( $ expected , $ pointer , $ strict ) , $ message ) ; }

Assert that a list in the document contains the hashes in the specified order.

@param $document
@param array $expected
@param string $pointer
@param bool $strict
@param string $message
@return void

Assert that a list in the document contains the hashes in the specified order .


public static function assertExactListInOrder(
        $document,
        array $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        self::assertExact($document, $expected, $pointer, $strict, $message);
    }

public static function assertExactListInOrder ( $ document , array $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { self :: assertExact ( $ document , $ expected , $ pointer , $ strict , $ message ) ; }

Assert that a list in the document contains the values in the specified order.

@param $document
@param array $expected
@param string $pointer
@param bool $strict
@param string $message
@return void

Assert that a list in the document contains the values in the specified order .


public static function assertIdentifiersList(
        $document,
        array $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        PHPUnitAssert::assertThat(
            $document,
            new OnlyIdentifiersInList($expected, $pointer, $strict),
            $message
        );
    }

public static function assertIdentifiersList ( $ document , array $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { PHPUnitAssert :: assertThat ( $ document , new OnlyIdentifiersInList ( $ expected , $ pointer , $ strict ) , $ message ) ; }

Assert that a list in the document only contains the specified identifiers.

Asserting that a list contains only identifiers will fail if any of the items in the
list is a resource object. I.e. to pass as an identifier, it must not contain
`attributes` and/or `relationships` members.

This assertion does not check that the expected and actual lists are in the same order.
To assert the order, use `assertIdentifiersListInOrder`.

@param $document
@param array $expected
@param string $pointer
@param bool $strict
@param string $message
@return void

Assert that a list in the document only contains the specified identifiers .


public static function assertIdentifiersListInOrder(
        $document,
        array $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        PHPUnitAssert::assertThat(
            $document,
            new IdentifiersInDocument($expected, $pointer, $strict),
            $message
        );
    }

public static function assertIdentifiersListInOrder ( $ document , array $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { PHPUnitAssert :: assertThat ( $ document , new IdentifiersInDocument ( $ expected , $ pointer , $ strict ) , $ message ) ; }

Assert that a list in the document contains the identifiers in the specified order.

Asserting that a list contains only identifiers will fail if any of the items in the
list is a resource object. I.e. to pass as an identifier, it must not contain
`attributes` and/or `relationships` members.

@param $document
@param array $expected
@param string $pointer
@param bool $strict
@param string $message
@return void

Assert that a list in the document contains the identifiers in the specified order .


public static function assertListContainsResource(
        $document,
        string $type,
        string $id,
        string $pointer = '/data',
        string $message = ''
    ): void
    {
        $expected = compact('type', 'id');

        self::assertListContainsHash($document, $expected, $pointer, true, $message);
    }

public static function assertListContainsResource ( $ document , string $ type , string $ id , string $ pointer = '/data' , string $ message = '' ) : void { $ expected = compact ( 'type' , 'id' ) ; self :: assertListContainsHash ( $ document , $ expected , $ pointer , true , $ message ) ; }

Assert that the document has a list containing the expected resource.

@param array|string $document
the JSON API document.
@param string $type
the expected resource object type.
@param string $id
the expected resource object id.
@param string $pointer
the JSON pointer to where the array is expected in the document.
@param string $message
@return void

Assert that the document has a list containing the expected resource .


public static function assertListContainsHash(
        $document,
        array $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        PHPUnitAssert::assertThat(
            $document,
            new SubsetInList($expected, $pointer, $strict),
            $message
        );
    }

public static function assertListContainsHash ( $ document , array $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { PHPUnitAssert :: assertThat ( $ document , new SubsetInList ( $ expected , $ pointer , $ strict ) , $ message ) ; }

Assert that a list in the document at the specified path contains the expected hash.

@param $document
@param array $expected
@param string $pointer
@param bool $strict
@param string $message
@return void

Assert that a list in the document at the specified path contains the expected hash .


public static function assertListContainsExact(
        $document,
        array $expected,
        string $pointer = '/data',
        bool $strict = true,
        string $message = ''
    ): void
    {
        PHPUnitAssert::assertThat(
            $document,
            new ExactInList($expected, $pointer, $strict),
            $message
        );
    }

public static function assertListContainsExact ( $ document , array $ expected , string $ pointer = '/data' , bool $ strict = true , string $ message = '' ) : void { PHPUnitAssert :: assertThat ( $ document , new ExactInList ( $ expected , $ pointer , $ strict ) , $ message ) ; }

Assert that a list in the document at the specified path contains the expected value.

@param $document
@param array $expected
@param string $pointer
@param bool $strict
@param string $message
@return void

Assert that a list in the document at the specified path contains the expected value .


public static function assertIncludedContainsHash(
        $document,
        array $expected,
        bool $strict = true,
        string $message = ''
    ): void
    {
        self::assertListContainsHash($document, $expected, '/included', $strict, $message);
    }

public static function assertIncludedContainsHash ( $ document , array $ expected , bool $ strict = true , string $ message = '' ) : void { self :: assertListContainsHash ( $ document , $ expected , '/included' , $ strict , $ message ) ; }

Assert that the included member contains the supplied hash.

@param $document
@param array $expected
@param bool $strict
@param string $message
@return void

Assert that the included member contains the supplied hash .


public static function assertExactError($document, array $error, bool $strict = true, string $message = ''): void
    {
        self::assertExactList($document, [$error], '/errors', $strict, $message);
    }

public static function assertExactError ( $ document , array $ error , bool $ strict = true , string $ message = '' ) : void { self :: assertExactList ( $ document , [ $ error ] , '/errors' , $ strict , $ message ) ; }

Assert the document contains a single error that exactly matches the supplied error.

@param $document
@param array $error
@param bool $strict
@param string $message
@return void

Assert the document contains a single error that exactly matches the supplied error .


public static function assertHasError($document, array $error, bool $strict = true, string $message = ''): void
    {
        self::assertListContainsHash($document, $error, '/errors', $strict, $message);
    }

public static function assertHasError ( $ document , array $ error , bool $ strict = true , string $ message = '' ) : void { self :: assertListContainsHash ( $ document , $ error , '/errors' , $ strict , $ message ) ; }

Assert the document contains the supplied error within its errors member.

@param $document
@param array $error
@param bool $strict
@param string $message
@return void

Assert the document contains the supplied error within its errors member .


public static function assertHasExactError(
        $document,
        array $error,
        bool $strict = true,
        string $message = ''
    ): void
    {
        self::assertListContainsExact($document, $error, '/errors', $strict, $message);
    }

public static function assertHasExactError ( $ document , array $ error , bool $ strict = true , string $ message = '' ) : void { self :: assertListContainsExact ( $ document , $ error , '/errors' , $ strict , $ message ) ; }

Assert the document contains the exact supplied error within its errors member.

@param $document
@param array $error
@param bool $strict
@param string $message
@return void

Assert the document contains the exact supplied error within its errors member .


public static function create($content): ?self
    {
        if (is_string($content)) {
            return self::fromString($content);
        }

        return $content ? self::cast($content) : null;
    }

public static function create ( $ content ) : ? self { if ( is_string ( $ content ) ) { return self :: fromString ( $ content ) ; } return $ content ? self :: cast ( $ content ) : null ; }

Safely create a document.

@param $content
@return Document|null


public static function cast($document): self
    {
        if ($document instanceof self) {
            return $document;
        }

        if (is_string($document)) {
            return self::decode($document);
        }

        return self::fromIterable($document);
    }

public static function cast ( $ document ) : self { if ( $ document instanceof self ) { return $ document ; } if ( is_string ( $ document ) ) { return self :: decode ( $ document ) ; } return self :: fromIterable ( $ document ) ; }

Cast a document to an instance of this document class.

@param Document|array|string $document
@return Document

Cast a document to an instance of this document class .


public static function fromString(string $json): ?self
    {
        $document = \json_decode($json, true);

        if (JSON_ERROR_NONE !== \json_last_error() || !\is_array($document)) {
            return null;
        }

        return new self($document);
    }

public static function fromString ( string $ json ) : ? self { $ document = \ json_decode ( $ json , true ) ; if ( JSON_ERROR_NONE !== \ json_last_error ( ) || ! \ is_array ( $ document ) ) { return null ; } return new self ( $ document ) ; }

Create a document from a string.

@param string $json
@return Document|null


public static function decode(string $json): self
    {
        if (!$document = self::fromString($json)) {
            throw new \InvalidArgumentException('Invalid JSON string.');
        }

        return $document;
    }

public
static
function
decode
(
string
$
json
)
:
self
{
if
(
!
$
document
=
self
::
fromString
(
$
json
)
)
{
throw
new
\
InvalidArgumentException
(
'Invalid JSON string.'
)
;
}
return
$
document
;
}

Decode a JSON string into a document.

@param string $json
@return Document


public function get(string $pointer, $default = null)
    {
        if (!$path = Compare::path($pointer)) {
            return $this->document;
        }

        return Arr::get($this->document, $path, $default);
    }

public function get ( string $ pointer , $ default = null ) { if ( ! $ path = Compare :: path ( $ pointer ) ) { return $ this -> document ; } return Arr :: get ( $ this -> document , $ path , $ default ) ; }

Get a value from using a JSON pointer.

@param string $pointer
@param mixed|null $default
@return mixed


public function has(string ...$pointers): bool
    {
        $paths = collect($pointers)->map(function ($pointer) {
            return Compare::path($pointer);
        })->filter()->all();

        return Arr::has($this->document, $paths);
    }

public function has ( string ... $ pointers ) : bool { $ paths = collect ( $ pointers ) -> map ( function ( $ pointer ) { return Compare :: path ( $ pointer ) ; } ) -> filter ( ) -> all ( ) ; return Arr :: has ( $ this -> document , $ paths ) ; }

Check if an item exists using JSON pointers.

@param string ...$pointers
@return bool

Check if an item exists using JSON pointers .


public function assertExists($pointers, string $message = ''): self
    {
        $missing = collect((array) $pointers)->reject(function ($pointer) {
            return $this->has($pointer);
        })->implode(', ');

        PHPUnitAssert::assertEmpty($missing, $message ?: "Members [{$missing}] do not exist.");

        return $this;
    }

public
function
assertExists
(
$
pointers
,
string
$
message
=
''
)
:
self
{
$
missing
=
collect
(
(
array
)
$
pointers
)
->
reject
(
function
(
$
pointer
)
{
return
$
this
->
has
(
$
pointer
)
;
}
)
->
implode
(
', '
)
;
PHPUnitAssert
::
assertEmpty
(
$
missing
,
$
message
:
"Members [{$missing}] do not exist."
)
;
return
$
this
;
}

Assert that all the provided members exist.

@param string|string[] $pointers
@param string $message
@return $this

Assert that all the provided members exist .


public function assertNotExists($pointers, string $message = ''): self
    {
        $unexpected = collect((array) $pointers)->filter(function ($pointer) {
            return $this->has($pointer);
        })->implode(', ');

        PHPUnitAssert::assertEmpty($unexpected, $message ?: "Members [{$unexpected}] exist.");

        return $this;
    }

public
function
assertNotExists
(
$
pointers
,
string
$
message
=
''
)
:
self
{
$
unexpected
=
collect
(
(
array
)
$
pointers
)
->
filter
(
function
(
$
pointer
)
{
return
$
this
->
has
(
$
pointer
)
;
}
)
->
implode
(
', '
)
;
PHPUnitAssert
::
assertEmpty
(
$
unexpected
,
$
message
:
"Members [{$unexpected}] exist."
)
;
return
$
this
;
}

Assert that the provided members do not exist.

@param string|string[] $pointers
@param string $message
@return Document

Assert that the provided members do not exist .


public static function exact($expected, $actual, bool $strict = true): bool
    {
        $expected = self::normalize($expected);
        $actual = self::normalize($actual);

        if ($strict) {
            return $expected === $actual;
        }

        return $expected == $actual;
    }

public static function exact ( $ expected , $ actual , bool $ strict = true ) : bool { $ expected = self :: normalize ( $ expected ) ; $ actual = self :: normalize ( $ actual ) ; if ( $ strict ) { return $ expected === $ actual ; } return $ expected == $ actual ; }

Does the actual value match the expected value?

@param array $expected
@param $actual
@param bool $strict
@return bool


public static function subset(array $expected, $actual, bool $strict = true): bool
    {
        if (!is_array($actual)) {
            return false;
        }

        $patched = self::patch($actual, $expected);

        return self::exact($patched, $actual, $strict);
    }

public static function subset ( array $ expected , $ actual , bool $ strict = true ) : bool { if ( ! is_array ( $ actual ) ) { return false ; } $ patched = self :: patch ( $ actual , $ expected ) ; return self :: exact ( $ patched , $ actual , $ strict ) ; }

Does the expected subset appear within the actual value?

@param array $expected
@param $actual
@param bool $strict
@return bool


public static function resourceIdentifier($value): bool
    {
        if (!is_array($value)) {
            return false;
        }

        $members = collect($value);

        return $members->has('type') &&
            $members->has('id') &&
            !$members->has('attributes') &&
            !$members->has('relationships');
    }

public static function resourceIdentifier ( $ value ) : bool { if ( ! is_array ( $ value ) ) { return false ; } $ members = collect ( $ value ) ; return $ members -> has ( 'type' ) && $ members -> has ( 'id' ) && ! $ members -> has ( 'attributes' ) && ! $ members -> has ( 'relationships' ) ; }

Is the supplied value a resource identifier?

A resource identifier must have a type and id member. It must not have attributes
or relationship members, otherwise it is a resource object.

- attributes
- relationships

@param $value
@return bool


public static function sort(array $value): array
    {
        if (self::hash($value)) {
            ksort($value);
        }

        return collect($value)->map(function ($item) {
            return self::normalize($item);
        })->all();
    }

public static function sort ( array $ value ) : array { if ( self :: hash ( $ value ) ) { ksort ( $ value ) ; } return collect ( $ value ) -> map ( function ( $ item ) { return self :: normalize ( $ item ) ; } ) -> all ( ) ; }

Recursively sort a JSON hash or JSON list for comparison.

@param array $value
@return array

Recursively sort a JSON hash or JSON list for comparison .


public static function identifiable($value): bool
    {
        return $value instanceof UrlRoutable ||
            is_string($value) ||
            is_int($value) ||
            self::hash($value);
    }

public static function identifiable ( $ value ) : bool { return $ value instanceof UrlRoutable || is_string ( $ value ) || is_int ( $ value ) || self :: hash ( $ value ) ; }

Does the value identify a resource?

@param $value
@return bool


protected function sendRequest()
    {
        if ($this->nextToken) {
            $this->command->set('page', $this->nextToken);
        }

        $result = $this->command->execute();
        $currentToken = $result['paging']['page'];
        $this->nextToken = $result['paging']['pages'] > $currentToken ? ++$currentToken : false;

        return $result['files'];
    }

protected function sendRequest ( ) { if ( $ this -> nextToken ) { $ this -> command -> set ( 'page' , $ this -> nextToken ) ; } $ result = $ this -> command -> execute ( ) ; $ currentToken = $ result [ 'paging' ] [ 'page' ] ; $ this -> nextToken = $ result [ 'paging' ] [ 'pages' ] > $ currentToken ? ++ $ currentToken : false ; return $ result [ 'files' ] ; }

Send a request to retrieve the next page of results. Hook for subclasses to implement.

@return array Returns the newly loaded resources

Send a request to retrieve the next page of results . Hook for subclasses to implement .


public function tell($user, $text)
    {
        return $this->say($this->sequencer->format('@'.$user).' '.$text);
    }

public
function
tell
(
$
user
,
$
text
)
{
return
$
this
->
say
(
$
this
->
sequencer
->
format
(
'@'
.
$
user
)
.
' '
.
$
text
)
;
}

Send a message to a user.

@param string $user user_id
{@inheritdoc}


public function reply($user, $text)
    {
        if ($user instanceof CommandInterface) {
            $sequence = $this->sequencer->command($user);

            return $this->say($sequence['user'].' '.$text);
        }

        return $this->tell($user, $text);
    }

public
function
reply
(
$
user
,
$
text
)
{
if
(
$
user
instanceof
CommandInterface
)
{
$
sequence
=
$
this
->
sequencer
->
command
(
$
user
)
;
return
$
this
->
say
(
$
sequence
[
'user'
]
.
' '
.
$
text
)
;
}
return
$
this
->
tell
(
$
user
,
$
text
)
;
}

Respond with a reply to a user.

@param CommandInterface|string user_id, or a CommandInterface containing user_id and user_name.
@param $text

@return Reply


public function setTypesAllowed($allowedTypes = null)
    {
        if (!$this->isLatest()) {
            return $this->setAllowedTypes($allowedTypes);
        }

        foreach ($allowedTypes as $option => $typesAllowed) {
            $this->setAllowedTypes($option, $typesAllowed);
        }

        return $this;
    }

public function setTypesAllowed ( $ allowedTypes = null ) { if ( ! $ this -> isLatest ( ) ) { return $ this -> setAllowedTypes ( $ allowedTypes ) ; } foreach ( $ allowedTypes as $ option => $ typesAllowed ) { $ this -> setAllowedTypes ( $ option , $ typesAllowed ) ; } return $ this ; }

Set a list of allowed types for the given option.

@see Symfony\Component\OptionsResolver\OptionsResolver::setAllowedTypes()

@param array $allowedTypes

@return $this

Set a list of allowed types for the given option .


public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
	{
		if (!is_array($messages))
		{
			$messages = array($messages);
		}

		foreach ($messages as $message)
		{
			$this->buffer .= $this->parse($message);
			if ($newline)
			{
				$this->buffer .= "\n";
			}
		}
	}

public function write ( $ messages , $ newline = false , $ type = self :: OUTPUT_NORMAL ) { if ( ! is_array ( $ messages ) ) { $ messages = array ( $ messages ) ; } foreach ( $ messages as $ message ) { $ this -> buffer .= $ this -> parse ( $ message ) ; if ( $ newline ) { $ this -> buffer .= "\n" ; } } }

Writes a message to the output.

@param string|array $messages The message as an array of lines or a single string
@param bool         $newline  Whether to add a newline
@param int          $type     The type of output (one of the OUTPUT constants)

@throws \InvalidArgumentException When unknown output type is given

@api


public function writelnIfDebug($message)
	{
		if ($this->debug)
		{
			$this->debugMessages[] = new Message(Output::DEBUG, $message, null);
		}
	}

public function writelnIfDebug ( $ message ) { if ( $ this -> debug ) { $ this -> debugMessages [ ] = new Message ( Output :: DEBUG , $ message , null ) ; } }

Write a message to the output, but only if Debug is enabled.

@param $message string|array $messages The message as an array of lines of a single string

@throws \InvalidArgumentException When unknown output type is given

Write a message to the output but only if Debug is enabled .


public function addMessage($type, $message, FileInterface $file = null)
	{
		switch ($type)
		{
			case Output::FATAL:
				$this->fatal++;
				break;
			case Output::ERROR:
				$this->error++;
				break;
			case Output::WARNING:
				$this->warning++;
				break;
			case Output::NOTICE:
				$this->notice++;
				break;
			case Output::DEBUG:
				break;
			default:
				// TODO: Decide on this?
		}
		$this->messages[] = new Message($type, $message, $file);
	}

public
function
addMessage
(
$
type
,
$
message
,
FileInterface
$
file
=
)
{
switch
(
$
type
)
{
case
Output
::
FATAL
:
$
this
->
fatal
++
;
break
;
case
Output
::
ERROR
:
$
this
->
error
++
;
break
;
case
Output
::
WARNING
:
$
this
->
warning
++
;
break
;
case
Output
::
NOTICE
:
$
this
->
notice
++
;
break
;
case
Output
::
DEBUG
:
break
;
default
:
// TODO: Decide on this?
}
$
this
->
messages
[
]
=
new
Message
(
$
type
,
$
message
,
$
file
)
;
}

Add a new message to the output of the validator.

@param                                $type    int message type
@param                                $message string message
@param \Phpbb\Epv\Files\FileInterface $file    File the error happened in. When provided, this is displayed to the user

Add a new message to the output of the validator .


public function getMessageCount($type)
	{
		switch ($type)
		{
			case Output::FATAL:
				return $this->fatal;
			case Output::ERROR:
				return $this->error;
			case Output::WARNING:
				return $this->warning;
			case Output::NOTICE:
				return $this->notice;
		}
	}

public function getMessageCount ( $ type ) { switch ( $ type ) { case Output :: FATAL : return $ this -> fatal ; case Output :: ERROR : return $ this -> error ; case Output :: WARNING : return $ this -> warning ; case Output :: NOTICE : return $ this -> notice ; } }

Get the count for a type;

@param $type

@return mixed


public function get_vars_from_single_line_array($line, $throw_multiline = true)
	{
		$match = array();
		preg_match('#^\$vars = (?:(\[)|array\()\'([a-z0-9_\' ,]+)\'(?(1)\]|\));$#i', $line, $match);

		if (isset($match[2]))
		{
			$vars_array = explode("', '", $match[2]);
			if ($throw_multiline && sizeof($vars_array) > 6)
			{
				throw new \LogicException('Should use multiple lines for $vars definition '
					. "for event '{$this->current_event}' in file '{$this->current_clean_file}:{$this->current_event_line}'", 2);
			}

			return $vars_array;
		}
		else
		{
			throw new \LogicException("Can not find '\$vars = array();'-line for event '{$this->current_event}' in file '{$this->current_clean_file}:{$this->current_event_line}'. Are you using UNIX style linefeeds?", 1);
		}
	}

Find the variables in a single line array

@param    string $line
@param    bool   $throw_multiline      Throw an exception when there are too
many arguments in one line.

@return array        List of variables
@throws \LogicException


public function get_vars_from_multi_line_array()
	{
		$current_vars_line = 2;
		$var_lines         = array();
		while (!in_array(ltrim($this->file_lines[$this->current_event_line - $current_vars_line], "\t"), ['$vars = array(', '$vars = [']))
		{
			$var_lines[] = substr(trim($this->file_lines[$this->current_event_line - $current_vars_line]), 0, -1);

			$current_vars_line++;
			if ($current_vars_line > $this->current_event_line)
			{
				// Reached the start of the file
				throw new \LogicException("Can not find end of \$vars array for event '{$this->current_event}' in file '{$this->current_clean_file}:{$this->current_event_line}'.", 2);
			}
		}

		return $this->get_vars_from_single_line_array('$vars = array(' . implode(", ", $var_lines) . ');', false);
	}

Find the variables in a multi line array

@return array        List of variables
@throws \LogicException


public function validate_vars_docblock_array($vars_array, $vars_docblock)
	{
		$vars_array        = array_unique($vars_array);
		$vars_docblock     = array_unique($vars_docblock);
		$sizeof_vars_array = sizeof($vars_array);

		if ($sizeof_vars_array !== sizeof($vars_docblock) || $sizeof_vars_array !== sizeof(array_intersect($vars_array, $vars_docblock)))
		{
			throw new \LogicException("\$vars array does not match the list of '@var' tags for event "
				. "'{$this->current_event}' in file '{$this->current_clean_file}:{$this->current_event_line}'");
		}
	}

Validates that two arrays contain the same strings

@param array $vars_array    Variables found in the array line
@param array $vars_docblock Variables found in the doc block

@return null
@throws \LogicException


public function all($strategy = null)
    {
        if ($this instanceof \Iterator) {
            $strategy = conversions\mixed_to_value_getter($strategy);

            foreach ($this as $item) {
                $tempVarPhp54 = call_user_func($strategy, $item);
                if (empty($tempVarPhp54)) {
                    return false;
                }
            }

            return true;
        }

        return null;
    }

public function all ( $ strategy = null ) { if ( $ this instanceof \ Iterator ) { $ strategy = conversions \ mixed_to_value_getter ( $ strategy ) ; foreach ( $ this as $ item ) { $ tempVarPhp54 = call_user_func ( $ strategy , $ item ) ; if ( empty ( $ tempVarPhp54 ) ) { return false ; } } return true ; } return null ; }

Returns true when all elements of this iterable are not empty, otherwise returns false

When the optional $STRATEGY argument is given, this argument is used to obtain the
value which is tested to be empty.

> iterable([1, 'hello world', true])->all()
true

> iterable([1, null, 3])->all()
false

@param null|string|\Closure $strategy Optional, when not specified !empty will be used
@return null|bool

Returns true when all elements of this iterable are not empty otherwise returns false


public function accumulate($closure = 'add')
    {
        if ($this instanceof \Iterator) {
            return new AccumulateIterator(
                $this,
                $closure instanceof \Closure ? $closure : reductions\get_reduction($closure)
            );
        }

        return null;
    }

public function accumulate ( $ closure = 'add' ) { if ( $ this instanceof \ Iterator ) { return new AccumulateIterator ( $ this , $ closure instanceof \ Closure ? $ closure : reductions \ get_reduction ( $ closure ) ) ; } return null ; }

Returns an iterator that containing accumulated elements

If the optional $closure argument is supplied, it should be a string:
add, sub, mul, min, or max.  Or it can be a Closure taking two
arguments that will be used to instead of addition.

> iter\iterable([1,2,3,4,5])->accumulate()
1 3 6 10 15

> iter\iterable(['One', 'Two', 'Three'])->accumulate(function ($a, $b) { return $a . $b; })
'One' 'OneTwo' 'OneTwoThree'

@param string|\Closure $closure
@return null|AccumulateIterator


protected function mergeSort(array &$array, \Closure $cmp_function)
    {
        // Arrays of size < 2 require no action.
        if (count($array) < 2) {
            return;
        }

        // Split the array in half
        $halfway = count($array) / 2;
        $array1 = array_slice($array, 0, $halfway);
        $array2 = array_slice($array, $halfway);

        // Recurse to sort the two halves
        $this->mergesort($array1, $cmp_function);
        $this->mergesort($array2, $cmp_function);

        // If all of $array1 is <= all of $array2, just append them.
        if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
            $array = array_merge($array1, $array2);
            return;
        }

        // Merge the two sorted arrays into a single sorted array
        $array = [];
        $ptr1 = $ptr2 = 0;
        while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
            if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
                $array[] = $array1[$ptr1++];
            } else {
                $array[] = $array2[$ptr2++];
            }
        }

        // Merge the remainder
        while ($ptr1 < count($array1)) {
            $array[] = $array1[$ptr1++];
        }
        while ($ptr2 < count($array2)) {
            $array[] = $array2[$ptr2++];
        }
        return;
    }

As the manual says, "If two members compare as equal, their
order in the sorted array is undefined."  This means that the
sort used is not "stable" and may change the order of elements
that compare equal.

Sometimes you really do need a stable sort. For example, if you
sort a list by one field, then sort it again by another field,
but don't want to lose the ordering from the previous field.
In that case it is better to use usort with a comparison
function that takes both fields into account, but if you can't
do that then use the function below. It is a merge sort, which
is guaranteed O(n*log(n)) complexity, which means it stays
reasonably fast even when you use larger lists (unlike
bubblesort and insertion sort, which are O(n^2)).

http://www.php.net/manual/en/function.usort.php#38827

@param array $array
@param \Closure $cmp_function

As the manual says If two members compare as equal their order in the sorted array is undefined . This means that the sort used is not stable and may change the order of elements that compare equal .


public function toArray()
    {
        if ($this instanceof \Traversable) {
            $array = iterator_to_array($this);
            array_walk(
                $array,
                function (&$value) {
                    if ($value instanceof FiniteIterableInterface) {
                        $value = $value->toArray();
                    }
                }
            );
            return $array;
        } else {
            return [];
        }
    }

public function toArray ( ) { if ( $ this instanceof \ Traversable ) { $ array = iterator_to_array ( $ this ) ; array_walk ( $ array , function ( & $ value ) { if ( $ value instanceof FiniteIterableInterface ) { $ value = $ value -> toArray ( ) ; } } ) ; return $ array ; } else { return [ ] ; } }

Returns an unsafe array built from this iterator

Note that when the iterator contains overlapping keys, that
these will be *lost* when converting to an array.

A safer option is to use either
- $iterable->keys(),
- $iterable->values(), or
- $iterable->items()

@return array


public function keys()
    {
        $keys = [];
        if ($this instanceof \Traversable) {
            foreach ($this as $key => $value) {
                $keys [] = $key;
            }
        }
        return $keys;
    }

public function keys ( ) { $ keys = [ ] ; if ( $ this instanceof \ Traversable ) { foreach ( $ this as $ key => $ value ) { $ keys [ ] = $ key ; } } return $ keys ; }

Returns an array with keys from this iterator

@return array


public function zip(/* $iterable, $iterable2, ... */)
    {
        if ($this instanceof \Iterator) {
            $iterables = array_map(
                '\Zicht\Itertools\conversions\mixed_to_iterator',
                func_get_args()
            );
            $reflectorClass = new \ReflectionClass('\Zicht\Itertools\lib\ZipIterator');
            return $reflectorClass->newInstanceArgs(array_merge([$this], $iterables));
        }

        return null;
    }

Returns an iterator where one or more iterables are zipped together

This function returns a list of tuples, where the i-th tuple contains
the i-th element from each of the argument sequences or iterables.

The returned list is truncated in length to the length of the
shortest argument sequence.

> zip([1, 2, 3], ['a', 'b', 'c'])
[1, 'a'] [2, 'b'] [3, 'c']

@param array|string|\Iterator $iterable
@param array|string|\Iterator $iterable2
@return ZipIterator


public function values()
    {
        $values = [];
        if ($this instanceof \Traversable) {
            foreach ($this as $key => $value) {
                $values [] = $value instanceof FiniteIterableInterface ? $value->values() : $value;
            }
        }
        return $values;
    }

public function values ( ) { $ values = [ ] ; if ( $ this instanceof \ Traversable ) { foreach ( $ this as $ key => $ value ) { $ values [ ] = $ value instanceof FiniteIterableInterface ? $ value -> values ( ) : $ value ; } } return $ values ; }

Returns an array with values from this iterator

@return array


public function reduce($closure = 'add', $initializer = null)
    {
        if ($this instanceof \Iterator) {
            $closure = $closure instanceof \Closure ? $closure : Itertools\reductions\get_reduction($closure);
            $this->rewind();

            if (null === $initializer) {
                if ($this->valid()) {
                    $initializer = $this->current();
                    $this->next();
                }
            }

            $accumulatedValue = $initializer;
            while ($this->valid()) {
                $accumulatedValue = $closure($accumulatedValue, $this->current());
                $this->next();
            }

            return $accumulatedValue;
        }

        return null;
    }

public function reduce ( $ closure = 'add' , $ initializer = null ) { if ( $ this instanceof \ Iterator ) { $ closure = $ closure instanceof \ Closure ? $ closure : Itertools \ reductions \ get_reduction ( $ closure ) ; $ this -> rewind ( ) ; if ( null === $ initializer ) { if ( $ this -> valid ( ) ) { $ initializer = $ this -> current ( ) ; $ this -> next ( ) ; } } $ accumulatedValue = $ initializer ; while ( $ this -> valid ( ) ) { $ accumulatedValue = $ closure ( $ accumulatedValue , $ this -> current ( ) ) ; $ this -> next ( ) ; } return $ accumulatedValue ; } return null ; }

Reduce an iterator to a single value

> iter\iterable([1,2,3])->reduce()
6

> iter\iterable([1,2,3])->reduce('max')
3

> iter\iterable([1,2,3])->reduce('sub', 10)
4

> iter\iterable([])->reduce('min', 1)
1

@param string|\Closure $closure
@param mixed $initializer
@return mixed


protected function genericKeysToKey($keysAndValues)
    {
        $keys = array_splice($keysAndValues, 0, count($keysAndValues) / 2);

        if (count($keys) == 1) {
            return $keys[0];
        }

        $value = $keys[0];
        foreach ($keys as $key) {
            if ($key !== $value) {
                // the keys are different, we will make a new string identifying this entry
                return join(
                    ':',
                    array_map(
                        function ($key) {
                            return (string)$key;
                        },
                        $keys
                    )
                );
            }
        }

        // all values are the same, use it
        return $value;
    }

Compute the key for an element

When multiple iterables are given, the key for an element is computed by taking
the keys of the element of all iterables, when they are the same, this key is used,
otherwise a compound key is created by concatenating the keys together.

@param array $keysAndValues
@return mixed


public function groupBy($strategy, $sort = true)
    {
        if (!is_bool($sort)) {
            throw new \InvalidArgumentException('Argument $sort must be a boolean');
        }

        if ($this instanceof \Iterator) {
            return new GroupbyIterator(
                conversions\mixed_to_value_getter($strategy),
                $sort ? $this->sorted($strategy) : $this
            );
        }

        return null;
    }

public
function
groupBy
(
$
strategy
,
$
sort
=
true
)
{
if
(
!
is_bool
(
$
sort
)
)
{
throw
new
\
InvalidArgumentException
(
'Argument $sort must be a boolean'
)
;
}
if
(
$
this
instanceof
\
Iterator
)
{
return
new
GroupbyIterator
(
conversions
\
mixed_to_value_getter
(
$
strategy
)
,
$
sort
$
this
->
sorted
(
$
strategy
)
:
$
this
)
;
}
return
;
}

Make an iterator that returns consecutive groups from this
iterable.  Generally, this iterable needs to already be sorted on
the same key function.

When $strategy is a string, the key is obtained through one of
the following:
1. $value->{$strategy}, when $value is an object and
$strategy is an existing property,
2. call $value->{$strategy}(), when $value is an object and
$strategy is an existing method,
3. $value[$strategy], when $value is an array and $strategy
is an existing key,
4. otherwise the key will default to null.

Alternatively $strategy can be a closure.  In this case the
$strategy closure is called with each value in this iterable and the
key will be its return value.  $strategy is called with two
parameters: the value and the key of the iterable as the first and
second parameter, respectively.

The operation of groupBy() is similar to the uniq filter in Unix.
It generates a break or new group every time the value of the key
function changes (which is why it is usually necessary to have
sorted the data using the same key function).  That behavior
differs from SQL's GROUP BY which aggregates common elements
regardless of their input order.

> $list = [['type'=>'A', 'title'=>'one'], ['type'=>'A', 'title'=>'two'], ['type'=>'B', 'title'=>'three']]
> iter\iterable($list)->groupBy('type')
'A'=>[['type'=>'A', 'title'=>'one'], ['type'=>'A', 'title'=>'two']] 'B'=>[['type'=>'B', 'title'=>'three']]

@param null|string|\Closure $strategy
@param bool $sort
@return GroupbyIterator

Make an iterator that returns consecutive groups from this iterable . Generally this iterable needs to already be sorted on the same key function .


public function reduce($iterable, $closure = 'add', $initializer = null)
    {
        return Itertools\reduce($iterable, $closure, $initializer);
    }

public function reduce ( $ iterable , $ closure = 'add' , $ initializer = null ) { return Itertools \ reduce ( $ iterable , $ closure , $ initializer ) ; }

Reduce an iterable to a single value

Simple examples:
{{ [1,2,3]|reduce }} --> 6
{{ [1,2,3]|reduce('max') }} --> 3

Sro example to get the prices for all items in the basket:
{{ transaction_snapshot.Basket.Items|map('TotalPrice.Amount')|reduce }}

@param array|string|\Iterator $iterable
@param string|\Closure $closure
@param mixed $initializer
@return mixed


public function reducing($name)
    {
        // note, once we stop supporting php 5.5, we can rewrite the code below
        // to the reducing($name, ...$args) structure.
        // http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

        if (is_string($name) &&
            in_array(
                $name,
                [
                    'add',
                    'chain',
                    'join',
                    'max',
                    'min',
                    'mul',
                    'sub',
                ]
            )) {
            return call_user_func_array(sprintf('\Zicht\Itertools\reductions\%s', $name), array_slice(func_get_args(), 1));
        }

        throw new \InvalidArgumentException(sprintf('$NAME "%s" is not a valid reduction.', $name));
    }

Returns a reduction closure

Any parameters provided, beyond $name, are passed directly to the underlying
reduction.  This can be used to, for example, provide a $glue when using join.

@param string $name
@return \Closure
@throws \InvalidArgumentException


public static function dump(Event $event)
    {
        $composer            = $event->getComposer();
        $installationManager = $composer->getInstallationManager();
        $repoManager         = $composer->getRepositoryManager();
        $localRepo           = $repoManager->getLocalRepository();
        $package             = $composer->getPackage();
        $config              = $composer->getConfig();

        // To enable class-based filtering, we force `--optimize` flag for our
        // custom autoloaders, so that all PSR-0 and PSR-4 namespaces are
        // iterated and translated to arrays of classes.
        $optimize = true;

        $vendorDir       = $config->get('vendor-dir', Config::RELATIVE_PATHS);
        $defaultLocation = "{$vendorDir}/wp-cli/wp-cli/php/WP_CLI/AutoloadSplitter.php";
        $suffix          = $config->get('autoloader-suffix');

        self::$extra = $event->getComposer()
            ->getPackage()
            ->getExtra();

        $splitterLogic    = self::getExtraKey(self::LOGIC_CLASS_KEY, 'WP_CLI\AutoloadSplitter');
        $splitterLocation = self::getExtraKey(self::LOGIC_CLASS_LOCATION_KEY, $defaultLocation);
        $filePrefixTrue   = self::getExtraKey(self::SPLIT_TARGET_PREFIX_TRUE_KEY, 'autoload_commands');
        $filePrefixFalse  = self::getExtraKey(self::SPLIT_TARGET_PREFIX_FALSE_KEY, 'autoload_framework');

        if (!class_exists($splitterLogic)) {
            $splitterClassPath = sprintf('%s/%s', getcwd(), $splitterLocation);

            // Avoid proceeding if the splitter class file does not exist.
            if (!is_readable( $splitterClassPath)) {
                return;
            }

            include_once $splitterClassPath;
        }

        $generator = new AutoloadGenerator(
            $composer->getEventDispatcher(),
            $event->getIO(),
            $splitterLogic,
            $filePrefixTrue,
            $filePrefixFalse
        );

        $generator->dump(
            $config,
            $localRepo,
            $package,
            $installationManager,
            'composer',
            $optimize,
            $suffix
        );
    }

Dump the event for discovery purposes.

@param Event $event Event that was triggered.


private static function getExtraKey($key, $fallback)
    {
        static $autosplitter = null;

        if (null === $autosplitter) {
            $autosplitter = isset(self::$extra[self::EXTRA_KEY])
                ? self::$extra[self::EXTRA_KEY]
                : array();
        }

        return isset($autosplitter[$key]) ? $autosplitter[$key] : $fallback;
    }

private static function getExtraKey ( $ key , $ fallback ) { static $ autosplitter = null ; if ( null === $ autosplitter ) { $ autosplitter = isset ( self :: $ extra [ self :: EXTRA_KEY ] ) ? self :: $ extra [ self :: EXTRA_KEY ] : array ( ) ; } return isset ( $ autosplitter [ $ key ] ) ? $ autosplitter [ $ key ] : $ fallback ; }

Get the value of a config key from the "Extra" section.

@param string $key      Key to look for.
@param string $fallback Fallback value to use if the key was not provided.

@return string

Get the value of a config key from the Extra section .


public static function escapePrefix($predicate, array $namespaces) {

    $exploded = explode(":", $predicate);
    if (!isset($namespaces[$exploded[0]])) {
      return $predicate;
    }
    return $namespaces[$exploded[0]] . $exploded[1];
  }

public static function escapePrefix ( $ predicate , array $ namespaces ) { $ exploded = explode ( ":" , $ predicate ) ; if ( ! isset ( $ namespaces [ $ exploded [ 0 ] ] ) ) { return $ predicate ; } return $ namespaces [ $ exploded [ 0 ] ] . $ exploded [ 1 ] ; }

Escapes namespace prefixes in predicates.

@param string $predicate
The predicate whose namespace you wish to escape.
@param array $namespaces
Associative array of namespaces keyed by prefix.

@return string
The predicate with escaped namespace prefix.

Escapes namespace prefixes in predicates .


protected function parseCompactedIri($iri) {
    // As naive as it gets.
    list($prefix, $rest) = array_pad(explode(":", $iri, 2), 2, '');
    if ((substr($rest, 0, 2) == "//") || ($prefix == $iri)) {
      // Means this was never a compacted IRI.
      return ['prefix' => NULL, 'term' => $iri];
    }
    return ['prefix' => $prefix, 'term' => $rest];
  }

Parses and IRI, checks if it is complaint with compacted IRI definition.

Assumes this notion of compact IRI/similar to CURIE
http://json-ld.org/spec/ED/json-ld-syntax/20120522/#dfn-prefix.

@param string $iri
IRIs are strings.

@return array
If $iri is a compacted iri, prefix and term as separate
array members, if not, unmodified $iri in term position
and null prefix.

Parses and IRI checks if it is complaint with compacted IRI definition .


protected function getTermContextFromField($field_type) {
    // Be aware that drupal field definitions can be complex.
    // e.g text_with_summary has a text, a summary, a number of lines, etc
    // we are only dealing with the resulting ->value() of all this separate
    // pieces and mapping only that as a whole.
    // Default mapping to return in case no $field_type matches
    // field_mappings array keys.
    $default_mapping = [
      "@type" => "xsd:string",
    ];

    // Only load mappings from hooks if we haven't done it
    // yet for this instance.
    if (empty($this->fieldMappings)) {
      // Cribbed from rdf module's rdf_get_namespaces.
      foreach (\Drupal::moduleHandler()->getImplementations(self::FIELD_MAPPPINGS_HOOK) as $module) {
        $function = $module . '_' . self::FIELD_MAPPPINGS_HOOK;
        foreach ($function() as $field => $mapping) {
          if (array_key_exists($field, $this->fieldMappings)) {
            $this->logger->warning(
              t('Tried to map @field_type to @new_type, but @field_type is already mapped to @orig_type.', [
                '@field_type' => $field,
                '@new_type' => $mapping['@type'],
                '@orig_type' => $this->fieldMappings[$field]['@type'],
              ])
            );
          }
          else {
            $this->fieldMappings[$field] = $mapping;
          }
        }
      }
    }
    return array_key_exists($field_type, $this->fieldMappings) ? $this->fieldMappings[$field_type] : $default_mapping;
  }

Naive approach on Drupal field to JSON-LD type mapping.

TODO: Would be fine to have this definitions in an
configEntity way in the future.

@param string $field_type
As provided by \Drupal\Core\Field\FieldDefinitionInterface::getType().

@return array
A json-ld term definition if there is a match
or array("@type" => "xsd:string") in case of no match.

Naive approach on Drupal field to JSON - LD type mapping .


public function persistCacheIfNeeded($lifeTime)
    {
        if ($this->isDirty) {
            $this->storage->doSave($this->storageId, $this->content, $lifeTime);
        }
    }

public function persistCacheIfNeeded ( $ lifeTime ) { if ( $ this -> isDirty ) { $ this -> storage -> doSave ( $ this -> storageId , $ this -> content , $ lifeTime ) ; } }

Will persist all previously made changes if there were any.

@param int $lifeTime  The cache lifetime in seconds.
If != 0, sets a specific lifetime for this cache entry (0 => infinite lifeTime).

Will persist all previously made changes if there were any .


public function content($entity_type, $bundle, Request $request) {

    // TODO: expose cached/not cached through
    // more varied HTTP response codes.
    try {
      $context = $this->jsonldContextGenerator->getContext("$entity_type.$bundle");
      $response = new CacheableJsonResponse(json_decode($context), 200);
      $response->setEncodingOptions(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
      $response->headers->set('Content-Type', 'application/ld+json');

      // For now deal with Cache dependencies manually.
      $meta = new CacheableMetadata();
      $meta->setCacheContexts(['user.permissions', 'ip', 'url']);
      $meta->setCacheTags(RdfMapping::load("$entity_type.$bundle")->getCacheTags());
      $meta->setCacheMaxAge(Cache::PERMANENT);
      $response->addCacheableDependency($meta);
    }
    catch (\Exception $e) {
      $response = new Response($e->getMessage(), 400);
    }

    return $response;
  }

Returns an JSON-LD Context for a entity bundle.

@param string $entity_type
Route argument, an entity type.
@param string $bundle
Route argument, a bundle.
@param \Symfony\Component\HttpFoundation\Request $request
The Symfony Http Request.

@return \Symfony\Component\HttpFoundation\Response
An Http response.

Returns an JSON - LD Context for a entity bundle .


protected function normalizeFieldItems(FieldItemListInterface $field, $format, array $context) {

    $normalized_field_items = [];
    if (!$field->isEmpty()) {
      foreach ($field as $field_item) {
        $normalized_field_items[] = $this->serializer->normalize($field_item, $format, $context);
      }
    }
    return $normalized_field_items;
  }

protected function normalizeFieldItems ( FieldItemListInterface $ field , $ format , array $ context ) { $ normalized_field_items = [ ] ; if ( ! $ field -> isEmpty ( ) ) { foreach ( $ field as $ field_item ) { $ normalized_field_items [ ] = $ this -> serializer -> normalize ( $ field_item , $ format , $ context ) ; } } return $ normalized_field_items ; }

Helper function to normalize field items.

@param \Drupal\Core\Field\FieldItemListInterface $field
The field object.
@param string $format
The format.
@param array $context
The context array.

@return array
The array of normalized field items.

Helper function to normalize field items .


public function doDelete($id)
    {
        foreach ($this->backends as $backend) {
            if ($backend->doContains($id)) {
                $backend->doDelete($id);
            }
        }

        return true;
    }

public function doDelete ( $ id ) { foreach ( $ this -> backends as $ backend ) { if ( $ backend -> doContains ( $ id ) ) { $ backend -> doDelete ( $ id ) ; } } return true ; }

returns true even when file does not exist


protected function createTranslatedInstance(FieldItemInterface $item, $langcode) {

    // Remove the untranslated item that was created for the default language
    // by FieldNormalizer::denormalize().
    $items = $item->getParent();
    $delta = $item->getName();
    unset($items[$delta]);

    // Instead, create a new item for the entity in the requested language.
    $entity = $item->getEntity();
    $entity_translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
    $field_name = $item->getFieldDefinition()->getName();
    return $entity_translation->get($field_name)->appendItem();
  }

Get a translated version of the field item instance.

To indicate that a field item applies to one translation of an entity and
not another, the property path must originate with a translation of the
entity. This is the reason for using target_instances, from which the
property path can be traversed up to the root.

@param \Drupal\Core\Field\FieldItemInterface $item
The untranslated field item instance.
@param string $langcode
The langcode.

@return \Drupal\Core\Field\FieldItemInterface
The translated field item instance.

Get a translated version of the field item instance .


protected function getEntityUri(EntityInterface $entity) {

    // Some entity types don't provide a canonical link template, at least call
    // out to ->url().
    if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) {
      return $entity->toUrl('canonical', []);
    }
    $url = $entity->toUrl('canonical', ['absolute' => TRUE]);
    return $url->setRouteParameter('_format', 'jsonld')->toString();
  }

Constructs the entity URI.

@param \Drupal\Core\Entity\EntityInterface $entity
The entity.

@return string
The entity URI.


protected function getTypedDataIds(array $types, array $context = []) {

    // The 'type' can potentially contain an array of type objects. By default,
    // Drupal only uses a single type in serializing, but allows for multiple
    // types when deserializing.
    if (isset($types['href'])) {
      $types = [$types];
    }

    foreach ($types as $type) {
      if (!isset($type['href'])) {
        throw new UnexpectedValueException('Type must contain an \'href\' attribute.');
      }
      $type_uri = $type['href'];
      // Check whether the URI corresponds to a known type on this site. Break
      // once one does.
      if ($typed_data_ids = $this->linkManager->getTypeInternalIds($type['href'], $context)) {
        break;
      }
    }

    // If none of the URIs correspond to an entity type on this site, no entity
    // can be created. Throw an exception.
    if (empty($typed_data_ids)) {
      throw new UnexpectedValueException(sprintf('Type %s does not correspond to an entity on this site.', $type_uri));
    }

    return $typed_data_ids;
  }

Gets the typed data IDs for a type URI.

@param array $types
The type array(s) (value of the 'type' attribute of the incoming data).
@param array $context
Context from the normalizer/serializer operation.

@return array
The typed data IDs.

Gets the typed data IDs for a type URI .


public function buildBackend($type, array $options)
    {
        switch ($type) {
            case 'array':

                return $this->buildArrayCache();

            case 'file':

                return $this->buildFileCache($options);

            case 'chained':

                return $this->buildChainedCache($options);

            case 'null':

                return $this->buildNullCache();

            case 'redis':

                return $this->buildRedisCache($options);

            default:

                throw new Factory\BackendNotFoundException("Cache backend $type not valid");
        }
    }

public
function
buildBackend
(
$
type
,
array
$
options
)
{
switch
(
$
type
)
{
case
'array'
:
return
$
this
->
buildArrayCache
(
)
;
case
'file'
:
return
$
this
->
buildFileCache
(
$
options
)
;
case
'chained'
:
return
$
this
->
buildChainedCache
(
$
options
)
;
case
'null'
:
return
$
this
->
buildNullCache
(
)
;
case
'redis'
:
return
$
this
->
buildRedisCache
(
$
options
)
;
default
:
throw
new
Factory
\
BackendNotFoundException
(
"Cache backend $type not valid"
)
;
}
}

Build a specific backend instance.

@param string $type The type of backend you want to create. Eg 'array', 'file', 'chained', 'null', 'redis'.
@param array $options An array of options for the backend you want to create.
@return Backend
@throws Factory\BackendNotFoundException In case the given type was not found.


public function fetch($id)
    {
        $id = $this->getCompletedCacheIdIfValid($id);

        return $this->backend->doFetch($id);
    }

public function fetch ( $ id ) { $ id = $ this -> getCompletedCacheIdIfValid ( $ id ) ; return $ this -> backend -> doFetch ( $ id ) ; }

Fetches an entry from the cache.

@param string $id The cache id.
@return mixed The cached data or FALSE, if no cache entry exists for the given id.


protected function runString($callable, array $arguments)
    {
        if (! function_exists($callable)) {
            throw new FunctionNotFoundException("Function $callable not found");
        }

        $this->startBuffer();

        $this->return = call_user_func_array($callable, $arguments);

        $this->endBuffer();

        return $this;
    }

protected
function
runString
(
$
callable
,
array
$
arguments
)
{
if
(
!
function_exists
(
$
callable
)
)
{
throw
new
FunctionNotFoundException
(
"Function $callable not found"
)
;
}
$
this
->
startBuffer
(
)
;
$
this
->
return
=
call_user_func_array
(
$
callable
,
$
arguments
)
;
$
this
->
endBuffer
(
)
;
return
$
this
;
}

Runs a user function.

@param string $callable Function name.
@param array $arguments Arguments to pass to the user function.
@return $this
@throws \StatonLab\TripalTestSuite\Exceptions\FunctionNotFoundException


public function error($line)
    {
        if (is_array($line)) {
            $lines = [];
            foreach ($line as $one) {
                $lines[] = "<error>$one</error>";
            }

            $this->output->writeln($lines);

            return;
        }

        $this->output->writeln("<error>$line</error>");
    }

public function error ( $ line ) { if ( is_array ( $ line ) ) { $ lines = [ ] ; foreach ( $ line as $ one ) { $ lines [ ] = "<error>$one</error>" ; } $ this -> output -> writeln ( $ lines ) ; return ; } $ this -> output -> writeln ( "<error>$line</error>" ) ; }

Write an error.

@param string|array $line


public function ask($question, $default = false)
    {
        $handler = $this->getHelper('question');
        $confirmation = new ConfirmationQuestion($question, $default);

        return $handler->ask($this->input, $this->output, $confirmation);
    }

public function ask ( $ question , $ default = false ) { $ handler = $ this -> getHelper ( 'question' ) ; $ confirmation = new ConfirmationQuestion ( $ question , $ default ) ; return $ handler -> ask ( $ this -> input , $ this -> output , $ confirmation ) ; }

Ask the user a question.

@param $question
@param bool $default
@return mixed


public function execute($row, $name = null)
    {
        parent::execute($row, $name);
        return $this->getConnection()->lastInsertId();
    }

public function execute ( $ row , $ name = null ) { parent :: execute ( $ row , $ name ) ; return $ this -> getConnection ( ) -> lastInsertId ( ) ; }

Persist's the passed row.

@param array       $row  The row to persist
@param string|null $name The name of the prepared statement that has to be executed

@return string The last inserted ID


public function create(array $overrides = [])
    {
        $factory = static::$factories[$this->table]['callback'];
        $data = [];

        for ($i = 0; $i < $this->times; $i++) {
            $values = $this->override($factory(\Faker\Factory::create($this->locale)), $overrides);

            $data[] = $this->insert($values);
        }

        if (count($data) === 1) {
            return $data[0];
        }

        return $data;
    }

public function create ( array $ overrides = [ ] ) { $ factory = static :: $ factories [ $ this -> table ] [ 'callback' ] ; $ data = [ ] ; for ( $ i = 0 ; $ i < $ this -> times ; $ i ++ ) { $ values = $ this -> override ( $ factory ( \ Faker \ Factory :: create ( $ this -> locale ) ) , $ overrides ) ; $ data [ ] = $ this -> insert ( $ values ) ; } if ( count ( $ data ) === 1 ) { return $ data [ 0 ] ; } return $ data ; }

Create the data.

@param array $overrides
@throws \Exception
@return \stdClass|array If only one item was inserted, an object will be returned.
Otherwise, an array of objects will be returned.


protected function override(array $values, array $overrides)
    {
        if (count($overrides) === 0) {
            return $values;
        }

        foreach ($overrides as $key => $value) {
            $values[$key] = $overrides[$key];
        }

        return $values;
    }

protected function override ( array $ values , array $ overrides ) { if ( count ( $ overrides ) === 0 ) { return $ values ; } foreach ( $ overrides as $ key => $ value ) { $ values [ $ key ] = $ overrides [ $ key ] ; } return $ values ; }

Override array.

@param array $values
@param array $overrides
@return array


protected function insert($values)
    {
        $id = db_insert($this->table)->fields($values)->execute();

        $query = db_select($this->table, 'T');
        $query->fields('T');
        $query->condition($this->primary_key, $id);

        return $query->execute()->fetchObject();
    }

protected function insert ( $ values ) { $ id = db_insert ( $ this -> table ) -> fields ( $ values ) -> execute ( ) ; $ query = db_select ( $ this -> table , 'T' ) ; $ query -> fields ( 'T' ) ; $ query -> condition ( $ this -> primary_key , $ id ) ; return $ query -> execute ( ) -> fetchObject ( ) ; }

Insert data into the db and obtain the inserted records.

@param $values
@throws \Exception
@return \stdClass

Insert data into the db and obtain the inserted records .


protected function extractPrimaryKey()
    {
        if (static::$factories[$this->table]['primary_key'] !== null) {
            return static::$factories[$this->table]['primary_key'];
        }

        if (preg_match('/^chado\./', $this->table)) {
            $schema = chado_get_schema(str_replace('chado.', '', $this->table));
            if ($schema) {
                if (isset($schema['primary key'])) {
                    return $schema['primary key'][0];
                } elseif (isset($schema['primary keys'])) {
                    return $schema['primary keys'][0];
                }
            }
        }

        throw new \Exception("Unable to determine primary key for $this->table factory. Please provide the primary key such as `nid` as a third argument in Factory::define().");
    }

Get the primary key of a table.

@throws \Exception
@return string


public function actingAs($uid)
    {
        global $user;

        // Load the new requested user
        if (is_object($uid)) {
            if($uid->uid === 0) {
                $user = drupal_anonymous_user();
            } else{
                $user = user_load($uid->uid);
            }
        } else {
            if($uid === 0) {
                $user = drupal_anonymous_user();
            } else {
                $user = user_load($uid);
            }
        }

        $this->_cookies = [
            session_name() => session_id()
        ];

        return $this;
    }

public
function
actingAs
(
$
uid
)
{
global
$
user
;
// Load the new requested user
if
(
is_object
(
$
uid
)
)
{
if
(
$
uid
->
uid
===
0
)
{
$
user
=
drupal_anonymous_user
(
)
;
}
else
{
$
user
=
user_load
(
$
uid
->
uid
)
;
}
}
else
{
if
(
$
uid
===
0
)
{
$
user
=
drupal_anonymous_user
(
)
;
}
else
{
$
user
=
user_load
(
$
uid
)
;
}
}
$
this
->
_cookies
=
[
session_name
(
)
=>
session_id
(
)
]
;
return
$
this
;
}

Set the active user.

@param int|object $user Either a user object or simply a user id.
@return $this


protected function copyStubs(array $files)
    {
        foreach ($files as $file => $to) {
            $to = "{$this->path}/{$to}";
            if (! file_exists($to) || $this->getOption('force') !== false) {
                copy("{$this->stubsDir}/{$file}", $to);
            } else {
                $this->line("TRIPALTEST: $to already exists.");
            }
        }
    }

protected
function
copyStubs
(
array
$
files
)
{
foreach
(
$
files
as
$
file
=>
$
to
)
{
$
to
=
"{$this->path}/{$to}"
;
if
(
!
file_exists
(
$
to
)
||
$
this
->
getOption
(
'force'
)
!==
false
)
{
copy
(
"{$this->stubsDir}/{$file}"
,
$
to
)
;
}
else
{
$
this
->
line
(
"TRIPALTEST: $to already exists."
)
;
}
}
}

Copy stubs to their paths.

@param array $files List of files in the following structure: [STUB_FILENAME => NEW_PATH]


protected function configureVariables(array $files)
    {
        foreach ($files as $file => $values) {
            $file = "{$this->path}/{$file}";
            if (! file_exists($file)) {
                throw new \Exception("TRIPALTEST: Unable to configure variables. $file does not exist!");
            }

            $content = file_get_contents($file);
            foreach ($values as $search => $replace) {
                $content = str_replace($search, $replace, $content);
            }

            file_put_contents($file, $content);
        }
    }

Finds a replaces variables in given files.

@param array $files List of files and values in the following structure:
['FILE_NAME' => [
"VARIABLE" => "NEW_VALUE"
]
]
@throws \Exception

Finds a replaces variables in given files .


protected function serializeAdditionalData(array $attr)
    {

        // serialize the additional data value if available
        if (isset($attr[MemberNames::ADDITIONAL_DATA]) && $attr[MemberNames::ADDITIONAL_DATA] !== null) {
            $attr[MemberNames::ADDITIONAL_DATA] = json_encode($attr[MemberNames::ADDITIONAL_DATA]);
        }

        // return the attribute
        return $attr;
    }

Serialize the additional_data attribute of the passed array.

@param array $attr The attribute with the data to serialize

@return array The attribute with the serialized additional_data

Serialize the additional_data attribute of the passed array .


protected function isSwatchType(array $additionalData)
    {
        return isset($additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE]) && in_array($additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE], $this->swatchTypes);
    }

protected function isSwatchType ( array $ additionalData ) { return isset ( $ additionalData [ CatalogAttributeObserver :: SWATCH_INPUT_TYPE ] ) && in_array ( $ additionalData [ CatalogAttributeObserver :: SWATCH_INPUT_TYPE ] , $ this -> swatchTypes ) ; }

Return's TRUE if the additional data contains a swatch type.

@param array $additionalData The additional data to query for a valid swatch type

@return boolean TRUE if the data contains a swatch type, else FALSE

Return s TRUE if the additional data contains a swatch type .


public function loadSwatchType($entityTypeId, $attributeCode)
    {

        // prepare a unique key for the swatch type from the given code and entity type ID
        $key = sprintf('%d-%s', $entityTypeId, $attributeCode);

        // query whether or not a swatch type has been set
        if ($this->hasSwatchType($key) === false) {
            // load the attribute and the catalog attribute data
            $attribute = $this->loadAttributeByEntityTypeIdAndAttributeCode($entityTypeId, $attributeCode);
            $catalogAttribute = $this->loadCatalogAttribute($attribute[MemberNames::ATTRIBUTE_ID]);

            // query whether or not additional data is available (to figure out if the attribute is a swatch type or not)
            if (is_array($catalogAttribute[MemberNames::ADDITIONAL_DATA]) && $catalogAttribute[MemberNames::ADDITIONAL_DATA] !== null) {
                // unserialize the additional data
                $additionalData = json_decode($catalogAttribute[MemberNames::ADDITIONAL_DATA]);
                // load and return the swatch type (can be either one of 'text' or 'visual')
                return $this->setSwatchType($key, $additionalData[CatalogAttributeObserver::SWATCH_INPUT_TYPE]);
            }
        }

        // return the actual swatch type
        return $this->getSwatchType($key);
    }

Returns the swatch type for the attribute with the passed code and entity type ID.

@param integer $entityTypeId  The entity type ID of the EAV attribute to return the swatch type for
@param string  $attributeCode The attribute code

@return string|null The swatch type (either one of 'text' or 'visual') or NULL, if the attribute is NOT a swatch type

Returns the swatch type for the attribute with the passed code and entity type ID .


public function handle()
    {
        // Let's bootstrap first
        new TripalTestBootstrap(false);

        $this->loadDatabaseSeeders();

        $seeder = $this->getArgument('name');

        if ($seeder) {
            $this->runSeeder($seeder);
            $this->success($seeder);

            return;
        }

        if (empty($this->seeders)) {
            $this->error('No database seeders found!');

            return;
        }

        foreach ($this->seeders as $seeder) {
            $this->runSeeder($seeder);
            $this->success($seeder);
        }
    }

public
function
handle
(
)
{
// Let's bootstrap first
new
TripalTestBootstrap
(
false
)
;
$
this
->
loadDatabaseSeeders
(
)
;
$
seeder
=
$
this
->
getArgument
(
'name'
)
;
if
(
$
seeder
)
{
$
this
->
runSeeder
(
$
seeder
)
;
$
this
->
success
(
$
seeder
)
;
return
;
}
if
(
empty
(
$
this
->
seeders
)
)
{
$
this
->
error
(
'No database seeders found!'
)
;
return
;
}
foreach
(
$
this
->
seeders
as
$
seeder
)
{
$
this
->
runSeeder
(
$
seeder
)
;
$
this
->
success
(
$
seeder
)
;
}
}


protected function prepSeeder($name)
    {
        $name = trim($name, '\\');
        if (strstr($name, 'Tests\\DatabaseSeeders') !== false) {
            return $name;
        }

        return 'Tests\\DatabaseSeeders\\'.$name;
    }

protected function prepSeeder ( $ name ) { $ name = trim ( $ name , '\\' ) ; if ( strstr ( $ name , 'Tests\\DatabaseSeeders' ) !== false ) { return $ name ; } return 'Tests\\DatabaseSeeders\\' . $ name ; }

Get the fully qualified seeder name.

@param $name
@return string


public function findOneByOptionIdAndStoreId($optionId, $storeId)
    {

        // the parameters of the EAV attribute option to load
        $params = array(
            MemberNames::OPTION_ID => $optionId,
            MemberNames::STORE_ID  => $storeId,
        );

        // load and return the EAV attribute option swatch with the passed parameters
        $this->attributeOptionSwatchByOptionIdAndStoreIdStmt->execute($params);
        return $this->attributeOptionSwatchByOptionIdAndStoreIdStmt->fetch(\PDO::FETCH_ASSOC);
    }

Load's and return's the EAV attribute option swatch with the passed option ID and store ID

@param string  $optionId The option ID of the attribute option swatch to load
@param integer $storeId  The store ID of the attribute option swatch to load

@return array The EAV attribute option swatch

Load s and return s the EAV attribute option swatch with the passed option ID and store ID


public function findOneByAttributeIdAndAttributeSetId($attributeId, $attributeSetId)
    {

        // initialize the params
        $params = array(
            MemberNames::ATTRIBUTE_ID       => $attributeId,
            MemberNames::ATTRIBUTE_SET_ID   => $attributeSetId
        );

        // load and return the EAV entity attribute with the passed params
        $this->entityAttributeByAttributeIdAndAttributeSetIdStmt->execute($params);
        return $this->entityAttributeByAttributeIdAndAttributeSetIdStmt->fetch(\PDO::FETCH_ASSOC);
    }

Return's the EAV entity attribute with the passed attribute + attribute set ID.

@param integer $attributeId    The ID of the EAV entity attribute's attribute to return
@param integer $attributeSetId The ID of the EAV entity attribute's attribute set to return

@return array The EAV entity attribute

Return s the EAV entity attribute with the passed attribute + attribute set ID .


public function findOneByEntityTypeIdAndAttributeCodeAndStoreIdAndValue($entityTypeId, $attributeCode, $storeId, $value)
    {

        // the parameters of the EAV attribute option to load
        $params = array(
            MemberNames::ENTITY_TYPE_ID => $entityTypeId,
            MemberNames::ATTRIBUTE_CODE => $attributeCode,
            MemberNames::STORE_ID       => $storeId,
            MemberNames::VALUE          => $value
        );

        // load and return the EAV attribute option with the passed parameters
        $this->attributeOptionByEntityTypeIdAndAttributeCodeAndStoreIdAndValueStmt->execute($params);
        return $this->attributeOptionByEntityTypeIdAndAttributeCodeAndStoreIdAndValueStmt->fetch(\PDO::FETCH_ASSOC);
    }

Load's and return's the EAV attribute option with the passed entity type ID and code, store ID and value.

@param string  $entityTypeId  The entity type ID of the EAV attribute to load the option for
@param string  $attributeCode The code of the EAV attribute option to load
@param integer $storeId       The store ID of the attribute option to load
@param string  $value         The value of the attribute option to load

@return array The EAV attribute option

Load s and return s the EAV attribute option with the passed entity type ID and code store ID and value .


public function findOneByAttributeIdAndHighestSortOrder($attributeId)
    {

        // load and return the EAV attribute option with the passed parameters
        $this->attributeOptionByAttributeIdOrderBySortOrderDescStmt->execute(array(MemberNames::ATTRIBUTE_ID => $attributeId));
        return $this->attributeOptionByAttributeIdOrderBySortOrderDescStmt->fetch(\PDO::FETCH_ASSOC);
    }

Returns the EAV attribute option of attribute with the passed ID with the highest sort order.

@param integer $attributeId The ID of the attribute to return the EAV option with the highest sort order for

@return array|null The EAV attribute option with the highest sort order

Returns the EAV attribute option of attribute with the passed ID with the highest sort order .


protected function createDatabaseSeedersFolder()
    {
        $path = getcwd().'/tests';
        if (! file_exists($path)) {
            throw new FileNotFoundException('Tests folder not found.');
        }

        if (! file_exists($path.'/DatabaseSeeders')) {
            mkdir($path.'/DatabaseSeeders');
        }
    }

protected
function
createDatabaseSeedersFolder
(
)
{
$
path
=
getcwd
(
)
.
'/tests'
;
if
(
!
file_exists
(
$
path
)
)
{
throw
new
FileNotFoundException
(
'Tests folder not found.'
)
;
}
if
(
!
file_exists
(
$
path
.
'/DatabaseSeeders'
)
)
{
mkdir
(
$
path
.
'/DatabaseSeeders'
)
;
}
}

Creates the database seeders folder if it doesn't exist.

@throws FileNotFoundException

Creates the database seeders folder if it doesn t exist .


protected function makeSeeder()
    {
        $path = getcwd().'/tests/DatabaseSeeders';
        $name = $this->getArgument('name');
        $stub = __DIR__.'/../../../stubs/SeederStub.php';
        $content = file_get_contents($stub);
        $content = str_replace('$$CLASS_NAME$$', $name, $content);
        $path = "{$path}/{$name}.php";

        if (file_exists($path)) {
            throw new \Exception("File already exists at $path");
        }

        $done = file_put_contents($path, $content);

        if ($done === false) {
            throw new \Exception("Could not create file at $path");
        }

        return $path;
    }

protected
function
makeSeeder
(
)
{
$
path
=
getcwd
(
)
.
'/tests/DatabaseSeeders'
;
$
name
=
$
this
->
getArgument
(
'name'
)
;
$
stub
=
__DIR__
.
'/../../../stubs/SeederStub.php'
;
$
content
=
file_get_contents
(
$
stub
)
;
$
content
=
str_replace
(
'$$CLASS_NAME$$'
,
$
name
,
$
content
)
;
$
path
=
"{$path}/{$name}.php"
;
if
(
file_exists
(
$
path
)
)
{
throw
new
\
Exception
(
"File already exists at $path"
)
;
}
$
done
=
file_put_contents
(
$
path
,
$
content
)
;
if
(
$
done
===
false
)
{
throw
new
\
Exception
(
"Could not create file at $path"
)
;
}
return
$
path
;
}

Make a database seeder.

@throws \Exception


protected function initializeAttribute(array $attr)
    {

        // load the entity type ID for the value from the system configuration
        $entityTypeId = $this->getEntityTypeId();

        // initialize the data to load the EAV attribute option
        $value = $this->getValue(ColumnKeys::VALUE);
        $storeId = $this->getRowStoreId(StoreViewCodes::ADMIN);
        $attributeCode = $this->getValue(ColumnKeys::ATTRIBUTE_CODE);

        // try to load the EAV attribute option
        if ($attributeOption = $this->loadAttributeOptionByEntityTypeIdAndAttributeCodeAndStoreIdAndValue($entityTypeId, $attributeCode, $storeId, $value)) {
            return $this->mergeEntity($attributeOption, $attr);
        }

        // simply return the attributes
        return $attr;
    }

Initialize the EAV attribute option with the passed attributes and returns an instance.

@param array $attr The EAV attribute option attributes

@return array The initialized EAV attribute option

Initialize the EAV attribute option with the passed attributes and returns an instance .


protected function DBTransactionSetUp()
    {
        $this->_transaction = db_transaction(uniqid());

        $shutdown = '\\StatonLab\\TripalTestSuite\\DBTransaction::rollbackTransaction';
        register_shutdown_function($shutdown, $this->_transaction);
    }


public function load($attributeId)
    {
        // load and return the EAV catalog attribute with the ID
        $this->catalogAttributeStmt->execute(array(MemberNames::ATTRIBUTE_ID => $attributeId));
        return $this->catalogAttributeStmt->fetch(\PDO::FETCH_ASSOC);
    }

Return's the EAV catalog attribute with the passed ID.

@param string $attributeId The ID of the EAV catalog attribute to return

@return array The EAV catalog attribute

Return s the EAV catalog attribute with the passed ID .


public function setPath($path)
    {
        $this->path = trim($path, '/');

        if(empty($this->path)) {
            // Home page requested so let's use /node
            $this->path = 'node';
        }

        return $this;
    }

Set public path.

@param $path
@return $this


public function addParams($params)
    {
        if (isset($params['form_params'])) {
            $params = $params['form_params'];
            $params['form_token'] = drupal_get_token();
        } elseif (isset($params['query'])) {
            $params = $params['query'];
        }

        foreach ($params as $key => $value) {
            $this->params[$key] = $value;
        }

        return $this;
    }

public function addParams ( $ params ) { if ( isset ( $ params [ 'form_params' ] ) ) { $ params = $ params [ 'form_params' ] ; $ params [ 'form_token' ] = drupal_get_token ( ) ; } elseif ( isset ( $ params [ 'query' ] ) ) { $ params = $ params [ 'query' ] ; } foreach ( $ params as $ key => $ value ) { $ this -> params [ $ key ] = $ value ; } return $ this ; }

Add parameters to the request.

@param $params
@return $this