sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function getRepositoryUrlCache()
{
$repositoryUrlCache = $this->getSession()->get(SessionParameter::REPOSITORY_URL_CACHE);
if ($repositoryUrlCache === null) {
$repositoryUrlCache = new RepositoryUrlCache();
$this->getSession()->put(SessionParameter::REPOSITORY_URL_CACHE, $repositoryUrlCache);
}
return $repositoryUrlCache;
} | Returns the repository URL cache or creates a new cache if it doesn't
exist.
@return RepositoryUrlCache | entailment |
protected function setSession(BindingSessionInterface $session)
{
$this->session = $session;
$succinct = $session->get(SessionParameter::BROWSER_SUCCINCT);
$this->succinct = $succinct ?? true;
$this->dateTimeFormat = DateTimeFormat::cast($session->get(SessionParameter::BROWSER_DATETIME_FORMAT));
} | Sets the current session.
@param BindingSessionInterface $session | entailment |
protected function getRepositoriesInternal($repositoryId = null)
{
$repositoryUrlCache = $this->getRepositoryUrlCache();
if ($repositoryId === null) {
// no repository id provided -> get all
$url = $repositoryUrlCache->buildUrl($this->getServiceUrl());
} else {
// use URL of the specified repository
$url = $repositoryUrlCache->getRepositoryUrl($repositoryId, Constants::SELECTOR_REPOSITORY_INFO) ??
$repositoryUrlCache->buildUrl($this->getServiceUrl());
}
$repositoryInfos = [];
$result = $this->readJson($url);
if (!is_array($result)) {
throw new CmisConnectionException(
'Could not fetch repository info! Response is not a valid JSON.',
1416343166
);
}
foreach ($result as $item) {
if (is_array($item)) {
$repositoryInfo = $this->getJsonConverter()->convertRepositoryInfo($item);
if ($repositoryInfo instanceof RepositoryInfoBrowserBinding) {
$id = $repositoryInfo->getId();
$repositoryUrl = $repositoryInfo->getRepositoryUrl();
$rootUrl = $repositoryInfo->getRootUrl();
if (empty($id) || empty($repositoryUrl) || empty($rootUrl)) {
throw new CmisConnectionException(
sprintf('Found invalid Repository Info! (id: %s)', $id),
1415187765
);
}
$this->getRepositoryUrlCache()->addRepository($id, $repositoryUrl, $rootUrl);
$repositoryInfos[] = $repositoryInfo;
}
} else {
throw new CmisConnectionException(
sprintf(
'Found invalid repository info! Value of type "array" was expected'
. 'but value of type "%s" was given.',
gettype($item)
),
1415187764
);
}
}
return $repositoryInfos;
} | Retrieves the the repository info objects.
@param string|null $repositoryId
@throws CmisConnectionException
@return RepositoryInfo[] Returns ALL Repository Infos that are available and not just the one requested by id. | entailment |
protected function read(Url $url)
{
/** @var Response $response */
try {
$response = $this->getHttpInvoker()->get((string) $url);
} catch (RequestException $exception) {
$code = 0;
$message = null;
if ($exception->getResponse()) {
$code = $exception->getResponse()->getStatusCode();
$message = $exception->getResponse()->getBody();
}
throw $this->convertStatusCode(
$code,
(string) $message,
$exception
);
}
return $response;
} | Do a get request for the given url
@param Url $url
@return Response
@throws CmisBaseException an more specific exception of this type could be thrown. For more details see
@see AbstractBrowserBindingService::convertStatusCode() | entailment |
protected function convertStatusCode($code, $message, \Exception $exception = null)
{
$messageData = json_decode($message, true);
if (is_array($messageData) && !empty($messageData[JSONConstants::ERROR_EXCEPTION])) {
$jsonError = $messageData[JSONConstants::ERROR_EXCEPTION];
if (!empty($messageData[JSONConstants::ERROR_MESSAGE])
&& is_string($messageData[JSONConstants::ERROR_MESSAGE])
) {
$message = $messageData[JSONConstants::ERROR_MESSAGE];
}
$exceptionName = '\\Dkd\\PhpCmis\\Exception\\Cmis' . ucfirst($jsonError) . 'Exception';
if (class_exists($exceptionName)) {
return new $exceptionName($message, null, $exception);
}
}
if (empty($message) && $exception !== null) {
$message = $exception->getMessage();
}
// fall back to status code
switch ($code) {
case 301:
case 302:
case 303:
case 307:
return new CmisConnectionException(
'Redirects are not supported (HTTP status code ' . $code . '): ' . $message,
null,
$exception
);
case 400:
return new CmisInvalidArgumentException($message, null, $exception);
case 401:
return new CmisUnauthorizedException($message, null, $exception);
case 403:
return new CmisPermissionDeniedException($message, null, $exception);
case 404:
return new CmisObjectNotFoundException($message, null, $exception);
case 405:
return new CmisNotSupportedException($message, null, $exception);
case 407:
return new CmisProxyAuthenticationException($message, null, $exception);
case 409:
return new CmisConstraintException($message, null, $exception);
default:
return new CmisRuntimeException($message, null, $exception);
}
} | Converts an error message or a HTTP status code into an Exception.
@see http://docs.oasis-open.org/cmis/CMIS/v1.1/os/CMIS-v1.1-os.html#x1-551021r549
@param integer $code
@param string $message
@param null|\Exception $exception
@return CmisBaseException | entailment |
protected function getPathUrl($repositoryId, $path, $selector = null)
{
$result = $this->getRepositoryUrlCache()->getPathUrl($repositoryId, $path, $selector);
if ($result === null) {
$this->getRepositoriesInternal($repositoryId);
$result = $this->getRepositoryUrlCache()->getPathUrl($repositoryId, $path, $selector);
}
if ($result === null) {
throw new CmisObjectNotFoundException(
sprintf(
'Unknown path! Repository: "%s" | Path: "%s" | Selector: "%s"',
$repositoryId,
$path,
$selector
)
);
}
return $result;
} | Generate url for a given path of a given repository.
@param string $repositoryId
@param string $path
@param string|null $selector
@throws CmisConnectionException
@throws CmisObjectNotFoundException
@return Url | entailment |
protected function postJson(Url $url, $content = [], array $headers = [])
{
return \json_decode($this->post($url, $content, $headers)->getBody(), true);
} | Wrapper for calling post() and reading response as JSON, as is the general use case.
@param Url $url
@param array $content
@param array $headers
@return mixed | entailment |
protected function post(Url $url, $content = [], array $headers = [])
{
if (is_resource($content) || is_object($content)) {
$headers['body'] = $content;
} elseif (is_array($content)) {
$headers['multipart'] = $this->convertQueryArrayToMultiPart($content);
}
try {
return $this->getHttpInvoker()->post((string) $url, $headers);
} catch (RequestException $exception) {
throw $this->convertStatusCode(
$exception->getResponse()->getStatusCode(),
(string) $exception->getResponse()->getBody(),
$exception
);
}
} | Performs a POST on an URL, checks the response code and returns the
result.
@param Url $url Request url
@param resource|string|StreamInterface|array $content Entity body data or an array for POST fields and files
@param array $headers Additional header options
@return ResponseInterface
@throws CmisBaseException an more specific exception of this type could be thrown. For more details see
@see AbstractBrowserBindingService::convertStatusCode() | entailment |
protected function getTypeDefinitionInternal($repositoryId, $typeId)
{
if (empty($repositoryId)) {
throw new CmisInvalidArgumentException('Repository id must not be empty!');
}
if (empty($typeId)) {
throw new CmisInvalidArgumentException('Type id must not be empty!');
}
// build URL
$url = $this->getRepositoryUrl($repositoryId, Constants::SELECTOR_TYPE_DEFINITION);
$url->getQuery()->modify([Constants::PARAM_TYPE_ID => $typeId]);
return $this->getJsonConverter()->convertTypeDefinition(
(array) $this->readJson($url)
);
} | Retrieves a type definition.
@param string $repositoryId
@param string $typeId
@return TypeDefinitionInterface|null
@throws CmisInvalidArgumentException if repository id or type id is <code>null</code> | entailment |
protected function getRepositoryUrl($repositoryId, $selector = null)
{
$result = $this->getRepositoryUrlCache()->getRepositoryUrl($repositoryId, $selector);
if ($result === null) {
$this->getRepositoriesInternal($repositoryId);
$result = $this->getRepositoryUrlCache()->getRepositoryUrl($repositoryId, $selector);
}
if ($result === null) {
throw new CmisObjectNotFoundException(
sprintf(
'Unknown repository! Repository: "%s" | Selector: "%s"',
$repositoryId,
$selector
)
);
}
return $result;
} | Get url for a repository
@param string $repositoryId
@param string|null $selector
@throws CmisConnectionException
@throws CmisObjectNotFoundException
@return Url | entailment |
protected function convertPropertiesToQueryArray(PropertiesInterface $properties)
{
$propertiesArray = [];
$propertyCounter = 0;
$propertiesArray[Constants::CONTROL_PROP_ID] = [];
$propertiesArray[Constants::CONTROL_PROP_VALUE] = [];
foreach ($properties->getProperties() as $property) {
$propertiesArray[Constants::CONTROL_PROP_ID][$propertyCounter] = $property->getId();
$propertyValues = $property->getValues();
if (count($propertyValues) === 1) {
$propertiesArray[Constants::CONTROL_PROP_VALUE][$propertyCounter] =
$this->convertPropertyValueToSimpleType(
$property->getFirstValue()
);
} elseif (count($propertyValues) > 1) {
$propertyValueCounter = 0;
$propertiesArray[Constants::CONTROL_PROP_VALUE][$propertyCounter] = [];
foreach ($propertyValues as $propertyValue) {
$propertiesArray[Constants::CONTROL_PROP_VALUE][$propertyCounter][$propertyValueCounter] =
$this->convertPropertyValueToSimpleType(
$propertyValue
);
$propertyValueCounter ++;
}
}
$propertyCounter ++;
}
return $propertiesArray;
} | Converts a Properties list into an array that can be used for the CMIS request.
@param PropertiesInterface $properties
@return array Example <code>
array('propertyId' => array(0 => 'myId'), 'propertyValue' => array(0 => 'valueOfMyId'))
</code> | entailment |
protected function convertPropertyValueToSimpleType($value)
{
if ($value instanceof \DateTime) {
// CMIS expects a timestamp in milliseconds
$value = $value->getTimestamp() * 1000;
} elseif (is_bool($value)) {
// Booleans must be represented in string form since request will fail if cast to integer
$value = $value ? 'true' : 'false';
}
return $value;
} | Converts values to a format that can be used for the CMIS Browser binding request.
@param mixed $value
@return mixed | entailment |
protected function convertAclToQueryArray(AclInterface $acl, $principalControl, $permissionControl)
{
$acesArray = [];
$principalCounter = 0;
foreach ($acl->getAces() as $ace) {
$permissions = $ace->getPermissions();
if ($ace->getPrincipal() !== null && $ace->getPrincipal()->getId() && !empty($permissions)) {
$acesArray[$principalControl][$principalCounter] = $ace->getPrincipal()->getId();
$permissionCounter = 0;
$acesArray[$permissionControl][$principalCounter] = [];
foreach ($permissions as $permission) {
$acesArray[$permissionControl][$principalCounter][$permissionCounter] = $permission;
$permissionCounter ++;
}
$principalCounter ++;
}
}
return $acesArray;
} | Converts a Access Control list into an array that can be used for the CMIS request
@param AclInterface $acl
@param string $principalControl one of principal ace constants
CONTROL_ADD_ACE_PRINCIPAL or CONTROL_REMOVE_ACE_PRINCIPAL
@param string $permissionControl one of permission ace constants
CONTROL_REMOVE_ACE_PRINCIPAL or CONTROL_REMOVE_ACE_PERMISSION
@return array Example <code>
array('addACEPrincipal' => array(0 => 'principalId'),
'addACEPermission' => array(0 => array(0 => 'permissonValue')))
</code> | entailment |
protected function convertPolicyIdArrayToQueryArray(array $policies)
{
$policiesArray = [];
$policyCounter = 0;
foreach ($policies as $policy) {
$policiesArray[Constants::CONTROL_POLICY][$policyCounter] = (string) $policy;
$policyCounter ++;
}
return $policiesArray;
} | Converts a policies array into an array that can be used for the CMIS request
@param string[] $policies A list of policy string representations
@return array | entailment |
protected function appendPoliciesToUrl(Url $url, array $policies)
{
if (!empty($policies)) {
$url->getQuery()->modify($this->convertPolicyIdArrayToQueryArray($policies));
}
} | Appends policies parameters to url
@param Url $url
@param string[] $policies A list of policy IDs that must be applied to the newly created document object | entailment |
protected function appendAddAcesToUrl(Url $url, AclInterface $addAces = null)
{
if ($addAces !== null) {
$url->getQuery()->modify(
$this->convertAclToQueryArray(
$addAces,
Constants::CONTROL_ADD_ACE_PRINCIPAL,
Constants::CONTROL_ADD_ACE_PERMISSION
)
);
}
} | Appends addAces parameters to url
@param Url $url
@param AclInterface|null $addAces A list of ACEs | entailment |
protected function appendRemoveAcesToUrl(Url $url, AclInterface $removeAces = null)
{
if ($removeAces !== null) {
$url->getQuery()->modify(
$this->convertAclToQueryArray(
$removeAces,
Constants::CONTROL_REMOVE_ACE_PRINCIPAL,
Constants::CONTROL_REMOVE_ACE_PERMISSION
)
);
}
} | Appends removeAces parameters to url
@param Url $url
@param AclInterface|null $removeAces A list of ACEs | entailment |
public function loadContentLink($repositoryId, $documentId)
{
$result = $this->getRepositoryUrlCache()->getObjectUrl($repositoryId, $documentId, Constants::SELECTOR_CONTENT);
return $result === null ? null : (string) $result;
} | Gets the content link from the cache if it is there or loads it into the
cache if it is not there.
@param string $repositoryId
@param string $documentId
@return string|null | entailment |
public function loadRenditionContentLink($repositoryId, $documentId, $streamId)
{
$result = $this->getRepositoryUrlCache()->getObjectUrl($repositoryId, $documentId, Constants::SELECTOR_CONTENT);
if ($result !== null) {
$result->getQuery()->modify([Constants::PARAM_STREAM_ID => $streamId]);
$result = (string) $result;
}
return $result;
} | Gets a rendition content link from the cache if it is there or loads it
into the cache if it is not there.
@param string $repositoryId
@param string $documentId
@param string $streamId
@return string|null | entailment |
public function setExtensions(array $extensions)
{
foreach ($extensions as $extension) {
$this->checkType(CmisExtensionElementInterface::class, $extension);
}
$this->extensions = $extensions;
} | Sets the list of top-level extension elements.
@param CmisExtensionElementInterface[] $extensions | entailment |
public function create($recurringApplicationChargeId, UsageCharge $usageCharge)
{
$data = $usageCharge->exportData();
$endpoint = '/admin/recurring_application_charges/'.$recurringApplicationChargeId.'/usage_charges.json';
$response = $this->request(
$endpoint, 'POST', array(
'usage_charge' => $data
)
);
$usageCharge->setData($response['usage_charge']);
} | Create a usage charges
@link https://help.shopify.com/api/reference/usagecharge#create
@param integer $recurringApplicationChargeId
@param UsageCharge $usageCharge
@return void | entailment |
public function get($recurringApplicationChargeId, $usageChargeId, array $params = array())
{
$endpoint = '/admin/recurring_application_charges/'.$recurringApplicationChargeId.'/usage_charges/'.$usageChargeId.'.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createObject(UsageCharge::class, $response['usage_charge']);
} | Receive a single usage charge
@link https://help.shopify.com/api/reference/usagecharge#show
@param integer $recurringApplicationChargeId
@param integer $usageChargeId
@param array $params
@return UsageCharge | entailment |
public function all($recurringApplicationChargeId, array $params = array())
{
$endpoint = '/admin/recurring_application_charges/'.$recurringApplicationChargeId.'/usage_charges.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createCollection(UsageCharge::class, $response['usage_charges']);
} | Retrieve all usage charges
@link https://help.shopify.com/api/reference/usagecharge#index
@param integer $recurringApplicationChargeId
@param array $params
@return UsageCharge[] | entailment |
public function setObjects(array $objects)
{
foreach ($objects as $object) {
$this->checkType(ObjectInFolderDataInterface::class, $object);
}
$this->objects = $objects;
} | checks input array for ObjectInFolderDataInterface and sets objects
@param ObjectInFolderDataInterface[] $objects | entailment |
public function addList(array $list, $listName, $state)
{
if (!is_bool($state)) {
throw new \InvalidArgumentException("Wrong parameter 'state' is not boolean");
}
$entryList = $this->entryFactory->getEntryList($list, $state);
$this->listMerger->addList($entryList, $listName);
return $this;
} | Add a list
@param array $list List
@param string $listName Identifier for the list
@param boolean|null $state Whether the list is trusted or not
@return $this | entailment |
public function handle(callable $callBack = null)
{
$ip = $this->getIpAddress();
$isAllowed = $this->listMerger->isAllowed($ip, $this->defaultState);
if ($callBack !== null) {
return call_user_func($callBack, array($this, $isAllowed));
} else {
return $isAllowed;
}
} | Handle the current request
@param callable $callBack Result handler
@return boolean | entailment |
public function getSpi(BindingSessionInterface $session)
{
$spi = $session->get(self::SPI_OBJECT);
if ($spi !== null) {
return $spi;
}
$spiClass = $session->get(SessionParameter::BINDING_CLASS);
if (empty($spiClass) || !class_exists($spiClass)) {
throw new CmisRuntimeException(
sprintf('The given binding class "%s" is not valid!', $spiClass)
);
}
if (!is_a($spiClass, CmisInterface::class, true)) {
throw new CmisRuntimeException(
sprintf('The given binding class "%s" does not implement required CmisInterface!', $spiClass)
);
}
try {
$spi = new $spiClass($session);
} catch (\Exception $exception) {
throw new CmisRuntimeException(
sprintf('Could not create object of type "%s"!', $spiClass),
null,
$exception
);
}
$session->put(self::SPI_OBJECT, $spi);
return $spi;
} | Gets the SPI object for the given session. If there is already a SPI
object in the session it will be returned. If there is no SPI object it
will be created and put into the session.
@param BindingSessionInterface $session
@return CmisInterface | entailment |
public function getTypeDefinitionCache(BindingSessionInterface $session)
{
$cache = $session->get(self::TYPE_DEFINITION_CACHE);
if ($cache !== null) {
return $cache;
}
$className = $session->get(SessionParameter::TYPE_DEFINITION_CACHE_CLASS);
try {
$cache = new $className();
} catch (\Exception $exception) {
throw new CmisRuntimeException(
sprintf('Could not create object of type "%s"!', $className),
null,
$exception
);
}
$session->put(self::TYPE_DEFINITION_CACHE, $cache);
return $cache;
} | Returns the type definition cache from the session.
@param BindingSessionInterface $session
@return Cache
@throws CmisRuntimeException Exception is thrown if cache instance could not be initialized. | entailment |
public static function match($entry)
{
$entries = preg_split('/' . static::$separatorRegex .'/', $entry);
if (count($entries) == 2) {
$checkIp = static::matchIp($entries[0]);
if ($checkIp && ($entries[1] >= 0) && ($entries[1] <= static::NB_BITS)) {
return true;
}
}
return false;
} | {@inheritdoc} | entailment |
public function getParts()
{
$keys = array('ip', 'mask');
$parts = array_combine($keys, preg_split('/'. self::$separatorRegex .'/', $this->template));
$bin = str_pad(str_repeat('1', (int) $parts['mask']), self::NB_BITS, 0);
$parts['mask'] = $this->long2ip($this->IPLongBaseConvert($bin, 2, 10));
return $parts;
} | {@inheritdoc} | entailment |
function get($id, $group = 'default', $doNotTestCacheValidity = false)
{
if ($data = parent::get($id, $group, true)) {
if ($filemtime = $this->lastModified()) {
if ($filemtime > $this->_masterFile_mtime) {
return $data;
}
}
}
return false;
} | Test if a cache is available and (if yes) return it
@param string $id cache id
@param string $group name of the cache group
@param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
@return string data of the cache (else : false)
@access public | entailment |
public function setValues(array $values)
{
foreach ($values as $value) {
$this->checkType(\DateTime::class, $value, true);
}
parent::setValues($values);
} | {@inheritdoc}
@param \DateTime[] $values | entailment |
public function addRepository($repositoryId, $repositoryUrl, $rootUrl)
{
if (empty($repositoryId) || empty($repositoryUrl) || empty($rootUrl)) {
throw new CmisInvalidArgumentException(
'Repository Id or Repository URL or Root URL is not set!',
1408536098
);
}
$this->repositoryUrls[$repositoryId] = $repositoryUrl;
$this->rootUrls[$repositoryId] = $rootUrl;
} | Adds the URLs of a repository to the cache.
@param string $repositoryId
@param string $repositoryUrl
@param string $rootUrl | entailment |
public function getRepositoryUrl($repositoryId, $selector = null)
{
$baseUrl = $this->getRepositoryBaseUrl($repositoryId);
if ($baseUrl === null) {
return null;
}
$repositoryUrl = $this->buildUrl($baseUrl);
if ($selector !== null && $selector !== '') {
$repositoryUrl->getQuery()->modify([Constants::PARAM_SELECTOR => $selector]);
}
return $repositoryUrl;
} | Returns the repository URL of a repository.
@param string $repositoryId
@param string|null $selector add optional cmis selector parameter
@return Url|null | entailment |
public function getObjectUrl($repositoryId, $objectId, $selector = null)
{
if ($this->getRootUrl($repositoryId) === null) {
return null;
}
$url = $this->buildUrl($this->getRootUrl($repositoryId));
$urlQuery = $url->getQuery();
$urlQuery->modify([Constants::PARAM_OBJECT_ID => (string) $objectId]);
if (!empty($selector)) {
$urlQuery->modify([Constants::PARAM_SELECTOR => (string) $selector]);
}
return $url;
} | Get URL for an object request
@param string $repositoryId
@param string $objectId
@param string|null $selector
@return Url|null | entailment |
public function getPathUrl($repositoryId, $path, $selector = null)
{
if ($this->getRootUrl($repositoryId) === null) {
return null;
}
$url = $this->buildUrl($this->getRootUrl($repositoryId));
$url->getPath()->append($path);
if (!empty($selector)) {
$url->getQuery()->modify([Constants::PARAM_SELECTOR => $selector]);
}
return $url;
} | Get Repository URL with given path
@param string $repositoryId
@param string $path
@param string|null $selector
@return Url | entailment |
public function getSource(OperationContextInterface $context = null)
{
$sourceId = $this->getSourceId();
if ($sourceId === null) {
return null;
}
$context = $this->ensureContext($context);
return $this->getSession()->getObject($sourceId, $context);
} | Gets the source object using the given OperationContext.
@param OperationContextInterface|null $context
@return CmisObjectInterface|null If the source object ID is invalid, <code>null</code> will be returned. | entailment |
public function getTarget(OperationContextInterface $context = null)
{
$context = $this->ensureContext($context);
$targetId = $this->getTargetId();
if ($targetId === null) {
return null;
}
return $this->getSession()->getObject($targetId, $context);
} | Gets the target object using the given OperationContext.
@param OperationContextInterface|null $context
@return CmisObjectInterface If the target object ID is invalid, <code>null</code> will be returned. | entailment |
public function getSourceId()
{
$sourceId = $this->getPropertyValue(PropertyIds::SOURCE_ID);
if (empty($sourceId)) {
return null;
}
return $this->getSession()->createObjectId($sourceId);
} | Returns the source ID of this CMIS relationship (CMIS property cmis:sourceId).
@return ObjectIdInterface|null the source ID or <code>null</code> if the property hasn't been requested,
hasn't been provided by the repository, or the property value isn't set | entailment |
public function getTargetId()
{
$targetId = $this->getPropertyValue(PropertyIds::TARGET_ID);
if (empty($targetId)) {
return null;
}
return $this->getSession()->createObjectId($targetId);
} | Returns the target ID of this CMIS relationship (CMIS property cmis:targetId).
@return ObjectIdInterface the target ID or <code>null</code> if the property hasn't been requested,
hasn't been provided by the repository, or the property value isn't set | entailment |
public function all($priceRuleId, array $params = array())
{
$endpoint = '/admin/price_rules/'.$priceRuleId.'/discount_codes.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createCollection(DiscountCode::class, $response['discount_codes']);
} | Receive a list of all discounts
@link https://help.shopify.com/api/reference/discount#index
@param integer $priceRuleId
@param array $params
@return DiscountCode[] | entailment |
public function get($priceRuleId, $discountCodeId)
{
$endpoint = '/admin/price_rules/'.$priceRuleId.'/discount_codes/'.$discountCodeId.'.json';
$response = $this->request($endpoint);
return $this->createObject(DiscountCode::class, $response['discount_code']);
} | Receive a single discount
@link https://help.shopify.com/api/reference/discount#show
@param integer $priceRuleId
@param integer $discountCodeId
@return DiscountCode | entailment |
public function create($priceRuleId, DiscountCode &$discountCode)
{
$data = $discountCode->exportData();
$endpoint = '/admin/price_rules/'.$priceRuleId.'/discount_codes.json';
$response = $this->request($endpoint, 'POST', array(
'discount_code' => $data
));
$discountCode->setData($response['discount_code']);
} | Create a new discount
@link https://help.shopify.com/api/reference/discount#create
@param integer $priceRuleId
@param DiscountCode $discountCode
@return void | entailment |
public function delete($priceRuleId, DiscountCode $discountCode)
{
$endpoint = '/admin/price_rules/'.$priceRuleId.'/discount_codes/'.$discountCode->id.'.json';
$this->request($endpoint, 'DELETE');
return;
} | Delete a discount
@link https://help.shopify.com/api/reference/discount#destroy
@param integer $priceRuleId
@param DiscountCode $discountCode
@return void | entailment |
public function update($priceRuleId, DiscountCode &$discountCode)
{
$data = $discountCode->exportData();
$endpoint = '/admin/price_rules/'.$priceRuleId.'/discount_codes/'.$discountCode->id.'.json';
$response = $this->request($endpoint, 'PUT', array(
'discount_code' => $data
));
$discountCode->setData($response['discount_code']);
} | Update a Discount Code
@param integer $priceRuleId
@param DiscountCode $discountCode
@return void | entailment |
function call()
{
$arguments = func_get_args();
$id = $this->_makeId($arguments);
$data = $this->get($id, $this->_defaultGroup);
if ($data !== false) {
if ($this->_debugCacheLiteFunction) {
echo "Cache hit !\n";
}
$array = unserialize($data);
$output = $array['output'];
$result = $array['result'];
} else {
if ($this->_debugCacheLiteFunction) {
echo "Cache missed !\n";
}
ob_start();
ob_implicit_flush(false);
$target = array_shift($arguments);
if (is_array($target)) {
// in this case, $target is for example array($obj, 'method')
$object = $target[0];
$method = $target[1];
$result = call_user_func_array(array(&$object, $method), $arguments);
} else {
if (strstr($target, '::')) { // classname::staticMethod
list($class, $method) = explode('::', $target);
$result = call_user_func_array(array($class, $method), $arguments);
} else if (strstr($target, '->')) { // object->method
// use a stupid name ($objet_123456789 because) of problems where the object
// name is the same as this var name
list($object_123456789, $method) = explode('->', $target);
global $$object_123456789;
$result = call_user_func_array(array($$object_123456789, $method), $arguments);
} else { // function
$result = call_user_func_array($target, $arguments);
}
}
$output = ob_get_contents();
ob_end_clean();
if ($this->_dontCacheWhenTheResultIsFalse) {
if ((is_bool($result)) && (!($result))) {
echo($output);
return $result;
}
}
if ($this->_dontCacheWhenTheResultIsNull) {
if (is_null($result)) {
echo($output);
return $result;
}
}
if ($this->_dontCacheWhenTheOutputContainsNOCACHE) {
if (strpos($output, 'NOCACHE') > -1) {
return $result;
}
}
$array['output'] = $output;
$array['result'] = $result;
$this->save(serialize($array), $id, $this->_defaultGroup);
}
echo($output);
return $result;
} | Calls a cacheable function or method (or not if there is already a cache for it)
Arguments of this method are read with func_get_args. So it doesn't appear
in the function definition. Synopsis :
call('functionName', $arg1, $arg2, ...)
(arg1, arg2... are arguments of 'functionName')
@return mixed result of the function/method
@access public | entailment |
function drop()
{
$id = $this->_makeId(func_get_args());
return $this->remove($id, $this->_defaultGroup);
} | Drop a cache file
Arguments of this method are read with func_get_args. So it doesn't appear
in the function definition. Synopsis :
remove('functionName', $arg1, $arg2, ...)
(arg1, arg2... are arguments of 'functionName')
@return boolean true if no problem
@access public | entailment |
function _makeId($arguments)
{
$id = serialize($arguments); // Generate a cache id
if (!$this->_fileNameProtection) {
$id = md5($id);
// if fileNameProtection is set to false, then the id has to be hashed
// because it's a very bad file name in most cases
}
return $id;
} | Make an id for the cache
@var array result of func_get_args for the call() or the remove() method
@return string id
@access private | entailment |
function setOption($name, $value)
{
$availableOptions = array('errorHandlingAPIBreak', 'hashedDirectoryUmask', 'hashedDirectoryLevel', 'automaticCleaningFactor', 'automaticSerialization', 'fileNameProtection', 'memoryCaching', 'onlyMemoryCaching', 'memoryCachingLimit', 'cacheDir', 'caching', 'lifeTime', 'fileLocking', 'writeControl', 'readControl', 'readControlType', 'pearErrorMode', 'hashedDirectoryGroup', 'cacheFileMode', 'cacheFileGroup');
if (in_array($name, $availableOptions)) {
$property = '_'.$name;
$this->$property = $value;
}
} | Generic way to set a Cache_Lite option
see Cache_Lite constructor for available options
@var string $name name of the option
@var mixed $value value of the option
@access public | entailment |
function get($id, $group = 'default', $doNotTestCacheValidity = false)
{
$this->_id = $id;
$this->_group = $group;
$data = false;
if ($this->_caching) {
$this->_setRefreshTime();
$this->_setFileName($id, $group);
clearstatcache();
if ($this->_memoryCaching) {
if (isset($this->_memoryCachingArray[$this->_file])) {
if ($this->_automaticSerialization) {
return unserialize($this->_memoryCachingArray[$this->_file]);
}
return $this->_memoryCachingArray[$this->_file];
}
if ($this->_onlyMemoryCaching) {
return false;
}
}
if (($doNotTestCacheValidity) || (is_null($this->_refreshTime))) {
if (file_exists($this->_file)) {
$data = $this->_read();
}
} else {
if ((file_exists($this->_file)) && (@filemtime($this->_file) > $this->_refreshTime)) {
$data = $this->_read();
}
}
if (($data) and ($this->_memoryCaching)) {
$this->_memoryCacheAdd($data);
}
if (($this->_automaticSerialization) and (is_string($data))) {
$data = unserialize($data);
}
return $data;
}
return false;
} | Test if a cache is available and (if yes) return it
@param string $id cache id
@param string $group name of the cache group
@param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
@return string data of the cache (else : false)
@access public | entailment |
function save($data, $id = NULL, $group = 'default')
{
if ($this->_caching) {
if ($this->_automaticSerialization) {
$data = serialize($data);
}
if (isset($id)) {
$this->_setFileName($id, $group);
}
if ($this->_memoryCaching) {
$this->_memoryCacheAdd($data);
if ($this->_onlyMemoryCaching) {
return true;
}
}
if ($this->_automaticCleaningFactor>0 && ($this->_automaticCleaningFactor==1 || mt_rand(1, $this->_automaticCleaningFactor)==1)) {
$this->clean(false, 'old');
}
if ($this->_writeControl) {
$res = $this->_writeAndControl($data);
if (is_bool($res)) {
if ($res) {
return true;
}
// if $res if false, we need to invalidate the cache
@touch($this->_file, time() - 2*abs($this->_lifeTime));
return false;
}
} else {
$res = $this->_write($data);
}
if (is_object($res)) {
// $res is a PEAR_Error object
if (!($this->_errorHandlingAPIBreak)) {
return false; // we return false (old API)
}
}
return $res;
}
return false;
} | Save some data in a cache file
@param string $data data to put in cache (can be another type than strings if automaticSerialization is on)
@param string $id cache id
@param string $group name of the cache group
@return boolean true if no problem (else : false or a PEAR_Error object)
@access public | entailment |
function remove($id, $group = 'default', $checkbeforeunlink = false)
{
$this->_setFileName($id, $group);
if ($this->_memoryCaching) {
if (isset($this->_memoryCachingArray[$this->_file])) {
unset($this->_memoryCachingArray[$this->_file]);
$this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
}
if ($this->_onlyMemoryCaching) {
return true;
}
}
if ( $checkbeforeunlink ) {
if (!file_exists($this->_file)) return true;
}
return $this->_unlink($this->_file);
} | Remove a cache file
@param string $id cache id
@param string $group name of the cache group
@param boolean $checkbeforeunlink check if file exists before removing it
@return boolean true if no problem
@access public | entailment |
function clean($group = false, $mode = 'ingroup')
{
return $this->_cleanDir($this->_cacheDir, $group, $mode);
} | Clean the cache
if no group is specified all cache files will be destroyed
else only cache files of the specified group will be destroyed
@param string $group name of the cache group
@param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
'callback_myFunction'
@return boolean true if no problem
@access public | entailment |
function saveMemoryCachingState($id, $group = 'default')
{
if ($this->_caching) {
$array = array(
'counter' => $this->_memoryCachingCounter,
'array' => $this->_memoryCachingArray
);
$data = serialize($array);
$this->save($data, $id, $group);
}
} | Save the state of the caching memory array into a cache file cache
@param string $id cache id
@param string $group name of the cache group
@access public | entailment |
function getMemoryCachingState($id, $group = 'default', $doNotTestCacheValidity = false)
{
if ($this->_caching) {
if ($data = $this->get($id, $group, $doNotTestCacheValidity)) {
$array = unserialize($data);
$this->_memoryCachingCounter = $array['counter'];
$this->_memoryCachingArray = $array['array'];
}
}
} | Load the state of the caching memory array from a given cache file cache
@param string $id cache id
@param string $group name of the cache group
@param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
@access public | entailment |
function _setRefreshTime()
{
if (is_null($this->_lifeTime)) {
$this->_refreshTime = null;
} else {
$this->_refreshTime = time() - $this->_lifeTime;
}
} | Compute & set the refresh time
@access private | entailment |
function _cleanDir($dir, $group = false, $mode = 'ingroup')
{
if ($this->_fileNameProtection) {
$motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
} else {
$motif = ($group) ? 'cache_'.$group.'_' : 'cache_';
}
if ($this->_memoryCaching) {
foreach($this->_memoryCachingArray as $key => $v) {
if (strpos($key, $motif) !== false) {
unset($this->_memoryCachingArray[$key]);
$this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
}
}
if ($this->_onlyMemoryCaching) {
return true;
}
}
if (!($dh = opendir($dir))) {
return $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
}
$result = true;
while (($file = readdir($dh)) !== false) {
if (($file != '.') && ($file != '..')) {
if (substr($file, 0, 6)=='cache_') {
$file2 = $dir . $file;
if (is_file($file2)) {
switch (substr($mode, 0, 9)) {
case 'old':
// files older than lifeTime get deleted from cache
if (!is_null($this->_lifeTime)) {
if ((time() - @filemtime($file2)) > $this->_lifeTime) {
$result = ($result and ($this->_unlink($file2)));
}
}
break;
case 'notingrou':
if (strpos($file2, $motif) === false) {
$result = ($result and ($this->_unlink($file2)));
}
break;
case 'callback_':
$func = substr($mode, 9, strlen($mode) - 9);
if ($func($file2, $group)) {
$result = ($result and ($this->_unlink($file2)));
}
break;
case 'ingroup':
default:
if (strpos($file2, $motif) !== false) {
$result = ($result and ($this->_unlink($file2)));
}
break;
}
}
if ((is_dir($file2)) and ($this->_hashedDirectoryLevel>0)) {
$result = ($result and ($this->_cleanDir($file2 . '/', $group, $mode)));
}
}
}
}
return $result;
} | Recursive function for cleaning cache file in the given directory
@param string $dir directory complete path (with a trailing slash)
@param string $group name of the cache group
@param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
'callback_myFunction'
@return boolean true if no problem
@access private | entailment |
function _memoryCacheAdd($data)
{
$this->_touchCacheFile();
$this->_memoryCachingArray[$this->_file] = $data;
if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
$key = key($this->_memoryCachingArray);
next($this->_memoryCachingArray);
unset($this->_memoryCachingArray[$key]);
} else {
$this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;
}
} | Add some date in the memory caching array
@param string $data data to cache
@access private | entailment |
function _setFileName($id, $group)
{
if ($this->_fileNameProtection) {
$suffix = 'cache_'.md5($group).'_'.md5($id);
} else {
$suffix = 'cache_'.$group.'_'.$id;
}
$root = $this->_cacheDir;
if ($this->_hashedDirectoryLevel>0) {
$hash = md5($suffix);
for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
$root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
}
}
$this->_fileName = $suffix;
$this->_file = $root.$suffix;
} | Make a file name (with path)
@param string $id cache id
@param string $group name of the group
@access private | entailment |
function _read()
{
$fp = @fopen($this->_file, "rb");
if ($fp) {
if ($this->_fileLocking) @flock($fp, LOCK_SH);
clearstatcache();
$length = @filesize($this->_file);
$mqr = get_magic_quotes_runtime();
if ($mqr) {
set_magic_quotes_runtime(0);
}
if ($this->_readControl) {
$hashControl = @fread($fp, 32);
$length = $length - 32;
}
if ($length) {
$data = '';
// See https://bugs.php.net/bug.php?id=30936
// The 8192 magic number is the chunk size used internally by PHP.
while(!feof($fp)) $data .= fread($fp, 8192);
} else {
$data = '';
}
if ($mqr) {
set_magic_quotes_runtime($mqr);
}
if ($this->_fileLocking) @flock($fp, LOCK_UN);
@fclose($fp);
if ($this->_readControl) {
$hashData = $this->_hash($data, $this->_readControlType);
if ($hashData != $hashControl) {
if (!(is_null($this->_lifeTime))) {
@touch($this->_file, time() - 2*abs($this->_lifeTime));
} else {
@unlink($this->_file);
}
return false;
}
}
return $data;
}
return $this->raiseError('Cache_Lite : Unable to read cache !', -2);
} | Read the cache file and return the content
@return string content of the cache file (else : false or a PEAR_Error object)
@access private | entailment |
function _write($data)
{
if ($this->_hashedDirectoryLevel > 0) {
$hash = md5($this->_fileName);
$root = $this->_cacheDir;
for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
$root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
if (!(@is_dir($root))) {
if (@mkdir($root))
{
@chmod($root, $this->_hashedDirectoryUmask);
if (! is_null($this->_hashedDirectoryGroup))
@chgrp($root, $this->_hashedDirectoryGroup);
}
}
}
}
// if both _cacheFileMode and _cacheFileGroup is null, then we don't need to call
// file_exists (see below: if ($is_newfile) ...)
$is_newfile = (! is_null($this->_cacheFileMode) || !is_null($this->_cacheFileGroup))
&& ! @file_exists($this->_file);
$fp = @fopen($this->_file, "wb");
if ($fp) {
if ($this->_fileLocking) @flock($fp, LOCK_EX);
if ($is_newfile)
{
if (! is_null($this->_cacheFileMode))
@chmod($this->_file, $this->_cacheFileMode);
if (! is_null($this->_cacheFileGroup))
@chgrp($this->_file, $this->_cacheFileGroup);
}
if ($this->_readControl) {
@fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
}
$mqr = get_magic_quotes_runtime();
if ($mqr) {
set_magic_quotes_runtime(0);
}
@fwrite($fp, $data);
if ($mqr) {
set_magic_quotes_runtime($mqr);
}
if ($this->_fileLocking) @flock($fp, LOCK_UN);
@fclose($fp);
return true;
}
return $this->raiseError('Cache_Lite : Unable to write cache file : '.$this->_file, -1);
} | Write the given data in the cache file
@param string $data data to put in cache
@return boolean true if ok (a PEAR_Error object else)
@access private | entailment |
function _writeAndControl($data)
{
$result = $this->_write($data);
if (is_object($result)) {
return $result; # We return the PEAR_Error object
}
$dataRead = $this->_read();
if (is_object($dataRead)) {
return $dataRead; # We return the PEAR_Error object
}
if ((is_bool($dataRead)) && (!$dataRead)) {
return false;
}
return ($dataRead==$data);
} | Write the given data in the cache file and control it just after to avoir corrupted cache entries
@param string $data data to put in cache
@return boolean true if the test is ok (else : false or a PEAR_Error object)
@access private | entailment |
function _hash($data, $controlType)
{
switch ($controlType) {
case 'md5':
return md5($data);
case 'crc32':
return sprintf('% 32d', crc32($data));
case 'strlen':
return sprintf('% 32d', strlen($data));
default:
return $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);
}
} | Make a control key with the string containing datas
@param string $data data
@param string $controlType type of control 'md5', 'crc32' or 'strlen'
@return string control key
@access private | entailment |
public function all(array $params = array())
{
$endpoint = '/admin/redirects.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createCollection(Redirect::class, $response['redirects']);
} | Receive a list of all redirects
@link https://help.shopify.com/api/reference/redirect#index
@param ListOptions $options
@return Redirect[] | entailment |
public function get($redirectId, array $params = array())
{
$endpoint = '/admin/redirects/'.$redirectId.'.json';
$response = $this->request($endpoint, 'GET', $params);
return $this->createObject(Redirect::class, $response['redirect']);
} | Receive a singel redirect
@link https://help.shopify.com/api/reference/redirect#show
@param integer $redirectId
@param array $params
@return Redirect | entailment |
public function create(Redirect &$redirect)
{
$endpoint = '/admin/redirects.json';
$data = $redirect->exportData();
$response = $this->request(
$endpoint, "POST", array(
'redirect' => $data
)
);
$redirect->setData($response['redirect']);
} | Create a new redirect
@link https://help.shopify.com/api/reference/redirect#create
@param Redirect $redirect
@return void | entailment |
public function update(Redirect &$redirect)
{
$endpoint = '/admin/redirects/'.$redirect->id.'.json';
$data = $redirect->exportData();
$response = $this->request(
$endpoint, "POST", array(
'redirect' => $data
)
);
$redirect->setData($response['redirect']);
} | Modify an existing redirect
@link https://help.shopify.com/api/reference/redirect#update
@param Redirect $redirect
@return void | entailment |
public function delete(Redirect $redirect)
{
$endpoint = '/admin/redirect/'.$redirect->id.'.json';
$response = $this->request($endpoint, 'DELETE');
return;
} | Remove a redirect
@link https://help.shopify.com/api/reference/redirect#destroy
@param Redirect $redirect
@return void | entailment |
public function getObjectRelationships(
$repositoryId,
$objectId,
$includeSubRelationshipTypes = false,
RelationshipDirection $relationshipDirection = null,
$typeId = null,
$filter = null,
$includeAllowableActions = false,
$maxItems = null,
$skipCount = 0,
ExtensionDataInterface $extension = null
) {
$url = $this->getObjectUrl($repositoryId, $objectId, Constants::SELECTOR_RELATIONSHIPS);
$query = $url->getQuery();
if ($relationshipDirection === null) {
$relationshipDirection = RelationshipDirection::cast(RelationshipDirection::SOURCE);
}
$query->modify(
[
Constants::PARAM_TYPE_ID => $typeId,
Constants::PARAM_RELATIONSHIP_DIRECTION => (string) $relationshipDirection,
Constants::PARAM_SUB_RELATIONSHIP_TYPES => $includeSubRelationshipTypes ? 'true' : 'false',
Constants::PARAM_ALLOWABLE_ACTIONS => $includeAllowableActions ? 'true' : 'false',
Constants::PARAM_SUCCINCT => $this->getSuccinct() ? 'true' : 'false',
Constants::PARAM_SKIP_COUNT => $skipCount,
Constants::PARAM_DATETIME_FORMAT => (string) $this->getDateTimeFormat()
]
);
if ($filter !== null) {
$query->modify([Constants::PARAM_FILTER => $filter]);
}
if ($maxItems !== null) {
$query->modify([Constants::PARAM_MAX_ITEMS => $maxItems]);
}
$responseData = (array) $this->readJson($url);
return $this->getJsonConverter()->convertObjectList($responseData);
} | Gets all or a subset of relationships associated with an independent object.
@param string $repositoryId The identifier for the repository.
@param string $objectId The identifier of the object.
@param boolean $includeSubRelationshipTypes If <code>true</code>, then the repository MUST return all
relationships whose object-types are descendant-types of the object-type specified by the typeId parameter
value as well as relationships of the specified type.
If <code>false</code>, then the repository MUST only return relationships whose object-types
is equivalent to the object-type specified by the typeId parameter value.
If the typeId input is not specified, then this input MUST be ignored.
@param RelationshipDirection|null $relationshipDirection Specifying whether the repository MUST return
relationships where the specified object is the source of the relationship, the target of the relationship,
or both. (default is source)
@param string|null $typeId If specified, then the repository MUST return only relationships whose object-type is
of the type specified. See also parameter includeSubRelationshipTypes.
If not specified, then the repository MUST return relationship objects of all types.
@param string|null $filter a comma-separated list of query names that defines which properties
must be returned by the repository (default is repository specific)
@param boolean $includeAllowableActions Whether or not to include in response, the list of allowable actions
@param integer|null $maxItems the maximum number of items to return in a response
(default is repository specific)
@param integer $skipCount number of potential results that the repository MUST skip/page over before
returning any results (default is 0)
@param ExtensionDataInterface|null $extension
@return ObjectListInterface | entailment |
public function convertObject(ObjectDataInterface $objectData, OperationContextInterface $context)
{
$type = $this->getTypeFromObjectData($objectData);
if ($type === null) {
throw new CmisRuntimeException('Could not get type from object data.');
}
$baseTypeId = $objectData->getBaseTypeId();
if ($baseTypeId->equals(BaseTypeId::CMIS_DOCUMENT)) {
return new Document($this->session, $type, $context, $objectData);
} elseif ($baseTypeId->equals(BaseTypeId::CMIS_FOLDER)) {
return new Folder($this->session, $type, $context, $objectData);
} elseif ($baseTypeId->equals(BaseTypeId::CMIS_POLICY)) {
return new Policy($this->session, $type, $context, $objectData);
} elseif ($baseTypeId->equals(BaseTypeId::CMIS_RELATIONSHIP)) {
return new Relationship($this->session, $type, $context, $objectData);
} elseif ($baseTypeId->equals(BaseTypeId::CMIS_ITEM)) {
return new Item($this->session, $type, $context, $objectData);
} elseif ($baseTypeId->equals(BaseTypeId::CMIS_SECONDARY)) {
throw new CmisRuntimeException('Secondary type is used as object type: ' . $baseTypeId);
} else {
throw new CmisRuntimeException('Unsupported base type: ' . $baseTypeId);
}
} | Convert given ObjectData to a high level API object
@param ObjectDataInterface $objectData
@param OperationContextInterface $context
@return CmisObjectInterface
@throws CmisRuntimeException | entailment |
public function convertPolicies(array $policies)
{
$result = [];
foreach ($policies as $policy) {
if ($policy->getId() !== null) {
$result[] = $policy->getId();
}
}
return $result;
} | Converts a list of Policy objects into a list of there string representations
@param PolicyInterface[] $policies
@return string[] | entailment |
public function convertPropertiesDataToPropertyList(
ObjectTypeInterface $objectType,
array $secondaryTypes,
PropertiesInterface $properties
) {
if (count($objectType->getPropertyDefinitions()) === 0) {
throw new CmisInvalidArgumentException('Object type has no property definitions!');
}
if (count($properties->getProperties()) === 0) {
throw new CmisInvalidArgumentException('Properties must be set');
}
// Iterate trough properties and convert them to Property objects
$result = [];
foreach ($properties->getProperties() as $propertyKey => $propertyData) {
// find property definition
$apiProperty = $this->convertProperty($objectType, $secondaryTypes, $propertyData);
$result[$propertyKey] = $apiProperty;
}
return $result;
} | Convert Properties in Properties instance to a list of PropertyInterface objects
@param ObjectTypeInterface $objectType
@param SecondaryTypeInterface[] $secondaryTypes
@param PropertiesInterface $properties
@return PropertyInterface[]
@throws CmisInvalidArgumentException | entailment |
protected function convertProperty(
ObjectTypeInterface $objectType,
array $secondaryTypes,
PropertyDataInterface $propertyData
) {
$definition = $objectType->getPropertyDefinition($propertyData->getId());
// search secondary types
if ($definition === null && !empty($secondaryTypes)) {
foreach ($secondaryTypes as $secondaryType) {
$propertyDefinitions = $secondaryType->getPropertyDefinitions();
if (!empty($propertyDefinitions)) {
$definition = $secondaryType->getPropertyDefinition($propertyData->getId());
if ($definition !== null) {
break;
}
}
}
}
// the type might have changed -> reload type definitions
if ($definition === null) {
$reloadedObjectType = $this->session->getTypeDefinition($objectType->getId(), false);
$definition = $reloadedObjectType->getPropertyDefinition($propertyData->getId());
if ($definition === null && !empty($secondaryTypes)) {
foreach ($secondaryTypes as $secondaryType) {
$reloadedSecondaryType = $this->session->getTypeDefinition($secondaryType->getId(), false);
$propertyDefinitions = $reloadedSecondaryType->getPropertyDefinitions();
if (!empty($propertyDefinitions)) {
$definition = $reloadedSecondaryType->getPropertyDefinition($propertyData->getId());
if ($definition !== null) {
break;
}
}
}
}
}
if ($definition === null) {
// property without definition
throw new CmisRuntimeException(sprintf('Property "%s" doesn\'t exist!', $propertyData->getId()));
}
return $this->createProperty($definition, $propertyData->getValues());
} | Convert PropertyData into a property API object
@param ObjectTypeInterface $objectType
@param SecondaryTypeInterface[] $secondaryTypes
@param PropertyDataInterface $propertyData
@return PropertyInterface
@throws CmisRuntimeException | entailment |
public function convertProperties(
array $properties,
ObjectTypeInterface $type = null,
array $secondaryTypes = [],
array $updatabilityFilter = []
) {
if (empty($properties)) {
return null;
}
if ($type === null) {
$type = $this->getTypeDefinition(
isset($properties[PropertyIds::OBJECT_TYPE_ID]) ? $properties[PropertyIds::OBJECT_TYPE_ID] : null
);
}
// get secondary types
$allSecondaryTypes = [];
$secondaryTypeIds = $this->getValueFromArray(PropertyIds::SECONDARY_OBJECT_TYPE_IDS, $properties);
if (is_array($secondaryTypeIds)) {
foreach ($secondaryTypeIds as $secondaryTypeId) {
$secondaryType = $this->getTypeDefinition((string) $secondaryTypeId);
if (!$secondaryType instanceof SecondaryType) {
throw new CmisInvalidArgumentException(
'Secondary types property contains a type that is not a secondary type: ' . $secondaryTypeId,
1425479398
);
}
$allSecondaryTypes[] = $secondaryType;
}
} elseif ($secondaryTypeIds !== null) {
throw new CmisInvalidArgumentException(
sprintf(
'The property "%s" must be of type array or undefined but is of type "%s"',
PropertyIds::SECONDARY_OBJECT_TYPE_IDS,
gettype($secondaryTypeIds)
),
1425473414
);
}
if (!empty($secondaryTypes) && empty($allSecondaryTypes)) {
$allSecondaryTypes = $secondaryTypes;
}
$propertyList = [];
foreach ($properties as $propertyId => $propertyValue) {
$value = $propertyValue;
if ($value instanceof PropertyInterface) {
if ($value->getId() !== $propertyId) {
throw new CmisInvalidArgumentException(
sprintf('Property id mismatch: "%s" != "%s"', $propertyId, $value->getId())
);
}
$value = ($value->isMultiValued()) ? $value->getValues() : $value->getFirstValue();
}
$definition = $type->getPropertyDefinition($propertyId);
if ($definition === null && !empty($allSecondaryTypes)) {
foreach ($allSecondaryTypes as $secondaryType) {
$definition = $secondaryType->getPropertyDefinition($propertyId);
if ($definition !== null) {
break;
}
}
}
if ($definition === null) {
throw new CmisInvalidArgumentException(
sprintf('Property "%s" is not valid for this type or one of the secondary types!', $propertyId)
);
}
// check updatability
if (!empty($updatabilityFilter) && !in_array($definition->getUpdatability(), $updatabilityFilter)) {
continue;
}
if (is_array($value)) {
if (!$definition->getCardinality()->equals(Cardinality::MULTI)) {
throw new CmisInvalidArgumentException(
sprintf('Property "%s" is not a multi value property but multiple values given!', $propertyId)
);
}
$values = $value;
} else {
if (!$definition->getCardinality()->equals(Cardinality::SINGLE)) {
throw new CmisInvalidArgumentException(
sprintf('Property "%s" is not a single value property but single value given!', $propertyId)
);
}
$values = [];
$values[] = $value;
}
$propertyList[] = $this->getBindingsObjectFactory()->createPropertyData($definition, $values);
}
return $this->getBindingsObjectFactory()->createPropertiesData($propertyList);
} | Convert properties to their property data objects and put them into a Properties object
@param mixed[] $properties
@param ObjectTypeInterface|null $type
@param SecondaryTypeInterface[] $secondaryTypes
@param Updatability[] $updatabilityFilter
@return PropertiesInterface
@throws CmisInvalidArgumentException | entailment |
private function getTypeDefinition($objectTypeId)
{
if (empty($objectTypeId) || !is_string($objectTypeId)) {
throw new CmisInvalidArgumentException(
'Type property must be set and must be of type string but is empty or not a string.'
);
}
return $this->session->getTypeDefinition($objectTypeId);
} | Get a type definition for the given object type id. If an empty id is given throw an exception.
@param string $objectTypeId
@return ObjectTypeInterface
@throws CmisInvalidArgumentException | entailment |
private function getValueFromArray($needle, $haystack)
{
if (!is_array($haystack) || !isset($haystack[$needle])) {
return null;
}
return $haystack[$needle];
} | Get a value from an array. Return <code>null</code> if the key does not exist in the array.
@param integer|string $needle
@param mixed $haystack
@return mixed | entailment |
public function convertRendition($objectId, RenditionDataInterface $renditionData)
{
$rendition = new Rendition($this->session, $objectId);
$rendition->populate($renditionData);
return $rendition;
} | Converts RenditionData to Rendition
@param string $objectId
@param RenditionDataInterface $renditionData
@return RenditionInterface | entailment |
public function convertTypeDefinition(TypeDefinitionInterface $typeDefinition)
{
if ($typeDefinition instanceof DocumentTypeDefinitionInterface) {
return new DocumentType($this->session, $typeDefinition);
} elseif ($typeDefinition instanceof FolderTypeDefinitionInterface) {
return new FolderType($this->session, $typeDefinition);
} elseif ($typeDefinition instanceof RelationshipTypeDefinitionInterface) {
return new RelationshipType($this->session, $typeDefinition);
} elseif ($typeDefinition instanceof PolicyTypeDefinitionInterface) {
return new PolicyType($this->session, $typeDefinition);
} elseif ($typeDefinition instanceof ItemTypeDefinitionInterface) {
return new ItemType($this->session, $typeDefinition);
} elseif ($typeDefinition instanceof SecondaryTypeDefinitionInterface) {
return new SecondaryType($this->session, $typeDefinition);
} else {
throw new CmisRuntimeException(
sprintf('Unknown base type! Received "%s"', get_class($typeDefinition)),
1422028427
);
}
} | Convert a type definition to a type
@param TypeDefinitionInterface $typeDefinition
@return ObjectTypeInterface
@throws CmisRuntimeException | entailment |
public function getTypeFromObjectData(ObjectDataInterface $objectData)
{
if ($objectData->getProperties() === null || count($objectData->getProperties()->getProperties()) === 0) {
return null;
}
$typeProperty = $objectData->getProperties()->getProperties()[PropertyIds::OBJECT_TYPE_ID];
if (!$typeProperty instanceof PropertyId) {
return null;
}
return $this->session->getTypeDefinition($typeProperty->getFirstValue());
} | Try to determined what object type the given objectData belongs to and return that type.
@param ObjectDataInterface $objectData
@return ObjectTypeInterface|null The object type or <code>null</code> if type could not be determined | entailment |
public function createTypeDefinition(
$id,
$localName,
$baseTypeIdString,
$parentId,
$creatable,
$fileable,
$queryable,
$controllablePolicy,
$controllableACL,
$fulltextIndexed,
$includedInSupertypeQuery,
$localNamespace = '',
$queryName = '',
$displayName = '',
$description = '',
TypeMutabilityInterface $typeMutability = null
) {
$typeDefinition = $this->getBindingsObjectFactory()->getTypeDefinitionByBaseTypeId($baseTypeIdString, $id);
$typeDefinition->setLocalName($localName);
$typeDefinition->setParentTypeId($parentId);
$typeDefinition->setIsCreatable($creatable);
$typeDefinition->setIsFileable($fileable);
$typeDefinition->setIsQueryable($queryable);
$typeDefinition->setisControllablePolicy($controllablePolicy);
$typeDefinition->setIsControllableAcl($controllableACL);
$typeDefinition->setIsFulltextIndexed($fulltextIndexed);
$typeDefinition->setIsIncludedInSupertypeQuery($includedInSupertypeQuery);
$typeDefinition->setLocalNamespace($localNamespace);
$typeDefinition->setQueryName($queryName);
$typeDefinition->setDisplayName($displayName);
$typeDefinition->setDescription($description);
if ($typeMutability !== null) {
$typeDefinition->setTypeMutability($typeMutability);
}
return $typeDefinition;
} | Create a type definition with all required properties.
@param string $id This opaque attribute identifies this object-type in the repository.
@param string $localName This attribute represents the underlying repository’s name for the object-type.
This field is opaque and has no uniqueness constraint imposed by this specification.
@param string $baseTypeIdString A value that indicates whether the base type for this object-type is the
document, folder, relationship, policy, item, or secondary base type.
@param string $parentId The id of the object-type’s immediate parent type. It MUST be "not set" for a base
type. Depending on the binding this means it might not exist on the base type object-type definition.
@param boolean $creatable Indicates whether new objects of this type MAY be created. If the value of this
attribute is FALSE, the repository MAY contain objects of this type already, but MUST NOT allow new objects
of this type to be created.
@param boolean $fileable Indicates whether or not objects of this type are file-able.
@param boolean $queryable Indicates whether or not this object-type can appear in the FROM clause of a query
statement. A non-queryable object-type is not visible through the relational view that is used for query,
and CAN NOT appear in the FROM clause of a query statement.
@param boolean $controllablePolicy Indicates whether or not objects of this type are controllable via policies.
Policy objects can only be applied to controllablePolicy objects.
@param boolean $controllableACL This attribute indicates whether or not objects of this type are controllable by
ACL’s. Only objects that are controllableACL can have an ACL.
@param boolean $fulltextIndexed Indicates whether objects of this type are indexed for full-text search for
querying via the CONTAINS() query predicate. If the value of this attribute is TRUE, the full-text index
MUST cover the content and MAY cover the metadata.
@param boolean $includedInSupertypeQuery Indicates whether this type and its subtypes appear in a query of this
type’s ancestor types. For example: if Invoice is a sub-type of cmis:document, if this is TRUE on Invoice
then for a query on cmis:document, instances of Invoice will be returned if they match. If this attribute
is FALSE, no instances of Invoice will be returned even if they match the query.
@param string $localNamespace This attribute allows repositories to represent the internal namespace of
the underlying repository’s name for the object-type.
@param string $queryName Used for query and filter operations on object-types. This is an opaque string with
limitations. See 2.1.2.1.3 Query Names of the CMIS 1.1 standard for details.
@param string $displayName Used for presentation by application.
@param string $description Description of this object-type, such as the nature of content, or its intended use.
Used for presentation by application.
@param TypeMutabilityInterface|null $typeMutability
typeMutability.create - Indicates whether new child types may be created with this type as the parent.
typeMutability.update - Indicates whether clients may make changes to this type per the constraints
defined in this specification.
typeMutability.delete - Indicates whether clients may delete this type if there are no instances of it in
the repository.
@return FolderTypeDefinition|DocumentTypeDefinition|RelationshipTypeDefinition|PolicyTypeDefinition|ItemTypeDefinition|SecondaryTypeDefinition | entailment |
public function getTypeDefinitionByBaseTypeId($baseTypeIdString, $typeId)
{
$baseTypeId = BaseTypeId::cast($baseTypeIdString);
if ($baseTypeId->equals(BaseTypeId::cast(BaseTypeId::CMIS_FOLDER))) {
$baseType = new FolderTypeDefinition($typeId);
} elseif ($baseTypeId->equals(BaseTypeId::cast(BaseTypeId::CMIS_DOCUMENT))) {
$baseType = new DocumentTypeDefinition($typeId);
} elseif ($baseTypeId->equals(BaseTypeId::cast(BaseTypeId::CMIS_RELATIONSHIP))) {
$baseType = new RelationshipTypeDefinition($typeId);
} elseif ($baseTypeId->equals(BaseTypeId::cast(BaseTypeId::CMIS_POLICY))) {
$baseType = new PolicyTypeDefinition($typeId);
} elseif ($baseTypeId->equals(BaseTypeId::cast(BaseTypeId::CMIS_ITEM))) {
$baseType = new ItemTypeDefinition($typeId);
} elseif ($baseTypeId->equals(BaseTypeId::cast(BaseTypeId::CMIS_SECONDARY))) {
$baseType = new SecondaryTypeDefinition($typeId);
} else {
// @codeCoverageIgnoreStart
// this could only happen if a new baseType is added to the enumeration and not implemented here.
throw new CmisInvalidArgumentException(
sprintf('The given type definition "%s" could not be converted.', $baseTypeId)
);
// @codeCoverageIgnoreEnd
}
$baseType->setBaseTypeId($baseTypeId);
return $baseType;
} | Get a type definition object by its base type id
@param string $baseTypeIdString
@param string $typeId
@return FolderTypeDefinition|DocumentTypeDefinition|RelationshipTypeDefinition|PolicyTypeDefinition|ItemTypeDefinition|SecondaryTypeDefinition
@throws CmisInvalidArgumentException Exception is thrown if the base type exists in the BaseTypeId enumeration
but is not implemented here. This could only happen if the base type enumeration is extended which requires
a CMIS specification change. | entailment |
public function createCmisBrowserBinding(array $sessionParameters, Cache $typeDefinitionCache = null)
{
$this->validateCmisBrowserBindingParameters($sessionParameters);
return new CmisBinding(new Session(), $sessionParameters, $typeDefinitionCache);
} | Create a browser binding
@param array $sessionParameters
@param Cache|null $typeDefinitionCache
@return CmisBinding | entailment |
protected function addDefaultSessionParameters(array &$sessionParameters)
{
$sessionParameters[SessionParameter::CACHE_SIZE_REPOSITORIES] = $sessionParameters[SessionParameter::CACHE_SIZE_REPOSITORIES] ?? 10;
$sessionParameters[SessionParameter::CACHE_SIZE_TYPES] = $sessionParameters[SessionParameter::CACHE_SIZE_TYPES] ?? 100;
$sessionParameters[SessionParameter::CACHE_SIZE_LINKS] = $sessionParameters[SessionParameter::CACHE_SIZE_LINKS] ?? 400;
$sessionParameters[SessionParameter::HTTP_INVOKER_CLASS] = $sessionParameters[SessionParameter::HTTP_INVOKER_CLASS] ?? Client::class;
$sessionParameters[SessionParameter::JSON_CONVERTER_CLASS] = $sessionParameters[SessionParameter::JSON_CONVERTER_CLASS] ?? JsonConverter::class;
$sessionParameters[SessionParameter::TYPE_DEFINITION_CACHE_CLASS] = $sessionParameters[SessionParameter::TYPE_DEFINITION_CACHE_CLASS] ?? ArrayCache::class;
} | Sets some parameters to a default value if they are not already set
@param array $sessionParameters | entailment |
protected function check(array $sessionParameters, $parameter)
{
if (empty($sessionParameters[$parameter])) {
throw new CmisInvalidArgumentException(sprintf('Parameter "%s" is missing!', $parameter));
}
return true;
} | Checks if the given parameter is present. If not, throw an
<code>IllegalArgumentException</code>.
@param array $sessionParameters
@param string $parameter
@throws CmisInvalidArgumentException
@return boolean | entailment |
public function all(array $params = array())
{
$response = $this->request('/admin/webhooks.json', 'GET', $params);
return $this->createCollection(Webhook::class, $response['webhooks']);
} | Receive a list of all webhooks
@link https://help.shopify.com/api/reference/webhook#index
@param array $params
@return Webhook[] | entailment |
public function get($webhookId, array $fields = array())
{
$params = array();
if (!empty($fields)) {
$params['fields'] = implode(',', $fields);
}
$response = $this->request('/admin/webhooks/'.$webhookId.'.json', 'GET', $params);
return $this->createObject(Webhook::class, $response['webhook']);
} | Receive a single webhook
@link https://help.shopify.com/api/reference/webhook#show
@param integer $webhookId
@param array $fields
@return Webhook | entailment |
public function create(Webhook &$webhook)
{
$data = $webhook->exportData();
$response = $this->request(
'/admin/webhooks.json', 'POST', array(
'webhook' => $data
)
);
$webhook->setData($response['webhook']);
} | Create a new webhook
@link https://help.shopify.com/api/reference/webhook#create
@param Webhook $webhook
@return void | entailment |
public function update(Webhook $webhook)
{
$data = $webhook->exportData();
$response = $this->request(
'/admin/webhooks/'.$webhook->id.'.json', 'PUT', array(
'webhook' => $data
)
);
$webhook->setData($response['webhook']);
} | Modify an existing webhook
@link https://help.shopify.com/api/reference/webhook#update
@param Webhook $webhook
@return void | entailment |
public function createDocument(
array $properties,
StreamInterface $contentStream,
VersioningState $versioningState,
array $policies = [],
array $addAces = [],
array $removeAces = [],
OperationContextInterface $context = null
) {
$newObjectId = $this->getSession()->createDocument(
$properties,
$this,
$contentStream,
$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 new document in this folder.
@param array $properties The property values that MUST be applied to the object. The array key is the property
name the value is the property value.
@param StreamInterface $contentStream
@param VersioningState $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|null the new folder 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 |
public function createDocumentFromSource(
ObjectIdInterface $source,
array $properties,
VersioningState $versioningState,
array $policies = [],
array $addAces = [],
array $removeAces = [],
OperationContextInterface $context = null
) {
$newObjectId = $this->getSession()->createDocumentFromSource(
$source,
$properties,
$this,
$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 new document from a source document in this folder.
@param ObjectIdInterface $source The ID of the source document.
@param array $properties The property values that MUST be applied to the object. The array key is the property
name the value is the property value.
@param VersioningState $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|null the new folder 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 |
public function createFolder(
array $properties,
array $policies = [],
array $addAces = [],
array $removeAces = [],
OperationContextInterface $context = null
) {
$newObjectId = $this->getSession()->createFolder($properties, $this, $policies, $addAces, $removeAces);
$folder = $this->getNewlyCreatedObject($newObjectId, $context);
if ($folder === null) {
return null;
} elseif (!$folder instanceof FolderInterface) {
throw new CmisRuntimeException('Newly created object is not a folder! New id: ' . $folder->getId());
}
return $folder;
} | Creates a new subfolder in this folder.
@param array $properties The property values that MUST be applied to the newly-created item object.
@param PolicyInterface[] $policies A list of policy ids that MUST be applied to the newly-created folder object.
@param AceInterface[] $addAces A list of ACEs that MUST be added to the newly-created folder 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 folder object,
either using the ACL from folderId if specified, or being ignored if no folderId is specified.
@param OperationContextInterface|null $context
@return FolderInterface|null the new folder 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 folder | entailment |
public function createItem(
array $properties,
array $policies = [],
array $addAces = [],
array $removeAces = [],
OperationContextInterface $context = null
) {
$newObjectId = $this->getSession()->createItem($properties, $this, $policies, $addAces, $removeAces);
$item = $this->getNewlyCreatedObject($newObjectId, $context);
if ($item === null) {
return null;
} elseif (!$item instanceof ItemInterface) {
throw new CmisRuntimeException('Newly created object is not a item! New id: ' . $item->getId());
}
return $item;
} | Creates a new item in this folder.
@param array $properties The property values that MUST be applied to the newly-created item object.
@param PolicyInterface[] $policies A list of policy ids that MUST be applied to the newly-created item object.
@param AceInterface[] $addAces A list of ACEs that MUST be added to the newly-created item 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 item object, either
using the ACL from folderId if specified, or being ignored if no folderId is specified.
@param OperationContextInterface|null $context
@return ItemInterface|null the new item object
@throws CmisRuntimeException Exception is thrown if the created object is not a item | entailment |
public function createPolicy(
array $properties,
array $policies = [],
array $addAces = [],
array $removeAces = [],
OperationContextInterface $context = null
) {
$newObjectId = $this->getSession()->createPolicy($properties, $this, $policies, $addAces, $removeAces);
$policy = $this->getNewlyCreatedObject($newObjectId, $context);
if ($policy === null) {
return null;
} elseif (!$policy instanceof PolicyInterface) {
throw new CmisRuntimeException('Newly created object is not a policy! New id: ' . $policy->getId());
}
return $policy;
} | Creates a new policy in this folder.
@param array $properties The property values that MUST be applied to the newly-created policy object.
@param PolicyInterface[] $policies A list of policy ids that MUST be applied to the newly-created policy object.
@param AceInterface[] $addAces A list of ACEs that MUST be added to the newly-created policy 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 policy object,
either using the ACL from folderId if specified, or being ignored if no folderId is specified.
@param OperationContextInterface|null $context
@return PolicyInterface|null the new policy object
@throws CmisRuntimeException Exception is thrown if the created object is not a policy | entailment |
public function deleteTree($allVersions, UnfileObject $unfile, $continueOnFailure = true)
{
$failed = $this->getBinding()->getObjectService()->deleteTree(
$this->getRepositoryId(),
$this->getId(),
$allVersions,
$unfile,
$continueOnFailure
);
if (count($failed->getIds()) === 0) {
$this->getSession()->removeObjectFromCache($this);
}
return $failed;
} | Deletes this folder and all subfolders.
@param boolean $allVersions If <code>true</code>, then delete all versions of all documents. If
<code>false</code>, delete only the document versions referenced in the tree. The repository MUST ignore the
value of this parameter when this service is invoked on any non-document objects or non-versionable document
objects.
@param UnfileObject $unfile An enumeration specifying how the repository MUST process file-able child- or
descendant-objects.
@param boolean $continueOnFailure If <code>true</code>, then the repository SHOULD continue attempting to
perform this operation even if deletion of a child- or descendant-object in the specified folder cannot be
deleted. If <code>false</code>, then the repository SHOULD abort this method when it fails to
delete a single child object or descendant object.
@return FailedToDeleteDataInterface A list of identifiers of objects in the folder tree that were not deleted. | entailment |
public function getCheckedOutDocs(OperationContextInterface $context = null)
{
$context = $this->ensureContext($context);
$checkedOutDocs = $this->getBinding()->getNavigationService()->getCheckedOutDocs(
$this->getRepositoryId(),
$this->getId(),
$context->getQueryFilterString(),
$context->getOrderBy(),
$context->isIncludeAllowableActions(),
$context->getIncludeRelationships(),
$context->getRenditionFilterString()
);
$result = [];
$objectFactory = $this->getObjectFactory();
foreach ($checkedOutDocs->getObjects() as $objectData) {
$document = $objectFactory->convertObject($objectData, $context);
if (!($document instanceof DocumentInterface)) {
// should not happen but could happen if the repository is not implemented correctly ...
continue;
}
$result[] = $document;
}
return $result;
} | Returns all checked out documents in this folder using the given OperationContext.
@param OperationContextInterface|null $context
@return DocumentInterface[] A list of checked out documents. | entailment |
public function getChildren(OperationContextInterface $context = null)
{
$context = $this->ensureContext($context);
$children = $this->getBinding()->getNavigationService()->getChildren(
$this->getRepositoryId(),
$this->getId(),
$context->getQueryFilterString(),
$context->getOrderBy(),
$context->isIncludeAllowableActions(),
$context->getIncludeRelationships(),
$context->getRenditionFilterString(),
$context->isIncludePathSegments()
);
$result = [];
$objectFactory = $this->getObjectFactory();
foreach ($children->getObjects() as $objectData) {
if ($objectData->getObject() !== null) {
$result[] = $objectFactory->convertObject($objectData->getObject(), $context);
}
}
return $result;
} | Returns the children of this folder using the given OperationContext.
@param OperationContextInterface|null $context
@return CmisObjectInterface[] A list of the child objects for the specified folder. | entailment |
public function getFolderParent()
{
if ($this->isRootFolder()) {
return null;
}
$parents = $this->getParents($this->getSession()->getDefaultContext());
// return the first element of the array
$parent = reset($parents);
if (!$parent instanceof FolderInterface) {
return null;
}
return $parent;
} | Gets the parent folder object.
@return FolderInterface|null the parent folder object or <code>null</code> if the folder is the root folder. | entailment |
public function getFolderTree($depth, OperationContextInterface $context = null)
{
$context = $this->ensureContext($context);
$containerList = $this->getBinding()->getNavigationService()->getFolderTree(
$this->getRepositoryId(),
$this->getId(),
(int) $depth,
$context->getQueryFilterString(),
$context->isIncludeAllowableActions(),
$context->getIncludeRelationships(),
$context->getRenditionFilterString(),
$context->isIncludePathSegments()
);
return $this->convertBindingContainer($containerList, $context);
} | Gets the folder tree starting with this folder using the given OperationContext.
@param integer $depth The number of levels of depth in the folder hierarchy from which to return results.
Valid values are:
1
Return only objects that are children of the folder. See also getChildren.
<Integer value greater than 1>
Return only objects that are children of the folder and descendants up to <value> levels deep.
-1
Return ALL descendant objects at all depth levels in the CMIS hierarchy.
The default value is repository specific and SHOULD be at least 2 or -1.
@param OperationContextInterface|null $context
@return TreeInterface A tree that contains FileableCmisObject objects
@see FileableCmisObject FileableCmisObject contained in returned TreeInterface | entailment |
public function getPath()
{
$path = $this->getPropertyValue(PropertyIds::PATH);
// if the path property isn't set, get it
if ($path === null) {
$objectData = $this->getBinding()->getObjectService()->getObject(
$this->getRepositoryId(),
$this->getId(),
$this->getPropertyQueryName(PropertyIds::PATH),
false,
IncludeRelationships::cast(IncludeRelationships::NONE),
Constants::RENDITION_NONE,
false,
false
);
if ($objectData !== null
&& $objectData->getProperties() !== null
&& $objectData->getProperties()->getProperties() !== null
) {
$objectProperties = $objectData->getProperties()->getProperties();
if (isset($objectProperties[PropertyIds::PATH])
&& $objectProperties[PropertyIds::PATH] instanceof PropertyString
) {
$path = $objectProperties[PropertyIds::PATH]->getFirstValue();
}
}
}
// we still don't know the path ... it's not a CMIS compliant repository
if ($path === null) {
throw new CmisRuntimeException('Repository didn\'t return ' . PropertyIds::PATH . '!');
}
return $path;
} | Returns the path of the folder.
@return string the absolute folder path | entailment |
public function getAllowedChildObjectTypes()
{
$result = [];
$objectTypeIds = $this->getPropertyValue(PropertyIds::ALLOWED_CHILD_OBJECT_TYPE_IDS);
if ($objectTypeIds === null) {
return $result;
}
foreach ($objectTypeIds as $objectTypeId) {
$result[] = $this->getSession()->getTypeDefinition($objectTypeId);
}
return $result;
} | Returns the list of the allowed object types in this folder (CMIS property cmis:allowedChildObjectTypeIds).
If the list is empty or <code>null</code> all object types are allowed.
@return ObjectTypeInterface[] the property value or <code>null</code> if the property hasn't been requested,
hasn't been provided by the repository, or the property value isn't set | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.