sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function checkOut()
{
$newObjectId = $this->getId();
$this->getBinding()->getVersioningService()->checkOut($this->getRepositoryId(), $newObjectId);
if ($newObjectId === null) {
return null;
}
return $this->getSession()->createObjectId($newObjectId);
} | Checks out the document and returns the object ID of the PWC (private working copy).
@return ObjectIdInterface|null PWC object ID | entailment |
public function copy(
ObjectIdInterface $targetFolderId = null,
array $properties = [],
VersioningState $versioningState = null,
array $policies = [],
array $addAces = [],
array $removeAces = [],
OperationContextInterface $context = null
) {
try {
$newObjectId = $this->getSession()->createDocumentFromSource(
$this,
$properties,
$targetFolderId,
$versioningState,
$policies,
$addAces,
$removeAces
);
} catch (CmisNotSupportedException $notSupportedException) {
$newObjectId = $this->copyViaClient(
$targetFolderId,
$properties,
$versioningState,
$policies,
$addAces,
$removeAces
);
}
$document = $this->getNewlyCreatedObject($newObjectId, $context);
if ($document === null) {
return null;
} elseif (!$document instanceof DocumentInterface) {
throw new CmisRuntimeException('Newly created object is not a document! New id: ' . $document->getId());
}
return $document;
} | Creates a copy of this document, including content.
@param ObjectIdInterface|null $targetFolderId the ID of the target folder, <code>null</code> to create an unfiled
document
@param array $properties The property values that MUST be applied to the object. This list of properties SHOULD
only contain properties whose values differ from the source document. The array key is the property name
the value is the property value.
@param VersioningState|null $versioningState An enumeration specifying what the versioning state of the
newly-created object MUST be. Valid values are:
<code>none</code>
(default, if the object-type is not versionable) The document MUST be created as a non-versionable
document.
<code>checkedout</code>
The document MUST be created in the checked-out state. The checked-out document MAY be
visible to other users.
<code>major</code>
(default, if the object-type is versionable) The document MUST be created as a major version.
<code>minor</code>
The document MUST be created as a minor version.
@param PolicyInterface[] $policies A list of policy ids that MUST be applied to the newly-created document
object.
@param AceInterface[] $addAces A list of ACEs that MUST be added to the newly-created document object, either
using the ACL from folderId if specified, or being applied if no folderId is specified.
@param AceInterface[] $removeAces A list of ACEs that MUST be removed from the newly-created document object,
either using the ACL from folderId if specified, or being ignored if no folderId is specified.
@param OperationContextInterface|null $context
@return DocumentInterface the new document object or <code>null</code> if the parameter <code>context</code> was
set to <code>null</code>
@throws CmisRuntimeException Exception is thrown if the created object is not a document | entailment |
protected function copyViaClient(
ObjectIdInterface $targetFolderId = null,
array $properties = [],
VersioningState $versioningState = null,
array $policies = [],
array $addAces = [],
array $removeAces = []
) {
$newProperties = [];
$allPropertiesContext = $this->getSession()->createOperationContext();
$allPropertiesContext->setFilterString('*');
$allPropertiesContext->setIncludeAcls(false);
$allPropertiesContext->setIncludeAllowableActions(false);
$allPropertiesContext->setIncludePathSegments(false);
$allPropertiesContext->setIncludePolicies(false);
$allPropertiesContext->setIncludeRelationships(IncludeRelationships::cast(IncludeRelationships::NONE));
$allPropertiesContext->setRenditionFilterString(Constants::RENDITION_NONE);
$allPropertiesDocument = $this->getSession()->getObject($this, $allPropertiesContext);
if (! $allPropertiesDocument instanceof DocumentInterface) {
throw new CmisRuntimeException('Returned object is not of expected type DocumentInterface');
}
foreach ($allPropertiesDocument->getProperties() as $property) {
if (Updatability::cast(Updatability::READWRITE)->equals($property->getDefinition()->getUpdatability())
|| Updatability::cast(Updatability::ONCREATE)->equals($property->getDefinition()->getUpdatability())
) {
$newProperties[$property->getId()] = $property->isMultiValued() ? $property->getValues(
) : $property->getFirstValue();
}
}
$newProperties = array_merge($newProperties, $properties);
$contentStream = $allPropertiesDocument->getContentStream();
return $this->getSession()->createDocument(
$newProperties,
$targetFolderId,
$contentStream,
$versioningState,
$policies,
$addAces,
$removeAces
);
} | Copies the document manually. The content is streamed from the repository and back.
@param ObjectIdInterface|null $targetFolderId the ID of the target folder, <code>null</code> to create an unfiled
document
@param array $properties The property values that MUST be applied to the object. This list of properties SHOULD
only contain properties whose values differ from the source document. The array key is the property name
the value is the property value.
@param VersioningState|null $versioningState An enumeration specifying what the versioning state of the
newly-created object MUST be. Valid values are:
<code>none</code>
(default, if the object-type is not versionable) The document MUST be created as a non-versionable
document.
<code>checkedout</code>
The document MUST be created in the checked-out state. The checked-out document MAY be
visible to other users.
<code>major</code>
(default, if the object-type is versionable) The document MUST be created as a major version.
<code>minor</code>
The document MUST be created as a minor version.
@param PolicyInterface[] $policies A list of policy ids that MUST be applied to the newly-created document
object.
@param AceInterface[] $addAces A list of ACEs that MUST be added to the newly-created document object, either
using the ACL from folderId if specified, or being applied if no folderId is specified.
@param AceInterface[] $removeAces A list of ACEs that MUST be removed from the newly-created document object,
either using the ACL from folderId if specified, or being ignored if no folderId is specified.
@return ObjectIdInterface The id of the newly-created document.
@throws CmisRuntimeException | entailment |
public function deleteContentStream($refresh = true)
{
$newObjectId = $this->getId();
$changeToken = $this->getPropertyValue(PropertyIds::CHANGE_TOKEN);
$this->getBinding()->getObjectService()->deleteContentStream(
$this->getRepositoryId(),
$newObjectId,
$changeToken
);
if ($refresh === true) {
$this->refresh();
}
if ($newObjectId === null) {
return null;
}
return $this->getSession()->getObject(
$this->getSession()->createObjectId($newObjectId),
$this->getCreationContext()
);
} | Removes the current content stream from the document and refreshes this object afterwards.
@param boolean $refresh if this parameter is set to <code>true</code>, this object will be refreshed after the
content stream has been deleted
@return DocumentInterface|null the updated document, or <code>null</code> if the repository did not return
an object ID | entailment |
public function getAllVersions(OperationContextInterface $context = null)
{
$context = $this->ensureContext($context);
$versions = $this->getBinding()->getVersioningService()->getAllVersions(
$this->getRepositoryId(),
$this->getId(),
$this->getVersionSeriesId(),
$context->getQueryFilterString(),
$context->isIncludeAllowableActions()
);
$objectFactory = $this->getSession()->getObjectFactory();
$result = [];
if (count($versions)) {
foreach ($versions as $objectData) {
$document = $objectFactory->convertObject($objectData, $context);
if (!($document instanceof DocumentInterface)) {
throw new CmisVersioningException(
sprintf(
'Repository yielded non-Document %s as version of Document %s - unsupported repository response',
$document->getId(),
$this->getId()
)
);
}
$result[] = $document;
}
}
return $result;
} | Fetches all versions of this document using the given OperationContext.
The behavior of this method is undefined if the document is not versionable
and can be different for each repository.
@param OperationContextInterface|null $context
@return DocumentInterface[] | entailment |
public function getContentUrl($streamId = null)
{
$objectService = $this->getBinding()->getObjectService();
if ($objectService instanceof LinkAccessInterface) {
if ($streamId === null) {
return $objectService->loadContentLink($this->getRepositoryId(), $this->getId());
} else {
return $objectService->loadRenditionContentLink($this->getRepositoryId(), $this->getId(), $streamId);
}
}
return null;
} | Returns the content URL of the document or a rendition if the binding
supports content URLs.
Depending on the repository and the binding, the server might not return
the content but an error message. Authentication data is not attached.
That is, a user may have to re-authenticate to get the content.
@param string|null $streamId the ID of the rendition or <code>null</code> for the document
@return string|null the content URL of the document or rendition or <code>null</code> if
the binding does not support content URLs | entailment |
public function getContentStream($streamId = null, $offset = null, $length = null)
{
return $this->getSession()->getContentStream($this, $streamId, $offset, $length);
} | Retrieves the content stream that is associated with the given stream ID.
This is usually a rendition of the document.
@param string|null $streamId the stream ID
@param integer|null $offset the offset of the stream or <code>null</code> to read the stream from the beginning
@param integer|null $length the maximum length of the stream or <code>null</code> to read to the end of the
stream
@return StreamInterface|null the content stream, or <code>null</code> if no content is associated with this
stream ID | entailment |
public function setContentStream(StreamInterface $contentStream, $overwrite, $refresh = true)
{
$newObjectId = $this->getId();
$changeToken = $this->getPropertyValue(PropertyIds::CHANGE_TOKEN);
$this->getBinding()->getObjectService()->setContentStream(
$this->getRepositoryId(),
$newObjectId,
$this->getObjectFactory()->convertContentStream($contentStream),
$overwrite,
$changeToken
);
if ($refresh === true) {
$this->refresh();
}
if ($newObjectId === null) {
return null;
}
return $this->getSession()->createObjectId($newObjectId);
} | Sets a new content stream for the document. If the repository created a new version,
the object ID of this new version is returned. Otherwise the object ID of the current document is returned.
The stream in contentStream is consumed but not closed by this method.
@param StreamInterface $contentStream the content stream
@param boolean $overwrite if this parameter is set to <code>false</code> and the document already has content,
the repository throws a CmisContentAlreadyExistsException
@param boolean $refresh if this parameter is set to <code>true</code>, this object will be refreshed
after the new content has been set
@return ObjectIdInterface|null the updated object ID, or <code>null</code> if the repository did not return
an object ID | entailment |
public function isAllowed($entry, $defaultState)
{
$whited = false;
$blacked = false;
if (is_array($this->lists)) {
foreach ($this->lists as $list) {
$allowed = $list->isAllowed($entry);
if ($allowed !== null) {
if ($allowed) {
$whited = true;
} else {
$blacked = true;
}
}
}
}
return ($defaultState ? (!$blacked || $whited) : ($whited && !$blacked));
} | Check if a string is allowed
@param string $entry String to compare
@param boolean $defaultState Default value
@return boolean | entailment |
public function all(array $params = array())
{
$endpoint = '/admin/smart_collections.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createCollection(SmartCollection::class, $response['smart_collections']);
} | Receive a list of all SmartCollection
@link https://help.shopify.com/api/reference/smartcollection#index
@param array $params
@return SmartCollection[] | entailment |
public function get($smartCollectionId, array $params = array())
{
$endpoint = '/admin/smart_collections/'.$smartCollectionId.'.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createObject(SmartCollection::class, $response['smart_collection']);
} | Receive a single smart collection
@link https://help.shopify.com/api/reference/smartcollection#show
@param integer $smartCollectionId
@param array $params
@return SmartCollection | entailment |
public function create(SmartCollection &$smartCollection)
{
$data = $smartCollection->exportData();
$endpoint = '/admin/smart_collections.json';
$response = $this->request(
$endpoint, 'POST', array(
'smart_collection' => $data
)
);
$smartCollection->setData($response['smart_collection']);
} | Create a new smart collection
@link https://help.shopify.com/api/reference/smartcollection#create
@param SmartCollection $smartCollection
@return void | entailment |
public function update(SmartCollection &$smartCollection)
{
$data = $smartCollection->exportData();
$endpoint = '/admin/smart_collections/'.$smart_collection->id.'.json';
$response = $this->request(
$endpoint, 'PUT', array(
'smart_collection' => $data
)
);
$smartCollection->setData($response['smart_collection']);
} | Modify an existing smart collection
@link https://help.shopify.com/api/reference/smartcollection#update
@param SmartCollection $smartCollection
@return void | entailment |
public function delete(SmartCollection $smartCollection)
{
$request = $this->createRequest('/admin/smart_collections/'.$smartCollection->getId().'.json', static::REQUEST_METHOD_DELETE);
$this->send($request);
} | Delete an existing smart_collection
@link https://help.shopify.com/api/reference/smartcollection#destroy
@param SmartCollection $smartCollection
@return void | entailment |
public function applyAcl(
$repositoryId,
$objectId,
AclInterface $addAces = null,
AclInterface $removeAces = null,
AclPropagation $aclPropagation = null,
ExtensionDataInterface $extension = null
) {
// TODO: Implement applyAcl() method.
} | Adds or removes the given ACEs to or from the ACL of the object.
@param string $repositoryId The identifier for the repository.
@param string $objectId The identifier of the object.
@param AclInterface|null $addAces The ACEs to be added.
@param AclInterface|null $removeAces The ACEs to be removed.
@param AclPropagation|null $aclPropagation Specifies how ACEs should be handled.
@param ExtensionDataInterface|null $extension
@return AclInterface the ACL of the object | entailment |
public function convertNewTypeSettableAttributes(array $data = null)
{
if (empty($data)) {
return null;
}
$object = new NewTypeSettableAttributes();
$object->populate(
$data,
array_combine(
JSONConstants::getCapabilityNewTypeSettableAttributeKeys(),
array_map(
function ($key) {
// add a prefix "canSet" to all keys as this are the property names
return 'canSet' . ucfirst($key);
},
JSONConstants::getCapabilityNewTypeSettableAttributeKeys()
)
),
true
);
$object->setExtensions(
$this->convertExtension(
$data,
JSONConstants::getCapabilityNewTypeSettableAttributeKeys()
)
);
return $object;
} | Create NewTypeSettableAttributes object and populate given data to it
@param string[]|null $data
@return NewTypeSettableAttributes|null Returns object or <code>null</code> if given data is empty | entailment |
public function convertCreatablePropertyTypes(array $data = null)
{
if (empty($data)) {
return null;
}
$object = new CreatablePropertyTypes();
$canCreate = [];
foreach ($data[JSONConstants::JSON_CAP_CREATABLE_PROPERTY_TYPES_CANCREATE] ?? [] as $canCreateItem) {
try {
$canCreate[] = PropertyType::cast($canCreateItem);
} catch (InvalidEnumerationValueException $exception) {
// ignore invalid types
}
}
$object->setCanCreate($canCreate);
$object->setExtensions(
$this->convertExtension(
$data,
JSONConstants::getCapabilityCreatablePropertyKeys()
)
);
return $object;
} | Create CreatablePropertyTypes object and populate given data to it
@param array|null $data The data that should be populated to the CreatablePropertyTypes object
@return CreatablePropertyTypes|null Returns a CreatablePropertyTypes object or <code>null</code> if empty data
is given. | entailment |
public function convertTypeDefinition(array $data = null)
{
if (empty($data)) {
return null;
}
if (empty($data[JSONConstants::JSON_TYPE_ID])) {
throw new CmisInvalidArgumentException('Id of type definition is empty but must not be empty!');
}
$typeDefinition = $this->getBindingsObjectFactory()->getTypeDefinitionByBaseTypeId(
$data[JSONConstants::JSON_TYPE_BASE_ID] ?? '',
$data[JSONConstants::JSON_TYPE_ID] ?? ''
);
$data = $this->convertTypeDefinitionSpecificData($data, $typeDefinition);
$data[JSONConstants::JSON_TYPE_TYPE_MUTABILITY] = $this->convertTypeMutability(
$data[JSONConstants::JSON_TYPE_TYPE_MUTABILITY] ?? null
);
foreach ($data[JSONConstants::JSON_TYPE_PROPERTY_DEFINITIONS] ?? [] as $propertyDefinitionData) {
if (is_array($propertyDefinitionData)) {
$propertyDefinition = $this->convertPropertyDefinition($propertyDefinitionData);
if ($propertyDefinition !== null) {
$typeDefinition->addPropertyDefinition($propertyDefinition);
}
}
}
unset(
$data[JSONConstants::JSON_TYPE_BASE_ID],
$data[JSONConstants::JSON_TYPE_ID],
$data[JSONConstants::JSON_TYPE_PROPERTY_DEFINITIONS]
);
$typeDefinition->populate(
array_filter($data, function ($item) { return !empty($item); }),
array_merge(
array_combine(JSONConstants::getTypeKeys(), JSONConstants::getTypeKeys()),
[
JSONConstants::JSON_TYPE_PARENT_ID => 'parentTypeId',
JSONConstants::JSON_TYPE_ALLOWED_TARGET_TYPES => 'allowedTargetTypeIds',
JSONConstants::JSON_TYPE_ALLOWED_SOURCE_TYPES => 'allowedSourceTypeIds',
]
),
true
);
$typeDefinition->setExtensions($this->convertExtension($data, JSONConstants::getTypeKeys()));
return $typeDefinition;
} | Convert an array to a type definition object
@param array|null $data
@return AbstractTypeDefinition|null
@throws CmisInvalidArgumentException | entailment |
private function convertTypeDefinitionSpecificData(array $data, MutableTypeDefinitionInterface $typeDefinition)
{
if ($typeDefinition instanceof MutableDocumentTypeDefinitionInterface) {
if (!empty($data[JSONConstants::JSON_TYPE_CONTENTSTREAM_ALLOWED])) {
$data[JSONConstants::JSON_TYPE_CONTENTSTREAM_ALLOWED] = ContentStreamAllowed::cast(
$data[JSONConstants::JSON_TYPE_CONTENTSTREAM_ALLOWED]
);
}
} elseif ($typeDefinition instanceof MutableRelationshipTypeDefinitionInterface) {
$data[JSONConstants::JSON_TYPE_ALLOWED_SOURCE_TYPES] = array_map(
'strval',
array_filter(
$data[JSONConstants::JSON_TYPE_ALLOWED_SOURCE_TYPES] ?? [],
function ($item) { return !empty($item); }
)
);
$data[JSONConstants::JSON_TYPE_ALLOWED_SOURCE_TYPES] = array_map(
'strval',
array_filter(
$data[JSONConstants::JSON_TYPE_ALLOWED_SOURCE_TYPES] ?? [],
function ($item) { return !empty($item); }
)
);
$data[JSONConstants::JSON_TYPE_ALLOWED_TARGET_TYPES] = array_map(
'strval',
array_filter(
$data[JSONConstants::JSON_TYPE_ALLOWED_TARGET_TYPES] ?? [],
function ($item) { return !empty($item); }
)
);
}
return $data;
} | Convert specific type definition data so it can be populated to the type definition
@param MutableTypeDefinitionInterface $typeDefinition The type definition to set the data to
@param array $data The data that contains the values that should be applied to the object
@return MutableTypeDefinitionInterface The type definition with the specific data applied | entailment |
public function convertTypeMutability(array $data = null)
{
if (empty($data)) {
return null;
}
$typeMutability = new TypeMutability();
$typeMutability->populate(
$data,
array_combine(
JSONConstants::getTypeTypeMutabilityKeys(),
array_map(
function ($key) {
// add a prefix "can" to all keys as this are the property names
return 'can' . ucfirst($key);
},
JSONConstants::getTypeTypeMutabilityKeys()
)
),
true
);
$typeMutability->setExtensions(
$this->convertExtension($data, JSONConstants::getTypeTypeMutabilityKeys())
);
return $typeMutability;
} | Convert an array to a type mutability object
@param array|null $data The data that should be populated to the object
@return TypeMutability|null Returns the type mutability object or <code>null</code> if empty array is given | entailment |
protected function preparePropertyDefinitionData(array $data)
{
$data[JSONConstants::JSON_PROPERTY_TYPE_PROPERTY_TYPE] = PropertyType::cast(
$data[JSONConstants::JSON_PROPERTY_TYPE_PROPERTY_TYPE]
);
if (isset($data[JSONConstants::JSON_PROPERTY_TYPE_DEAULT_VALUE])) {
$data[JSONConstants::JSON_PROPERTY_TYPE_DEAULT_VALUE]
= (array) $data[JSONConstants::JSON_PROPERTY_TYPE_DEAULT_VALUE];
}
if (isset($data[JSONConstants::JSON_PROPERTY_TYPE_RESOLUTION])) {
$data[JSONConstants::JSON_PROPERTY_TYPE_RESOLUTION] = DateTimeResolution::cast(
$data[JSONConstants::JSON_PROPERTY_TYPE_RESOLUTION]
);
}
if (isset($data[JSONConstants::JSON_PROPERTY_TYPE_PRECISION])) {
$data[JSONConstants::JSON_PROPERTY_TYPE_PRECISION] = DecimalPrecision::cast(
$data[JSONConstants::JSON_PROPERTY_TYPE_PRECISION]
);
}
if (isset($data[JSONConstants::JSON_PROPERTY_TYPE_CARDINALITY])) {
$data[JSONConstants::JSON_PROPERTY_TYPE_CARDINALITY] = Cardinality::cast(
$data[JSONConstants::JSON_PROPERTY_TYPE_CARDINALITY]
);
}
if (isset($data[JSONConstants::JSON_PROPERTY_TYPE_UPDATABILITY])) {
$data[JSONConstants::JSON_PROPERTY_TYPE_UPDATABILITY] = Updatability::cast(
$data[JSONConstants::JSON_PROPERTY_TYPE_UPDATABILITY]
);
}
return $data;
} | Cast data values to the expected type
@param array $data
@return array | entailment |
public function convertObject(array $data = null)
{
if (empty($data)) {
return null;
}
$object = new ObjectData();
$acl = $this->convertAcl(
$data[JSONConstants::JSON_OBJECT_ACL] ?? [],
(boolean) ($data[JSONConstants::JSON_OBJECT_EXACT_ACL] ?? false)
);
if ($acl !== null) {
$object->setAcl($acl);
}
$allowableActions = $this->convertAllowableActions($data[JSONConstants::JSON_OBJECT_ALLOWABLE_ACTIONS] ?? []);
if ($allowableActions !== null) {
$object->setAllowableActions($allowableActions);
}
if (isset($data[JSONConstants::JSON_OBJECT_CHANGE_EVENT_INFO])
&& is_array($data[JSONConstants::JSON_OBJECT_CHANGE_EVENT_INFO])
) {
$changeEventInfoData = $data[JSONConstants::JSON_OBJECT_CHANGE_EVENT_INFO];
$changeEventInfo = new ChangeEventInfo();
$changeEventInfo->setChangeTime(
$this->convertDateTimeValue($changeEventInfoData[JSONConstants::JSON_CHANGE_EVENT_TIME])
);
$changeEventInfo->setChangeType(
ChangeType::cast($changeEventInfoData[JSONConstants::JSON_CHANGE_EVENT_TYPE])
);
$changeEventInfo->setExtensions(
$this->convertExtension($changeEventInfoData, JSONConstants::getChangeEventKeys())
);
$object->setChangeEventInfo($changeEventInfo);
}
$object->setIsExactAcl((boolean) ($data[JSONConstants::JSON_OBJECT_EXACT_ACL] ?? false));
$object->setPolicyIds($this->convertPolicyIdList($data[JSONConstants::JSON_OBJECT_POLICY_IDS] ?? null));
/**
* A client MAY add the query parameter succinct (HTTP GET) or the control succinct (HTTP POST) with the
* value <code>true</code> to a request. If this is set, the repository MUST return properties in a succinct
* format. That is, whenever the repository renders an object or a query result, it MUST populate the
* succinctProperties value and MUST NOT populate the properties value.
*
* @see http://docs.oasis-open.org/cmis/CMIS/v1.1/os/CMIS-v1.1-os.html#x1-552027r554
*/
if (isset($data[JSONConstants::JSON_OBJECT_SUCCINCT_PROPERTIES])) {
$properties = $this->convertSuccinctProperties(
$data[JSONConstants::JSON_OBJECT_SUCCINCT_PROPERTIES] ?? [],
(array) ($data[JSONConstants::JSON_OBJECT_PROPERTIES_EXTENSION] ?? [])
);
} else {
$properties = $this->convertProperties(
$data[JSONConstants::JSON_OBJECT_PROPERTIES] ?? [],
(array) ($data[JSONConstants::JSON_OBJECT_PROPERTIES_EXTENSION] ?? [])
);
}
$object->setProperties($properties ?? []);
$object->setRelationships($this->convertObjects($data[JSONConstants::JSON_OBJECT_RELATIONSHIPS] ?? null));
$object->setRenditions($this->convertRenditions($data[JSONConstants::JSON_OBJECT_RENDITIONS] ?? []));
$object->setExtensions($this->convertExtension($data, JSONConstants::getObjectKeys()));
return $object;
} | Converts an object.
@param array|null $data
@return null|ObjectData | entailment |
public function convertRendition(array $data = null)
{
if (empty($data)) {
return null;
}
$rendition = new RenditionData();
if (isset($data[JSONConstants::JSON_RENDITION_HEIGHT])) {
$rendition->setHeight((integer) $data[JSONConstants::JSON_RENDITION_HEIGHT]);
}
if (isset($data[JSONConstants::JSON_RENDITION_KIND])) {
$rendition->setKind((string) $data[JSONConstants::JSON_RENDITION_KIND]);
}
if (isset($data[JSONConstants::JSON_RENDITION_LENGTH])) {
$rendition->setLength((integer) $data[JSONConstants::JSON_RENDITION_LENGTH]);
}
if (isset($data[JSONConstants::JSON_RENDITION_MIMETYPE])) {
$rendition->setMimeType((string) $data[JSONConstants::JSON_RENDITION_MIMETYPE]);
}
if (isset($data[JSONConstants::JSON_RENDITION_DOCUMENT_ID])) {
$rendition->setRenditionDocumentId((string) $data[JSONConstants::JSON_RENDITION_DOCUMENT_ID]);
}
if (isset($data[JSONConstants::JSON_RENDITION_STREAM_ID])) {
$rendition->setStreamId((string) $data[JSONConstants::JSON_RENDITION_STREAM_ID]);
}
if (isset($data[JSONConstants::JSON_RENDITION_TITLE])) {
$rendition->setTitle((string) $data[JSONConstants::JSON_RENDITION_TITLE]);
}
if (isset($data[JSONConstants::JSON_RENDITION_WIDTH])) {
$rendition->setWidth((integer) $data[JSONConstants::JSON_RENDITION_WIDTH]);
}
$rendition->setExtensions($this->convertExtension($data, JSONConstants::getRenditionKeys()));
return $rendition;
} | Convert given input data to a RenditionData object
@param array|null $data
@return null|RenditionData | entailment |
public function convertRenditions(array $data = null)
{
return array_filter(
array_map(
[$this, 'convertRendition'],
array_filter(
$data,
'is_array'
)
),
function ($item) {
// @TODO once a logger is available we should log an INFO message if the rendition could not be converted
return !empty($item);
}
);
} | Convert given input data to a list of RenditionData objects
@param array|null $data
@return RenditionData[] | entailment |
public function convertExtension(array $data = null, array $cmisKeys = [])
{
$extensions = [];
foreach (array_diff_key((array) $data, array_flip($cmisKeys)) as $key => $value) {
if (!is_array($value)) {
$value = (empty($value)) ? null : (string) $value;
$extensions[] = new CmisExtensionElement(null, $key, [], $value);
} else {
$extension = $this->convertExtension($value, $cmisKeys);
if (!empty($extension)) {
$extensions[] = new CmisExtensionElement(
null,
$key,
[],
null,
$extension
);
}
}
}
return $extensions;
} | Convert given input data to an Extension object
@param array|null $data
@param string[] $cmisKeys
@return CmisExtensionElement[] | entailment |
public function convertExtensionFeatures(array $data = null)
{
$features = [];
$extendedFeatures = array_filter(array_filter((array) $data, 'is_array'), function ($item) { return !empty($item); });
foreach ($extendedFeatures as $extendedFeature) {
$feature = new ExtensionFeature();
$feature->setId((string) $extendedFeature[JSONConstants::JSON_FEATURE_ID]);
$feature->setUrl((string) $extendedFeature[JSONConstants::JSON_FEATURE_URL]);
$feature->setCommonName((string) $extendedFeature[JSONConstants::JSON_FEATURE_COMMON_NAME]);
$feature->setVersionLabel((string) $extendedFeature[JSONConstants::JSON_FEATURE_VERSION_LABEL]);
$feature->setDescription((string) $extendedFeature[JSONConstants::JSON_FEATURE_DESCRIPTION]);
$featureData = [];
foreach ($extendedFeature[JSONConstants::JSON_FEATURE_DATA] ?? [] as $key => $value) {
$featureData[$key] = $value;
}
$feature->setFeatureData($featureData);
$feature->setExtensions($this->convertExtension($extendedFeature, JSONConstants::getFeatureKeys()));
$features[] = $feature;
}
return $features;
} | Convert given input data to an ExtensionFeature object
@param array|null $data
@return ExtensionFeature[] | entailment |
public function convertPolicyIdList(array $data = null)
{
$policyIdsList = new PolicyIdList();
$policyIdsList->setPolicyIds(
array_filter(
array_filter(
$data[JSONConstants::JSON_OBJECT_POLICY_IDS_IDS] ?? [],
'is_string'
),
function ($item) { return !empty($item); }
)
);
$policyIdsList->setExtensions($this->convertExtension($data, JSONConstants::getPolicyIdsKeys()));
return $policyIdsList;
} | Converts a list of policy ids.
@param array|null $data
@return PolicyIdList List of policy ids | entailment |
public function convertFromTypeDefinition(TypeDefinitionInterface $typeDefinition)
{
$propertyList = [
'baseTypeId' => JSONConstants::JSON_TYPE_BASE_ID,
'parentTypeId' => JSONConstants::JSON_TYPE_PARENT_ID
];
if ($typeDefinition instanceof RelationshipTypeDefinitionInterface) {
$propertyList['allowedTargetTypeIds'] = JSONConstants::JSON_TYPE_ALLOWED_TARGET_TYPES;
$propertyList['allowedSourceTypeIds'] = JSONConstants::JSON_TYPE_ALLOWED_SOURCE_TYPES;
}
$data = $typeDefinition->exportGettableProperties(
$propertyList
);
$data = $this->castArrayValuesToSimpleTypes($data);
return json_encode($data, JSON_FORCE_OBJECT);
} | Convert a type definition object to a custom format
@param TypeDefinitionInterface $typeDefinition
@return string JSON representation of the type definition | entailment |
protected function castArrayValuesToSimpleTypes(array $data)
{
foreach ($data as $key => $item) {
if (is_array($item)) {
$data[$key] = $this->castArrayValuesToSimpleTypes($item);
} elseif (is_object($item)) {
$data[$key] = $this->convertObjectToSimpleType($item);
}
}
return $data;
} | Cast values of an array to simple types
@param array $data
@return array | entailment |
protected function convertObjectToSimpleType($data)
{
/** @var null|TypeConverterInterface $converterClassName */
$converterClassName = null;
if (class_exists($this->buildConverterClassName(get_class($data)))) {
$converterClassName = $this->buildConverterClassName(get_class($data));
} else {
$classInterfaces = class_implements($data);
foreach ((array) $classInterfaces as $classInterface) {
if (class_exists($this->buildConverterClassName($classInterface))) {
$converterClassName = $this->buildConverterClassName($classInterface);
break;
}
}
if ($converterClassName === null) {
$classParents = class_parents($data);
foreach ((array) $classParents as $classParent) {
if (class_exists($this->buildConverterClassName($classParent))) {
$converterClassName = $this->buildConverterClassName($classParent);
break;
}
}
}
}
if ($converterClassName === null) {
throw new CmisRuntimeException(
'Could not find a converter that converts "' . get_class($data) . '" to a simple type.'
);
}
return $converterClassName::convertToSimpleType($data);
} | Convert an object to a simple type representation
@param mixed $data
@return mixed
@throws CmisRuntimeException Exception is thrown if no type converter could be found to convert the given data
to a simple type | entailment |
public function convertTypeChildren(array $data = null)
{
if (empty($data)) {
return null;
}
$result = new TypeDefinitionList();
$types = [];
$typesList = $data[JSONConstants::JSON_TYPESLIST_TYPES] ?? [];
foreach (array_filter($typesList, 'is_array') as $typeData) {
$type = $this->convertTypeDefinition($typeData);
if ($type !== null) {
$types[] = $type;
}
}
$result->setList($types);
$result->setHasMoreItems((boolean) ($data[JSONConstants::JSON_TYPESLIST_HAS_MORE_ITEMS] ?? false));
$result->setNumItems($data[JSONConstants::JSON_TYPESLIST_NUM_ITEMS] ?? 0);
$result->setExtensions($this->convertExtension($data, JSONConstants::getTypesListKeys()));
return $result;
} | Convert given input data to a TypeChildren object
@param array|null $data
@return TypeDefinitionListInterface|null Returns a TypeDefinitionListInterface object or <code>null</code>
if empty data is given. | entailment |
public function convertTypeDescendants(array $data = null)
{
$result = [];
if (empty($data)) {
return $result;
}
foreach (array_filter($data, 'is_array') as $itemData) {
$container = new TypeDefinitionContainer();
$typeDefinition = $this->convertTypeDefinition($itemData[JSONConstants::JSON_TYPESCONTAINER_TYPE] ?? []);
if ($typeDefinition !== null) {
$container->setTypeDefinition($typeDefinition);
}
$container->setChildren(
$this->convertTypeDescendants($itemData[JSONConstants::JSON_TYPESCONTAINER_CHILDREN] ?? [])
);
$container->setExtensions($this->convertExtension($data, JSONConstants::getTypesContainerKeys()));
$result[] = $container;
}
return $result;
} | Convert given input data to a TypeDescendants object
@param array|null $data
@return TypeDefinitionContainerInterface[] Returns an array of TypeDefinitionContainerInterface objects | entailment |
public function convertObjectInFolderList(array $data = null)
{
if (empty($data)) {
return null;
}
$objects = array_filter(
array_map(
[$this, 'convertObjectInFolder'],
$data[JSONConstants::JSON_OBJECTINFOLDERLIST_OBJECTS] ?? []
),
function ($item) { return !empty($item); }
);
$objectInFolderList = new ObjectInFolderList();
$objectInFolderList->setObjects($objects);
$objectInFolderList->setHasMoreItems((boolean) ($data[JSONConstants::JSON_OBJECTINFOLDERLIST_HAS_MORE_ITEMS] ?? false));
$objectInFolderList->setNumItems((integer)($data[JSONConstants::JSON_OBJECTINFOLDERLIST_NUM_ITEMS] ?? count($objects)));
$objectInFolderList->setExtensions($this->convertExtension($data, JSONConstants::getObjectInFolderListKeys()));
return $objectInFolderList;
} | Convert given input data to a ObjectInFolderList object
@param array|null $data
@return null|ObjectInFolderList | entailment |
public function convertObjectInFolder(array $data = null)
{
if (empty($data)) {
return null;
}
$objectInFolderData = new ObjectInFolderData();
$object = $this->convertObject($data[JSONConstants::JSON_OBJECTINFOLDER_OBJECT] ?? []);
if ($object !== null) {
$objectInFolderData->setObject($object);
}
$objectInFolderData->setPathSegment((string) $data[JSONConstants::JSON_OBJECTINFOLDER_PATH_SEGMENT] ?? null);
$objectInFolderData->setExtensions($this->convertExtension($data, JSONConstants::getObjectInFolderKeys()));
return $objectInFolderData;
} | Convert given input data to a ObjectInFolderData object
@param array|null $data
@return ObjectInFolderData|null | entailment |
public function convertObjectParents(array $data = null)
{
return array_filter(
array_map(
[$this, 'convertObjectParentData'],
(array) ($data ?? [])
),
function ($item) {
return !empty($item);
// @TODO once a logger is available we should log an INFO message if the parent data could not be converted
}
);
} | Convert given input data to a list of ObjectParentData objects
@param array|null $data
@return ObjectParentData[] | entailment |
public function convertObjectParentData(array $data = null)
{
if (empty($data)) {
return null;
}
$parent = new ObjectParentData();
$object = $this->convertObject($data[JSONConstants::JSON_OBJECTPARENTS_OBJECT] ?? null);
if ($object !== null) {
$parent->setObject($object);
}
$parent->setRelativePathSegment((string) ($data[JSONConstants::JSON_OBJECTPARENTS_RELATIVE_PATH_SEGMENT] ?? ''));
$parent->setExtensions($this->convertExtension($data, JSONConstants::getObjectParentsKeys()));
return $parent;
} | Convert given input data to a ObjectParentData object
@param array|null $data
@return null|ObjectParentData | entailment |
public function convertObjectList(array $data = null)
{
if (empty($data)) {
return null;
}
$objectList = new ObjectList();
$objects = [];
foreach ((array) ($data[JSONConstants::JSON_OBJECTLIST_OBJECTS] ?? []) as $objectData) {
$object = $this->convertObject($objectData);
if ($object !== null) {
$objects[] = $object;
}
}
$objectList->setObjects($objects);
$objectList->setHasMoreItems(
(boolean) ($data[JSONConstants::JSON_OBJECTLIST_HAS_MORE_ITEMS] ?? false)
);
if (isset($data[JSONConstants::JSON_OBJECTLIST_NUM_ITEMS])) {
$objectList->setNumItems((integer) $data[JSONConstants::JSON_OBJECTLIST_NUM_ITEMS]);
}
$objectList->setExtensions($this->convertExtension($data, JSONConstants::getObjectListKeys()));
return $objectList;
} | Convert given input data array to a ObjectList object
@param array|null $data
@return null|ObjectList | entailment |
public function convertQueryResultList(array $data = null)
{
if (empty($data)) {
return null;
}
$objectList = new ObjectList();
$objects = [];
foreach ((array) ($data[JSONConstants::JSON_QUERYRESULTLIST_RESULTS] ?? []) as $objectData) {
$object = $this->convertObject($objectData);
if ($object !== null) {
$objects[] = $object;
}
}
$objectList->setObjects($objects);
$objectList->setHasMoreItems((boolean) ($data[JSONConstants::JSON_QUERYRESULTLIST_HAS_MORE_ITEMS] ?? false));
if (isset($data[JSONConstants::JSON_QUERYRESULTLIST_NUM_ITEMS])) {
$objectList->setNumItems((integer) $data[JSONConstants::JSON_QUERYRESULTLIST_NUM_ITEMS]);
}
$objectList->setExtensions($this->convertExtension($data, JSONConstants::getQueryResultListKeys()));
return $objectList;
} | Convert given input data array from query result to a ObjectList object
@param array|null $data
@return null|ObjectList | entailment |
public function convertDescendants(array $data = null)
{
return array_filter(
array_map(
[$this, 'convertDescendant'],
$data ?? []
),
function ($item) { return !empty($item); }
);
} | Convert given input data array to a ObjectList object
@param array|null $data
@return ObjectInFolderContainer[] | entailment |
public function convertDescendant(array $data = null)
{
if (empty($data)) {
return null;
}
$object = $this->convertObjectInFolder($data[JSONConstants::JSON_OBJECTINFOLDERCONTAINER_OBJECT] ?? null);
if ($object === null) {
throw new CmisRuntimeException('Given data could not be converted to ObjectInFolder!');
}
$objectInFolderContainer = new ObjectInFolderContainer($object);
$objectInFolderContainer->setChildren(
array_filter(
array_map(
[$this, 'convertDescendant'],
(array) ($data[JSONConstants::JSON_OBJECTINFOLDERCONTAINER_CHILDREN] ?? [])
),
function ($item) { return !empty($item); }
)
);
$objectInFolderContainer->setExtensions(
$this->convertExtension($data, JSONConstants::getObjectInFolderContainerKeys())
);
return $objectInFolderContainer;
} | Convert given input data array to a ObjectInFolderContainer object
@param array|null $data
@return null|ObjectInFolderContainer
@throws CmisRuntimeException | entailment |
public function convertFailedToDelete(array $data = null)
{
$result = new FailedToDeleteData();
if (empty($data)) {
return $result;
}
$result->setIds(array_map('strval', $data[JSONConstants::JSON_FAILEDTODELETE_ID] ?? []));
$result->setExtensions($this->convertExtension($data, JSONConstants::getFailedToDeleteKeys()));
return $result;
} | Converts FailedToDelete ids.
@param array|null $data
@return FailedToDeleteData | entailment |
public static function getMatchRegex()
{
$pRegex = IPRange::getMatchRegex();
$regex = substr($pRegex, 2, ( strlen($pRegex) - 4 ));
$separator = static::$separatorRegex;
$maskRegex = static::getMaskRegex();
return sprintf("/^%s%s%s$/", $regex, $separator, $maskRegex);
} | {@inheritdoc} | entailment |
public function getRange($long = true)
{
$parts = $this->getParts();
$ret = array();
$ipLong = $this->ip2long($parts['ip']);
$maskLong = $this->ip2long($parts['mask']);
$ret['begin'] = $this->IPLongAnd(
$ipLong,
$maskLong
);
$ret['end'] = $this->IPLongOr(
$ipLong,
$this->IPLongCom($maskLong)
);
if ($parts['mask'] != "255.255.255.255") {
$ret['begin'] = $this->IPLongAdd($ret['begin'], 1);
}
$ret['begin'] = $this->long2ip($ret['begin']);
$ret['end'] = $this->long2ip($ret['end']);
if ($long) {
$ret['begin'] = $this->ip2long($ret['begin']);
$ret['end'] = $this->ip2long($ret['end']);
}
return $ret;
} | {@inheritdoc} | entailment |
public function get($orderId, $transactionId, array $params = array())
{
$endpoint = '/admin/orders/'.$orderId.'/transactions/'.$transactionId.'.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createObject(Transaction::class, $response['transaction']);
} | Get a single Transaction
@link https://help.shopify.com/api/reference/transaction#show
@param integer $orderId
@param integer $transactionId
@param array $params
@return Transaction | entailment |
public function create(Transaction &$transaction)
{
$data = $transaction->exportData();
$endpoint = '/admin/transactions.json';
$response = $this->request(
$endpoint, 'POST', array(
'transaction' => $data
)
);
$transaction->setData($response['transaction']);
} | Create a new transaction
@link https://help.shopify.com/api/reference/transaction#create
@param Transaction $transaction
@return void | entailment |
public function get($themeId, array $params = array())
{
$endpoint = '/admin/themes/'.$themeId.'.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createObject(Theme::class, $response['theme']);
} | Receive a single theme
@link https://help.shopify.com/api/reference/theme#show
@param integer $themeId
@param array $params
@return Theme | entailment |
public function all(array $params = array())
{
$endpoint = '/admin/themes.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createCollection(Theme::class, $response['themes']);
} | Receive a list of all themes
@link https://help.shopify.com/api/reference/theme#index
@param array $params
@return Theme[] | entailment |
public function create(Theme &$theme)
{
$data = $theme->exportData();
$endpoint = '/admin/themes.json';
$response = $this->request(
$endpoint, 'POST', array(
'theme' => $data
)
);
$theme->setData($response['theme']);
} | Create a new theme
@link https://help.shopify.com/api/reference/theme#create
@param Theme $theme
@return void | entailment |
public function update(Theme &$theme)
{
$data = $theme->exportData();
$endpoint = '/admin/themes/'.$theme->id.'.json';
$response = $this->request(
$endpoint, 'PUT', array(
'theme' => $data
)
);
$theme->setData($response['theme']);
} | Update a theme
@link https://help.shopify.com/api/reference/theme#update
@param Theme $theme
@return void | entailment |
public function getBindingType()
{
$bindingType = $this->session->get(SessionParameter::BINDING_TYPE);
if (!is_string($bindingType)) {
return BindingType::cast(BindingType::CUSTOM);
}
try {
return BindingType::cast($bindingType);
} catch (InvalidEnumerationValueException $exception) {
return BindingType::cast(BindingType::CUSTOM);
}
} | Returns the binding type.
@return BindingType | entailment |
private function search(string $parameter, string $value): SeriesData
{
$options = [
'query' => [
$parameter => $value,
],
'http_errors' => false
];
$json = $this->client->performApiCallWithJsonResponse('get', '/search/series', $options);
return ResponseHandler::create($json, ResponseHandler::METHOD_SEARCH_SERIES)->handle();
} | Search for a series based on parameter and value.
@param string $parameter
@param string $value
@return SeriesData
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidArgumentException
@throws InvalidJsonInResponseException | entailment |
public function isImage()
{
$mime = $this->getMimeType();
// The $image_mimes property contains an array of file extensions and
// their associated MIME types. We will loop through them and look for
// the MIME type of the current UploadedFile.
foreach ($this->image_mimes as $image_mime) {
if (in_array($mime, (array)$image_mime)) {
return true;
}
}
return false;
} | Utility method for detecing whether a given file upload is an image.
@return bool | entailment |
public function getErrorMessage($code = null)
{
$code = $code ?: $this->$code;
static $errors = [
UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d kb).',
UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.',
UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.',
UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.',
UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.',
UPLOAD_ERR_EXTENSION => 'File upload was stopped by a php extension.',
];
$max_file_size = $code === UPLOAD_ERR_INI_SIZE ? self::getMaxFilesize() / 1024 : 0;
$message = isset($errors[$code]) ? $errors[$code] : 'The file "%s" was not uploaded due to an unknown error.';
return sprintf($message, $this->getClientOriginalName(), $max_file_size);
} | Returns an informative upload error message.
@param int $code
@return string | entailment |
protected function getName($name)
{
$name = parent::getName($name);
// This fixes any URL encoded filename and sanitize it
$name = strtolower(urldecode($name));
// Replace spaces with a dash
$name = preg_replace('!\s+!', '-', $name);
// Remove odd characters
return preg_replace('/[^A-Za-z0-9\-_\.]/', '', $name);
} | Returns locale independent base name of the given path.
@param string $name The new file name
@return string containing | entailment |
public function resize(UploadedFile $file, $style)
{
$quality = $this->option('quality', 90);
$this->imagine = new $this->image_processor;
$file_path = @tempnam(sys_get_temp_dir(), 'STP') . '.' . $file->getClientOriginalName();
list($width, $height, $option, $enlarge) = $this->parseStyleDimensions($style);
$method = 'resize' . ucfirst($option);
if ($method == 'resizeCustom') {
$this->resizeCustom($file, $style, $enlarge)
->save($file_path, [
'quality' => $quality,
]);
return $file_path;
}
$image = $this->imagine->open($file->getRealPath());
// Orient the file programmatically
if ($this->option('auto_orient', false)) {
$image = $this->autoOrient($file->getRealPath(), $image);
}
// Force a color palette
if ($palette = $this->option('color_palette')) {
$image->usePalette(new $palette);
}
$this->$method($image, $width, $height, $enlarge)
->save($file_path, [
'quality' => $quality,
'flatten' => false,
]);
return $file_path;
} | Resize an image using the computed settings.
@param UploadedFile $file
@param string $style
@return string | entailment |
protected function parseStyleDimensions($style)
{
if (is_callable($style) === true) {
return [null, null, 'custom', false];
}
$enlarge = true;
// Don't allow the package to enlarge an image
if (strpos($style, '?') !== false) {
$style = str_replace('?', '', $style);
$enlarge = false;
}
if (strpos($style, 'x') === false) {
// Width given, height automatically selected to preserve aspect ratio (landscape).
$width = $style;
return [$width, null, 'landscape', $enlarge];
}
$dimensions = explode('x', $style);
$width = $dimensions[0];
$height = $dimensions[1];
if (empty($width)) {
// Height given, width automatically selected to preserve aspect ratio (portrait).
return [null, $height, 'portrait', $enlarge];
}
$resizing_option = substr($height, -1, 1);
if ($resizing_option == '#') {
// Resize, then crop.
$height = rtrim($height, '#');
return [$width, $height, 'crop', $enlarge];
}
if ($resizing_option == '!') {
// Resize by exact width/height (does not preserve aspect ratio).
$height = rtrim($height, '!');
return [$width, $height, 'exact', $enlarge];
}
// Let the script decide the best way to resize.
return [$width, $height, 'auto', $enlarge];
} | parseStyleDimensions method
Parse the given style dimensions to extract out the file processing options,
perform any necessary image resizing for a given style.
@param string $style
@return array | entailment |
protected function resizeLandscape(ImageInterface $image, $width, $height, $enlarge = true)
{
// Don't enlarge a small image
$box = $image->getSize();
$ratio = $box->getHeight() / $box->getWidth();
if ($enlarge === false && $box->getWidth() < $width) {
$width = $box->getWidth();
}
$dimensions = $image->getSize()
->widen($width)
->heighten($width * $ratio);
return $image->resize($dimensions);
} | Resize an image as a landscape (width only)
@param ImageInterface $image
@param string $width
@param string $height
@param bool $enlarge
@return ManipulatorInterface | entailment |
protected function resizePortrait(ImageInterface $image, $width, $height, $enlarge = true)
{
// Don't enlarge a small image
$box = $image->getSize();
$ratio = $box->getWidth() / $box->getHeight();
if ($enlarge === false && $box->getHeight() < $height) {
$height = $box->getHeight();
}
$dimensions = $image->getSize()
->heighten($height)
->widen($height * $ratio);
return $image->resize($dimensions);
} | Resize an image as a portrait (height only)
@param ImageInterface $image
@param string $width
@param string $height
@param bool $enlarge
@return ManipulatorInterface | entailment |
protected function resizeCrop(ImageInterface $image, $width, $height, $enlarge = true)
{
$size = $image->getSize();
if ($enlarge === false && $size->getWidth() < $width) {
$width = $size->getWidth();
}
if ($enlarge === false && $size->getHeight() < $height) {
$height = $size->getHeight();
}
list($optimal_width, $optimal_height) = $this->getOptimalCrop($size, $width, $height, $enlarge);
// Find center - this will be used for the crop
$center_x = ($optimal_width / 2) - ($width / 2);
$center_y = ($optimal_height / 2) - ($height / 2);
return $image->resize(new Box($optimal_width, $optimal_height))
->crop(new Point($center_x, $center_y), new Box($width, $height));
} | Resize an image and then center crop it.
@param ImageInterface $image
@param string $width
@param string $height
@param bool $enlarge
@return ManipulatorInterface | entailment |
protected function resizeExact(ImageInterface $image, $width, $height, $enlarge = true)
{
return $image->resize(new Box($width, $height));
} | Resize an image to an exact width and height.
@param ImageInterface $image
@param string $width
@param string $height
@param bool $enlarge
@return ImageInterface | entailment |
protected function resizeAuto(ImageInterface $image, $width, $height, $enlarge = true)
{
$size = $image->getSize();
$original_width = $size->getWidth();
$original_height = $size->getHeight();
if ($original_height < $original_width) {
return $this->resizeLandscape($image, $width, $height, $enlarge);
}
if ($original_height > $original_width) {
return $this->resizePortrait($image, $width, $height, $enlarge);
}
if ($height < $width) {
return $this->resizeLandscape($image, $width, $height, $enlarge);
}
if ($height > $width) {
return $this->resizePortrait($image, $width, $height, $enlarge);
}
return $this->resizeExact($image, $width, $height, $enlarge);
} | Resize an image as closely as possible to a given width and
height while still maintaining aspect ratio.
This method is really just a proxy to other resize methods:
If the current image is wider than it is tall, we'll resize landscape.
If the current image is taller than it is wide, we'll resize portrait.
If the image is as tall as it is wide (it's a squarey) then we'll
apply the same process using the new dimensions (we'll resize exact if
the new dimensions are both equal since at this point we'll have a square
image being resized to a square).
@param ImageInterface $image
@param string $width
@param string $height
@param bool $enlarge
@return ManipulatorInterface | entailment |
protected function resizeCustom(UploadedFile $file, $callable, $enlarge = true)
{
return call_user_func_array($callable, [$file, $this->imagine, $enlarge]);
} | Resize an image using a user defined callback.
@param UploadedFile $file
@param $callable
@param bool $enlarge
@return \stdClass | entailment |
protected function getOptimalCrop(BoxInterface $size, $width, $height, $enlarge = true)
{
$height_ratio = $size->getHeight() / $height;
$width_ratio = $size->getWidth() / $width;
if ($height_ratio < $width_ratio) {
$optimal_ratio = $height_ratio;
}
else {
$optimal_ratio = $width_ratio;
}
$optimal_height = round($size->getHeight() / $optimal_ratio, 2);
$optimal_width = round($size->getWidth() / $optimal_ratio, 2);
return [$optimal_width, $optimal_height];
} | Attempts to find the best way to crop.
Takes into account the image being a portrait or landscape.
@param BoxInterface $size
@param string $width
@param string $height
@param bool $enlarge
@return array | entailment |
protected function autoOrient($path, ImageInterface $image)
{
if (function_exists('exif_read_data')) {
$exif = exif_read_data($path);
if (isset($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 2:
$image->flipHorizontally();
break;
case 3:
$image->rotate(180);
break;
case 4:
$image->flipVertically();
break;
case 5:
$image->flipVertically()
->rotate(90);
break;
case 6:
$image->rotate(90);
break;
case 7:
$image->flipHorizontally()
->rotate(90);
break;
case 8:
$image->rotate(-90);
break;
}
}
return $image->strip();
}
else {
return $image;
}
} | Re-orient an image using its embedded Exif profile orientation:
1. Attempt to read the embedded exif data inside the image to determine it's orientation.
if there is no exif data (i.e an exeption is thrown when trying to read it) then we'll
just return the image as is.
2. If there is exif data, we'll rotate and flip the image accordingly to re-orient it.
3. Finally, we'll strip the exif data from the image so that there can be no attempt to 'correct' it again.
@param string $path
@param ImageInterface $image
@return ImageInterface $image | entailment |
public function get(): UserData
{
$json = $this->client->performApiCallWithJsonResponse('get', '/user');
return ResponseHandler::create($json, ResponseHandler::METHOD_USER)->handle();
} | Get basic information about the currently authenticated user.
@return UserData
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidArgumentException
@throws InvalidJsonInResponseException | entailment |
public function getFavorites(): UserFavoritesData
{
$json = $this->client->performApiCallWithJsonResponse('get', '/user/favorites');
return ResponseHandler::create($json, ResponseHandler::METHOD_USER_FAVORITES)->handle();
} | Get user favorites.
@return UserFavoritesData
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidArgumentException
@throws InvalidJsonInResponseException | entailment |
public function removeFavorite(int $identifier): bool
{
$response = $this->client->performApiCall(
'delete',
sprintf('user/favorites/%d', (int) $identifier),
[
'http_errors' => false
]
);
return $response->getStatusCode() === 200 && $response->getReasonPhrase() === 'OK';
} | Remove series with $identifier from favorites.
@param int $identifier
@return bool
@throws UnauthorizedException | entailment |
public function addFavorite(int $identifier): UserFavoritesData
{
$identifier = (int) $identifier;
try {
$json = $this->client->performApiCallWithJsonResponse(
'put',
sprintf('user/favorites/%d', $identifier),
[
'http_errors' => true
]
);
} catch (ClientException $e) {
$message = $this->getApiErrorMessage($e->getResponse());
if ($message !== '') {
throw CouldNotAddFavoriteException::reason($message);
}
throw CouldNotAddFavoriteException::reason($e->getMessage());
}
return ResponseHandler::create($json, ResponseHandler::METHOD_USER_FAVORITES)->handle();
} | Add series with $identifier to favorites.
@param int $identifier
@return UserFavoritesData
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidArgumentException
@throws InvalidJsonInResponseException
@throws CouldNotAddFavoriteException | entailment |
public function getRatings(string $type = null): UserRatingsData
{
if ($type !== null && !in_array($type, self::$ratingTypes, true)) {
throw new InvalidArgumentException(
'Invalid rating type, use one of these instead: ' . implode(self::$ratingTypes, ', ')
);
}
if ($type !== null) {
$json = $this->client->performApiCallWithJsonResponse(
'get',
'/user/ratings/query',
[
'query' => [
'itemType' => $type
]
]
);
} else {
$json = $this->client->performApiCallWithJsonResponse('get', '/user/ratings');
}
return ResponseHandler::create($json, ResponseHandler::METHOD_USER_RATINGS)->handle();
} | Get user ratings.
@param string|null $type Use class constants UsersExtension::RATING_TYPE_*
@return UserRatingsData
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidArgumentException
@throws InvalidJsonInResponseException | entailment |
public function addRating(int $type, int $itemId, int $rating): UserRatingsDataNoLinks
{
if (!in_array($type, self::$ratingTypes, true)) {
throw new InvalidArgumentException(
'Invalid rating type, use one of these instead: ' . implode(self::$ratingTypes, ', ')
);
}
try {
$json = $this->client->performApiCallWithJsonResponse(
'put',
sprintf(
'user/ratings/%s/%d/%d',
$type,
(int) $itemId,
(int) $rating
),
[
'http_errors' => true
]
);
} catch (ClientException $e) {
$message = $this->getApiErrorMessage($e->getResponse());
if ($message !== '') {
throw CouldNotAddOrUpdateUserRatingException::reason($message);
}
throw CouldNotAddOrUpdateUserRatingException::reason($e->getMessage());
}
return ResponseHandler::create($json, ResponseHandler::METHOD_USER_RATINGS_ADD)->handle();
} | Add user rating.
@param int $type Use class constants UsersExtension::RATING_TYPE_*
@param int $itemId
@param int $rating Value between 1 and 10
@return UserRatingsDataNoLinks
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidArgumentException
@throws InvalidJsonInResponseException | entailment |
public function updateRating(int $type, int $itemId, int $rating): UserRatingsDataNoLinks
{
return $this->addRating($type, $itemId, $rating);
} | Update user rating.
@param int $type Use class constants UsersExtension::RATING_TYPE_*
@param int $itemId
@param int $rating Value between 1 and 10
@return UserRatingsDataNoLinks
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidArgumentException
@throws InvalidJsonInResponseException | entailment |
public function removeRating(int $type, int $itemId): bool
{
$response = $this->client->performApiCall(
'delete',
sprintf('user/ratings/%d/%d', (int) $type, (int) $itemId),
[
'http_errors' => false
]
);
return $response->getStatusCode() === 200 && $response->getReasonPhrase() === 'OK';
} | Remove user rating.
@param int $type
@param int $itemId
@return bool
@throws UnauthorizedException | entailment |
private function getApiErrorMessage(ResponseInterface $response): string
{
try {
$body = $response->getBody()->getContents();
} catch (\RuntimeException $re) {
return '';
}
if (strpos($body, '"Error"') !== false
&& ($body = json_decode($body, true))
&& array_key_exists('Error', $body)
) {
return $body['Error'];
}
return '';
} | Extract error message from response body.
@param ResponseInterface $response
@return string | entailment |
public function login(string $apiKey, string $username = null, string $accountIdentifier = null): string
{
$this->client->setToken(null);
$data = [
'apikey' => $apiKey
];
if ($username !== null) {
$data['username'] = $username;
}
if ($accountIdentifier !== null) {
$data['userkey'] = $accountIdentifier;
}
$response = $this->client->performApiCall('post', '/login', [
'body' => json_encode($data),
'http_errors' => true
]);
if ($response->getStatusCode() === 200) {
try {
$contents = $response->getBody()->getContents();
} catch (\RuntimeException $e) {
throw CouldNotLoginException::invalidContents($e->getMessage());
}
$contents = (array) json_decode($contents);
if (!array_key_exists('token', $contents)) {
throw CouldNotLoginException::noTokenInResponse();
}
return $contents['token'];
}
if ($response->getStatusCode() === 401) {
throw CouldNotLoginException::unauthorized();
}
throw CouldNotLoginException::failedWithStatusCode($response->getStatusCode());
} | Returns a session token to be included in the rest of the requests.
Example of usage:
$token = $client->authentication()->login('apikey', 'username', 'accountIdentifier');
$client->setToken($token);
@param string $apiKey
@param string $username
@param string $accountIdentifier
@return string
@throws CouldNotLoginException
@throws UnauthorizedException | entailment |
public function refreshToken(): string
{
$data = $this->client->performApiCallWithJsonResponse('get', '/refresh_token');
$data = (array) json_decode($data);
if (array_key_exists('token', $data)) {
return $data['token'];
}
throw new TokenNotFoundInResponseException('No token found in response.');
} | Refreshes your current, valid JWT token and returns a new token.
@return string
@throws TokenNotFoundInResponseException
@throws RequestFailedException
@throws UnauthorizedException | entailment |
public function interpolate($string, $style = '')
{
return preg_replace_callback("/{(([[:alnum:]]|_|\.|-)+)?}/", function ($match) use ($style) {
$key = $match[1];
// Create local method call.
$method = 'get' . studly_case($key);
// Check for a custom interpolator value.
if (method_exists($this, $method)) {
return $this->$method($style);
}
// Check for an interpolator override
if ($override = $this->manager->config("interpolate.{$key}")) {
return $override;
}
return $this->getAttribute($key);
}, $string);
} | Interpolate a string.
@param string $string
@param string $style
@return string | entailment |
protected function getId()
{
if ($key = $this->manager->config('model_primary_key')) {
return $this->manager->getInstance()->{$key};
}
return $this->manager->getInstance()->getKey();
} | Returns the id of the current object instance.
@return string | entailment |
public function handle()
{
$data = [
'table' => $this->argument('table'),
'attachment' => $this->argument('attachment'),
'queueable' => $this->option('queueable'),
];
// Create filename
$file = base_path("database/migrations/" . date('Y_m_d_His')
. "_add_{$data['attachment']}_fields_to_{$data['table']}_table.php");
// Save the new migration to disk using the MediaSort migration view.
$migration = $this->view->file(realpath(__DIR__ . '/../../resources/views/migration.blade.php'), $data)->render();
$this->file->put($file, $migration);
// Print a created migration message to the console.
$this->info("Created migration: $file");
} | Execute the console command.
@return void | entailment |
public function changeConfig($config)
{
if (!is_array($config)) {
return false;
}
$this->config = array_merge($this->config, $config);
return true;
} | Change the configuration values.
@param array $configArray
@return bool | entailment |
public function set($key, $content, $expiry = 0)
{
$cacheObj = new \stdClass();
if (!is_string($content)) {
$content = serialize($content);
}
$cacheObj->content = $content;
if (!$expiry) {
// If no expiry specified, set to 'Never' expire timestamp (+10 years)
$cacheObj->expiryTimestamp = time() + 315360000;
} elseif ($expiry > 2592000) {
// For value greater than 30 days, interpret as timestamp
$cacheObj->expiryTimestamp = $expiry;
} else {
// Else, interpret as number of seconds
$cacheObj->expiryTimestamp = time() + $expiry;
}
// Do not save if cache has already expired
if ($cacheObj->expiryTimestamp < time()) {
$this->delete($key);
return false;
}
$cacheFileData = json_encode($cacheObj);
if ($this->config['gzipCompression']) {
$cacheFileData = gzcompress($cacheFileData);
}
$filePath = $this->getFilePathFromKey($key);
$result = file_put_contents($filePath, $cacheFileData);
return $result ? true : false;
} | Sets an item in the cache.
@param mixed $key
@param mixed $content
@param int $expiry
@return bool | entailment |
public function get($key)
{
$filePath = $this->getFilePathFromKey($key);
if (!file_exists($filePath)) {
return false;
}
if (!is_readable($filePath)) {
return false;
}
$cacheFileData = file_get_contents($filePath);
if ($this->config['gzipCompression']) {
$cacheFileData = gzuncompress($cacheFileData);
}
$cacheObj = json_decode($cacheFileData);
// Unable to decode JSON (could happen if compression was turned off while compressed caches still exist)
if ($cacheObj === null) {
return false;
}
if (!function_exists('sys_getloadavg')) {
throw new Exception('Your PHP installation does not support `sys_getloadavg` (Windows?). Please set `unixLoadUpperThreshold` to `-1` in your RWFileCache config.');
}
if ($this->config['unixLoadUpperThreshold'] == -1) {
$unixLoad = [0 => PHP_INT_MAX, 1 => PHP_INT_MAX, 2 => PHP_INT_MAX];
} else {
$unixLoad = sys_getloadavg();
}
if ($cacheObj->expiryTimestamp > time() || $unixLoad[0] >= $this->config['unixLoadUpperThreshold']) {
// Cache item has not yet expired or system load is too high
$content = $cacheObj->content;
if (($unserializedContent = @unserialize($content)) !== false) {
// Normal unserialization
$content = $unserializedContent;
} elseif ($content == serialize(false)) {
// Edge case to handle boolean false being stored
$content = false;
}
return $content;
} else {
// Cache item has expired
return false;
}
} | Returns a value from the cache.
@param string $key
@return mixed | entailment |
public function delete($key)
{
$filePath = $this->getFilePathFromKey($key);
if (!file_exists($filePath)) {
return false;
}
return unlink($filePath);
} | Remove a value from the cache.
@param string $key
@return bool | entailment |
private function deleteDirectoryTree($directory)
{
$filePaths = scandir($directory);
foreach ($filePaths as $filePath) {
if ($filePath == '.' || $filePath == '..') {
continue;
}
$fullFilePath = $directory.'/'.$filePath;
if (is_dir($fullFilePath)) {
$result = $this->deleteDirectoryTree($fullFilePath);
if ($result) {
$result = rmdir($fullFilePath);
}
} else {
if (basename($fullFilePath) == '.keep') {
continue;
}
$result = unlink($fullFilePath);
}
if (!$result) {
return false;
}
}
return true;
} | Removes cache files from a given directory.
@param string $directory
@return bool | entailment |
public function increment($key, $offset = 1)
{
$filePath = $this->getFilePathFromKey($key);
if (!file_exists($filePath)) {
return false;
}
if (!is_readable($filePath)) {
return false;
}
$cacheFileData = file_get_contents($filePath);
if ($this->config['gzipCompression']) {
$cacheFileData = gzuncompress($cacheFileData);
}
$cacheObj = json_decode($cacheFileData);
$content = $cacheObj->content;
if ($unserializedContent = @unserialize($content)) {
$content = $unserializedContent;
}
if (!$content || !is_numeric($content)) {
return false;
}
$content += $offset;
return $this->set($key, $content, $cacheObj->expiryTimestamp);
} | Increments a value within the cache.
@param string $key
@param int $offset
@return bool | entailment |
public function replace($key, $content, $expiry = 0)
{
if (!$this->get($key)) {
return false;
}
return $this->set($key, $content, $expiry);
} | Replaces a value within the cache.
@param string $key
@param mixed $content
@param int $expiry
@return bool | entailment |
protected function getFilePathFromKey($key)
{
$key = basename($key);
$badChars = ['-', '.', '_', '\\', '*', '\"', '?', '[', ']', ':', ';', '|', '=', ','];
$key = str_replace($badChars, '/', $key);
while (strpos($key, '//') !== false) {
$key = str_replace('//', '/', $key);
}
$directoryToCreate = $this->config['cacheDirectory'];
$endOfDirectory = strrpos($key, '/');
if ($endOfDirectory !== false) {
$directoryToCreate = $this->config['cacheDirectory'].substr($key, 0, $endOfDirectory);
}
if (!file_exists($directoryToCreate)) {
$result = mkdir($directoryToCreate, 0777, true);
if (!$result) {
return false;
}
}
$filePath = $this->config['cacheDirectory'].$key.'.'.$this->config['fileExtension'];
return $filePath;
} | Returns the file path from a given cache key, creating the relevant directory structure if necessary.
@param string $key
@return string | entailment |
public function make($file)
{
if ($file instanceof SymfonyUploadedFile) {
return $this->createFromObject($file);
}
if (is_array($file)) {
if (isset($file['base64']) && isset($file['name'])) {
return $this->createFromBase64($file['name'], $file['base64']);
}
else {
return $this->createFromArray($file);
}
}
if (array_key_exists('scheme', parse_url($file))) {
return $this->createFromUrl($file);
}
return $this->createFromString($file);
} | Build an UploadedFile object using various file input types.
@param mixed $file
@return \Torann\MediaSort\File\UploadedFile | entailment |
protected function createFromObject(SymfonyUploadedFile $file)
{
$path = $file->getPathname();
$original_name = $file->getClientOriginalName();
$mime_type = $file->getClientMimeType();
$size = $file->getSize();
$error = $file->getError();
$upload_file = new UploadedFile($path, $original_name, $mime_type, $size, $error);
// Throw error if the object is not valid
if ($upload_file->isValid() === false) {
throw new FileException(
$upload_file->getErrorMessage(
$upload_file->getError()
)
);
}
return $upload_file;
} | Build a \Torann\MediaSort\File\UploadedFile object from
a Symfony\Component\HttpFoundation\File\UploadedFile object.
@param \Symfony\Component\HttpFoundation\File\UploadedFile $file
@return \Torann\MediaSort\File\UploadedFile
@throws \Torann\MediaSort\Exceptions\FileException | entailment |
protected function createFromBase64($filename, $data)
{
// Get temporary destination
$destination = sys_get_temp_dir() . '/' . str_random(4) . '-' . $filename;
// Create destination if not already there
if (is_dir(dirname($destination)) === false) {
mkdir(dirname($destination), 0755, true);
}
// Create temporary file
file_put_contents($destination, base64_decode($data), 0);
// Get mime type
$mime_type = mime_content_type($destination);
return new UploadedFile($destination, $filename, $mime_type);
} | Build a Torann\MediaSort\File\UploadedFile object from a
base64 encoded image array. Usually from an API request.
@param array $filename
@param array $data
@return \Torann\MediaSort\File\UploadedFile | entailment |
protected function createFromUrl($file)
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $file,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
CURLOPT_FOLLOWLOCATION => 1,
]);
$raw_file = curl_exec($ch);
curl_close($ch);
// Get the mime type of the file
$size_info = getimagesizefromstring($raw_file);
$mime = $size_info['mime'];
// Create a file path for the file by storing it on disk.
$file_path = @tempnam(sys_get_temp_dir(), 'STP');
file_put_contents($file_path, $raw_file);
// Get the original filename
$name = strtok(pathinfo($file, PATHINFO_BASENAME), '?');
// Append missing file extension
if (empty(pathinfo($file, PATHINFO_EXTENSION))) {
$name = $name . '.' . $this->getExtension($mime);
}
// Get the length of the file
if (function_exists('mb_strlen')) {
$size = mb_strlen($raw_file, '8bit');
}
else {
$size = strlen($raw_file);
}
return new UploadedFile($file_path, $name, $mime, $size, 0);
} | Fetch a remote file using a string URL and convert it into
an instance of Torann\MediaSort\File\UploadedFile.
@param string $file
@return \Torann\MediaSort\File\UploadedFile | entailment |
protected function setPathPrefix()
{
if ($this->media->local_root) {
// Interpolate path
$root = $this->media->getInterpolator()
->interpolate($this->media->local_root);
// Set path
$this->filesystem->getDriver()
->getAdapter()
->setPathPrefix($root);
}
} | Set local path prefix from settings.
@return void | entailment |
public function register()
{
$this->registerMediaSort();
if ($this->app->runningInConsole()) {
$this->registerResources();
$this->registerCommands();
}
$this->mergeConfigFrom(
__DIR__ . '/../config/mediasort.php', 'mediasort'
);
} | Register the service provider.
@return void | entailment |
protected function registerMediaSort()
{
$this->media_sort_null = sha1(time());
if (defined('MEDIASORT_NULL') === false) {
define('MEDIASORT_NULL', $this->media_sort_null);
}
} | Register \Torann\MediaSort\MediaSort with the container.
@return void | entailment |
public function registerCommands()
{
$this->app->bind('mediasort.fasten', function ($app) {
return new Commands\FastenCommand(
$app['view'], $app['files']
);
});
// TODO: Get this working
//$this->app->bind('mediasort.refresh', function ($app) {
// return new Commands\RefreshCommand(
// new Services\ImageRefreshService()
// );
//});
$this->commands([
'mediasort.fasten',
//'mediasort.refresh',
]);
} | Register commands.
@return void | entailment |
public function handle(): ValueObject
{
$data = $this->getData();
$class = self::$mapping[$this->method];
return new $class($data);
} | {@inheritdoc}
@throws InvalidJsonInResponseException | entailment |
public function all(): LanguageData
{
$json = $this->client->performApiCallWithJsonResponse('get', '/languages');
return ResponseHandler::create($json, ResponseHandler::METHOD_LANGUAGES)->handle();
} | Get all available languages.
@return LanguageData
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidJsonInResponseException
@throws InvalidArgumentException | entailment |
public function get($identifier): Language
{
$json = $this->client->performApiCallWithJsonResponse('get', sprintf('/languages/%d', (int) $identifier));
return ResponseHandler::create($json, ResponseHandler::METHOD_LANGUAGE)->handle();
} | Get information about a particular language, given the language ID.
@param int $identifier
@return Language
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidJsonInResponseException
@throws InvalidArgumentException | entailment |
public function getById($id, array $options = [])
{
$query = $this->createBaseBuilder($options);
return $query->find($id);
} | Get a resource by its primary key
@param mixed $id
@param array $options
@return Collection | entailment |
public function getRecent(array $options = [])
{
$query = $this->createBaseBuilder($options);
$query->orderBy($this->getCreatedAtColumn(), 'DESC');
return $query->get();
} | Get all resources ordered by recentness
@param array $options
@return Collection | entailment |
public function getRecentWhere($column, $value, array $options = [])
{
$query = $this->createBaseBuilder($options);
$query->where($column, $value);
$query->orderBy($this->getCreatedAtColumn(), 'DESC');
return $query->get();
} | Get all resources by a where clause ordered by recentness
@param string $column
@param mixed $value
@param array $options
@return Collection | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.