repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
multidots/cakephp-rest-api | src/Error/ApiExceptionRenderer.php | ApiExceptionRenderer.__prepareResponse | private function __prepareResponse($exception, $options = [])
{
$response = $this->_getController()->response;
$code = $this->_code($exception);
$response->getStatusCode($this->_code($exception));
Configure::write('apiExceptionMessage', $exception->getMessage());
$responseFormat = $this->_getController()->responseFormat;
$responseData = [
$responseFormat['statusKey'] => !empty($options['responseStatus']) ? $options['responseStatus'] : $responseFormat['statusNokText'],
$responseFormat['resultKey'] => [
$responseFormat['errorKey'] => ($code < 500) ? 'Not Found' : 'An Internal Error Has Occurred.',
],
];
if ((isset($options['customMessage']) && $options['customMessage']) || Configure::read('ApiRequest.debug')) {
$responseData[$responseFormat['resultKey']][$responseFormat['errorKey']] = $exception->getMessage();
}
if ('xml' === Configure::read('ApiRequest.responseType')) {
$body = $response->getBody();
$body->write(Xml::fromArray([Configure::read('ApiRequest.xmlResponseRootNode') => $responseData], 'tags')->asXML());
$response->withBody($body);
} else {
$body = $response->getBody();
$body->write(json_encode($responseData));
$response->withBody($body);
}
$this->controller->response = $response;
return $response;
} | php | private function __prepareResponse($exception, $options = [])
{
$response = $this->_getController()->response;
$code = $this->_code($exception);
$response->getStatusCode($this->_code($exception));
Configure::write('apiExceptionMessage', $exception->getMessage());
$responseFormat = $this->_getController()->responseFormat;
$responseData = [
$responseFormat['statusKey'] => !empty($options['responseStatus']) ? $options['responseStatus'] : $responseFormat['statusNokText'],
$responseFormat['resultKey'] => [
$responseFormat['errorKey'] => ($code < 500) ? 'Not Found' : 'An Internal Error Has Occurred.',
],
];
if ((isset($options['customMessage']) && $options['customMessage']) || Configure::read('ApiRequest.debug')) {
$responseData[$responseFormat['resultKey']][$responseFormat['errorKey']] = $exception->getMessage();
}
if ('xml' === Configure::read('ApiRequest.responseType')) {
$body = $response->getBody();
$body->write(Xml::fromArray([Configure::read('ApiRequest.xmlResponseRootNode') => $responseData], 'tags')->asXML());
$response->withBody($body);
} else {
$body = $response->getBody();
$body->write(json_encode($responseData));
$response->withBody($body);
}
$this->controller->response = $response;
return $response;
} | [
"private",
"function",
"__prepareResponse",
"(",
"$",
"exception",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"_getController",
"(",
")",
"->",
"response",
";",
"$",
"code",
"=",
"$",
"this",
"->",
"_code",
"(",
"$",
"exception",
")",
";",
"$",
"response",
"->",
"getStatusCode",
"(",
"$",
"this",
"->",
"_code",
"(",
"$",
"exception",
")",
")",
";",
"Configure",
"::",
"write",
"(",
"'apiExceptionMessage'",
",",
"$",
"exception",
"->",
"getMessage",
"(",
")",
")",
";",
"$",
"responseFormat",
"=",
"$",
"this",
"->",
"_getController",
"(",
")",
"->",
"responseFormat",
";",
"$",
"responseData",
"=",
"[",
"$",
"responseFormat",
"[",
"'statusKey'",
"]",
"=>",
"!",
"empty",
"(",
"$",
"options",
"[",
"'responseStatus'",
"]",
")",
"?",
"$",
"options",
"[",
"'responseStatus'",
"]",
":",
"$",
"responseFormat",
"[",
"'statusNokText'",
"]",
",",
"$",
"responseFormat",
"[",
"'resultKey'",
"]",
"=>",
"[",
"$",
"responseFormat",
"[",
"'errorKey'",
"]",
"=>",
"(",
"$",
"code",
"<",
"500",
")",
"?",
"'Not Found'",
":",
"'An Internal Error Has Occurred.'",
",",
"]",
",",
"]",
";",
"if",
"(",
"(",
"isset",
"(",
"$",
"options",
"[",
"'customMessage'",
"]",
")",
"&&",
"$",
"options",
"[",
"'customMessage'",
"]",
")",
"||",
"Configure",
"::",
"read",
"(",
"'ApiRequest.debug'",
")",
")",
"{",
"$",
"responseData",
"[",
"$",
"responseFormat",
"[",
"'resultKey'",
"]",
"]",
"[",
"$",
"responseFormat",
"[",
"'errorKey'",
"]",
"]",
"=",
"$",
"exception",
"->",
"getMessage",
"(",
")",
";",
"}",
"if",
"(",
"'xml'",
"===",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseType'",
")",
")",
"{",
"$",
"body",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"$",
"body",
"->",
"write",
"(",
"Xml",
"::",
"fromArray",
"(",
"[",
"Configure",
"::",
"read",
"(",
"'ApiRequest.xmlResponseRootNode'",
")",
"=>",
"$",
"responseData",
"]",
",",
"'tags'",
")",
"->",
"asXML",
"(",
")",
")",
";",
"$",
"response",
"->",
"withBody",
"(",
"$",
"body",
")",
";",
"}",
"else",
"{",
"$",
"body",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"$",
"body",
"->",
"write",
"(",
"json_encode",
"(",
"$",
"responseData",
")",
")",
";",
"$",
"response",
"->",
"withBody",
"(",
"$",
"body",
")",
";",
"}",
"$",
"this",
"->",
"controller",
"->",
"response",
"=",
"$",
"response",
";",
"return",
"$",
"response",
";",
"}"
] | Prepare response.
@param Exception $exception Exception
@param array $options Array of options
@return Response | [
"Prepare",
"response",
"."
] | train | https://github.com/multidots/cakephp-rest-api/blob/6c2a73bbe3073c58ade3f24cd015dd58e71ebd50/src/Error/ApiExceptionRenderer.php#L77-L110 |
multidots/cakephp-rest-api | src/Controller/ApiErrorController.php | ApiErrorController.beforeRender | public function beforeRender(Event $event)
{
$this->httpStatusCode = $this->response->getStatusCode();
$messageArr = $this->response->withStatus($this->httpStatusCode);
if (Configure::read('ApiRequest.debug') && isset($this->viewVars['error'])) {
$this->apiResponse[$this->responseFormat['messageKey']] = $this->viewVars['error']->getMessage();
} else {
$this->apiResponse[$this->responseFormat['messageKey']] = !empty($messageArr[$this->httpStatusCode]) ? $messageArr[$this->httpStatusCode] : 'Unknown error!';
}
Configure::write('apiExceptionMessage', isset($this->viewVars['error']) ? $this->viewVars['error']->getMessage() : null);
parent::beforeRender($event);
$this->viewBuilder()->setClassName('RestApi.ApiError');
return null;
} | php | public function beforeRender(Event $event)
{
$this->httpStatusCode = $this->response->getStatusCode();
$messageArr = $this->response->withStatus($this->httpStatusCode);
if (Configure::read('ApiRequest.debug') && isset($this->viewVars['error'])) {
$this->apiResponse[$this->responseFormat['messageKey']] = $this->viewVars['error']->getMessage();
} else {
$this->apiResponse[$this->responseFormat['messageKey']] = !empty($messageArr[$this->httpStatusCode]) ? $messageArr[$this->httpStatusCode] : 'Unknown error!';
}
Configure::write('apiExceptionMessage', isset($this->viewVars['error']) ? $this->viewVars['error']->getMessage() : null);
parent::beforeRender($event);
$this->viewBuilder()->setClassName('RestApi.ApiError');
return null;
} | [
"public",
"function",
"beforeRender",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"this",
"->",
"httpStatusCode",
"=",
"$",
"this",
"->",
"response",
"->",
"getStatusCode",
"(",
")",
";",
"$",
"messageArr",
"=",
"$",
"this",
"->",
"response",
"->",
"withStatus",
"(",
"$",
"this",
"->",
"httpStatusCode",
")",
";",
"if",
"(",
"Configure",
"::",
"read",
"(",
"'ApiRequest.debug'",
")",
"&&",
"isset",
"(",
"$",
"this",
"->",
"viewVars",
"[",
"'error'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"apiResponse",
"[",
"$",
"this",
"->",
"responseFormat",
"[",
"'messageKey'",
"]",
"]",
"=",
"$",
"this",
"->",
"viewVars",
"[",
"'error'",
"]",
"->",
"getMessage",
"(",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"apiResponse",
"[",
"$",
"this",
"->",
"responseFormat",
"[",
"'messageKey'",
"]",
"]",
"=",
"!",
"empty",
"(",
"$",
"messageArr",
"[",
"$",
"this",
"->",
"httpStatusCode",
"]",
")",
"?",
"$",
"messageArr",
"[",
"$",
"this",
"->",
"httpStatusCode",
"]",
":",
"'Unknown error!'",
";",
"}",
"Configure",
"::",
"write",
"(",
"'apiExceptionMessage'",
",",
"isset",
"(",
"$",
"this",
"->",
"viewVars",
"[",
"'error'",
"]",
")",
"?",
"$",
"this",
"->",
"viewVars",
"[",
"'error'",
"]",
"->",
"getMessage",
"(",
")",
":",
"null",
")",
";",
"parent",
"::",
"beforeRender",
"(",
"$",
"event",
")",
";",
"$",
"this",
"->",
"viewBuilder",
"(",
")",
"->",
"setClassName",
"(",
"'RestApi.ApiError'",
")",
";",
"return",
"null",
";",
"}"
] | beforeRender callback.
@param Event $event Event.
@return null | [
"beforeRender",
"callback",
"."
] | train | https://github.com/multidots/cakephp-rest-api/blob/6c2a73bbe3073c58ade3f24cd015dd58e71ebd50/src/Controller/ApiErrorController.php#L22-L41 |
multidots/cakephp-rest-api | src/Utility/JwtToken.php | JwtToken.generateToken | public static function generateToken($payload = null)
{
if (empty($payload)) {
return false;
}
$token = JWT::encode($payload, Configure::read('ApiRequest.jwtAuth.cypherKey'), Configure::read('ApiRequest.jwtAuth.tokenAlgorithm'));
return $token;
} | php | public static function generateToken($payload = null)
{
if (empty($payload)) {
return false;
}
$token = JWT::encode($payload, Configure::read('ApiRequest.jwtAuth.cypherKey'), Configure::read('ApiRequest.jwtAuth.tokenAlgorithm'));
return $token;
} | [
"public",
"static",
"function",
"generateToken",
"(",
"$",
"payload",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"payload",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"token",
"=",
"JWT",
"::",
"encode",
"(",
"$",
"payload",
",",
"Configure",
"::",
"read",
"(",
"'ApiRequest.jwtAuth.cypherKey'",
")",
",",
"Configure",
"::",
"read",
"(",
"'ApiRequest.jwtAuth.tokenAlgorithm'",
")",
")",
";",
"return",
"$",
"token",
";",
"}"
] | Generates a token based on payload
@param mixed $payload Payload data to generate token
@return string|bool Token or false | [
"Generates",
"a",
"token",
"based",
"on",
"payload"
] | train | https://github.com/multidots/cakephp-rest-api/blob/6c2a73bbe3073c58ade3f24cd015dd58e71ebd50/src/Utility/JwtToken.php#L20-L29 |
multidots/cakephp-rest-api | src/View/ApiErrorView.php | ApiErrorView.initialize | public function initialize()
{
parent::initialize();
if ('xml' === Configure::read('ApiRequest.responseType')) {
$this->response->withType('xml');
$this->_responseLayout = 'xml_error';
} else {
$this->response->withType('json');
}
} | php | public function initialize()
{
parent::initialize();
if ('xml' === Configure::read('ApiRequest.responseType')) {
$this->response->withType('xml');
$this->_responseLayout = 'xml_error';
} else {
$this->response->withType('json');
}
} | [
"public",
"function",
"initialize",
"(",
")",
"{",
"parent",
"::",
"initialize",
"(",
")",
";",
"if",
"(",
"'xml'",
"===",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseType'",
")",
")",
"{",
"$",
"this",
"->",
"response",
"->",
"withType",
"(",
"'xml'",
")",
";",
"$",
"this",
"->",
"_responseLayout",
"=",
"'xml_error'",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"response",
"->",
"withType",
"(",
"'json'",
")",
";",
"}",
"}"
] | Initialization hook method.
@return void | [
"Initialization",
"hook",
"method",
"."
] | train | https://github.com/multidots/cakephp-rest-api/blob/6c2a73bbe3073c58ade3f24cd015dd58e71ebd50/src/View/ApiErrorView.php#L29-L39 |
multidots/cakephp-rest-api | src/Utility/ApiRequestLogger.php | ApiRequestLogger.log | public static function log(Request $request, Response $response)
{
Configure::write('requestLogged', true);
try {
$apiRequests = TableRegistry::get('RestApi.ApiRequests');
$entityData = [
'http_method' => $request->getMethod(),
'endpoint' => $request->getRequestTarget(),
'token' => Configure::read('accessToken'),
'ip_address' => $request->clientIp(),
'request_data' => json_encode($request->getData()),
'response_code' => $response->getStatusCode(),
'response_type' => Configure::read('ApiRequest.responseType'),
'response_data' => $response->getBody(),
'exception' => Configure::read('apiExceptionMessage'),
];
$entity = $apiRequests->newEntity($entityData);
$apiRequests->save($entity);
} catch (\Exception $e) {
return;
}
} | php | public static function log(Request $request, Response $response)
{
Configure::write('requestLogged', true);
try {
$apiRequests = TableRegistry::get('RestApi.ApiRequests');
$entityData = [
'http_method' => $request->getMethod(),
'endpoint' => $request->getRequestTarget(),
'token' => Configure::read('accessToken'),
'ip_address' => $request->clientIp(),
'request_data' => json_encode($request->getData()),
'response_code' => $response->getStatusCode(),
'response_type' => Configure::read('ApiRequest.responseType'),
'response_data' => $response->getBody(),
'exception' => Configure::read('apiExceptionMessage'),
];
$entity = $apiRequests->newEntity($entityData);
$apiRequests->save($entity);
} catch (\Exception $e) {
return;
}
} | [
"public",
"static",
"function",
"log",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"Configure",
"::",
"write",
"(",
"'requestLogged'",
",",
"true",
")",
";",
"try",
"{",
"$",
"apiRequests",
"=",
"TableRegistry",
"::",
"get",
"(",
"'RestApi.ApiRequests'",
")",
";",
"$",
"entityData",
"=",
"[",
"'http_method'",
"=>",
"$",
"request",
"->",
"getMethod",
"(",
")",
",",
"'endpoint'",
"=>",
"$",
"request",
"->",
"getRequestTarget",
"(",
")",
",",
"'token'",
"=>",
"Configure",
"::",
"read",
"(",
"'accessToken'",
")",
",",
"'ip_address'",
"=>",
"$",
"request",
"->",
"clientIp",
"(",
")",
",",
"'request_data'",
"=>",
"json_encode",
"(",
"$",
"request",
"->",
"getData",
"(",
")",
")",
",",
"'response_code'",
"=>",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
",",
"'response_type'",
"=>",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseType'",
")",
",",
"'response_data'",
"=>",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"'exception'",
"=>",
"Configure",
"::",
"read",
"(",
"'apiExceptionMessage'",
")",
",",
"]",
";",
"$",
"entity",
"=",
"$",
"apiRequests",
"->",
"newEntity",
"(",
"$",
"entityData",
")",
";",
"$",
"apiRequests",
"->",
"save",
"(",
"$",
"entity",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
";",
"}",
"}"
] | Logs the request and response data into database.
@param Request $request The \Cake\Network\Request object
@param Response $response The \Cake\Network\Response object | [
"Logs",
"the",
"request",
"and",
"response",
"data",
"into",
"database",
"."
] | train | https://github.com/multidots/cakephp-rest-api/blob/6c2a73bbe3073c58ade3f24cd015dd58e71ebd50/src/Utility/ApiRequestLogger.php#L22-L44 |
multidots/cakephp-rest-api | src/Controller/AppController.php | AppController.initialize | public function initialize()
{
parent::initialize();
$this->responseFormat = [
'statusKey' => (null !== Configure::read('ApiRequest.responseFormat.statusKey')) ? Configure::read('ApiRequest.responseFormat.statusKey') : 'status',
'statusOkText' => (null !== Configure::read('ApiRequest.responseFormat.statusOkText')) ? Configure::read('ApiRequest.responseFormat.statusOkText') : 'OK',
'statusNokText' => (null !== Configure::read('ApiRequest.responseFormat.statusNokText')) ? Configure::read('ApiRequest.responseFormat.statusNokText') : 'NOK',
'resultKey' => (null !== Configure::read('ApiRequest.responseFormat.resultKey')) ? Configure::read('ApiRequest.responseFormat.resultKey') : 'result',
'messageKey' => (null !== Configure::read('ApiRequest.responseFormat.messageKey')) ? Configure::read('ApiRequest.responseFormat.messageKey') : 'message',
'defaultMessageText' => (null !== Configure::read('ApiRequest.responseFormat.defaultMessageText')) ? Configure::read('ApiRequest.responseFormat.defaultMessageText') : 'Empty response!',
'errorKey' => (null !== Configure::read('ApiRequest.responseFormat.errorKey')) ? Configure::read('ApiRequest.responseFormat.errorKey') : 'error',
'defaultErrorText' => (null !== Configure::read('ApiRequest.responseFormat.defaultErrorText')) ? Configure::read('ApiRequest.responseFormat.defaultErrorText') : 'Unknown request!'
];
$this->responseStatus = $this->responseFormat['statusOkText'];
$this->loadComponent('RequestHandler');
$this->loadComponent('RestApi.AccessControl');
} | php | public function initialize()
{
parent::initialize();
$this->responseFormat = [
'statusKey' => (null !== Configure::read('ApiRequest.responseFormat.statusKey')) ? Configure::read('ApiRequest.responseFormat.statusKey') : 'status',
'statusOkText' => (null !== Configure::read('ApiRequest.responseFormat.statusOkText')) ? Configure::read('ApiRequest.responseFormat.statusOkText') : 'OK',
'statusNokText' => (null !== Configure::read('ApiRequest.responseFormat.statusNokText')) ? Configure::read('ApiRequest.responseFormat.statusNokText') : 'NOK',
'resultKey' => (null !== Configure::read('ApiRequest.responseFormat.resultKey')) ? Configure::read('ApiRequest.responseFormat.resultKey') : 'result',
'messageKey' => (null !== Configure::read('ApiRequest.responseFormat.messageKey')) ? Configure::read('ApiRequest.responseFormat.messageKey') : 'message',
'defaultMessageText' => (null !== Configure::read('ApiRequest.responseFormat.defaultMessageText')) ? Configure::read('ApiRequest.responseFormat.defaultMessageText') : 'Empty response!',
'errorKey' => (null !== Configure::read('ApiRequest.responseFormat.errorKey')) ? Configure::read('ApiRequest.responseFormat.errorKey') : 'error',
'defaultErrorText' => (null !== Configure::read('ApiRequest.responseFormat.defaultErrorText')) ? Configure::read('ApiRequest.responseFormat.defaultErrorText') : 'Unknown request!'
];
$this->responseStatus = $this->responseFormat['statusOkText'];
$this->loadComponent('RequestHandler');
$this->loadComponent('RestApi.AccessControl');
} | [
"public",
"function",
"initialize",
"(",
")",
"{",
"parent",
"::",
"initialize",
"(",
")",
";",
"$",
"this",
"->",
"responseFormat",
"=",
"[",
"'statusKey'",
"=>",
"(",
"null",
"!==",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.statusKey'",
")",
")",
"?",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.statusKey'",
")",
":",
"'status'",
",",
"'statusOkText'",
"=>",
"(",
"null",
"!==",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.statusOkText'",
")",
")",
"?",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.statusOkText'",
")",
":",
"'OK'",
",",
"'statusNokText'",
"=>",
"(",
"null",
"!==",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.statusNokText'",
")",
")",
"?",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.statusNokText'",
")",
":",
"'NOK'",
",",
"'resultKey'",
"=>",
"(",
"null",
"!==",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.resultKey'",
")",
")",
"?",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.resultKey'",
")",
":",
"'result'",
",",
"'messageKey'",
"=>",
"(",
"null",
"!==",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.messageKey'",
")",
")",
"?",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.messageKey'",
")",
":",
"'message'",
",",
"'defaultMessageText'",
"=>",
"(",
"null",
"!==",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.defaultMessageText'",
")",
")",
"?",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.defaultMessageText'",
")",
":",
"'Empty response!'",
",",
"'errorKey'",
"=>",
"(",
"null",
"!==",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.errorKey'",
")",
")",
"?",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.errorKey'",
")",
":",
"'error'",
",",
"'defaultErrorText'",
"=>",
"(",
"null",
"!==",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.defaultErrorText'",
")",
")",
"?",
"Configure",
"::",
"read",
"(",
"'ApiRequest.responseFormat.defaultErrorText'",
")",
":",
"'Unknown request!'",
"]",
";",
"$",
"this",
"->",
"responseStatus",
"=",
"$",
"this",
"->",
"responseFormat",
"[",
"'statusOkText'",
"]",
";",
"$",
"this",
"->",
"loadComponent",
"(",
"'RequestHandler'",
")",
";",
"$",
"this",
"->",
"loadComponent",
"(",
"'RestApi.AccessControl'",
")",
";",
"}"
] | Initialization hook method.
@return void | [
"Initialization",
"hook",
"method",
"."
] | train | https://github.com/multidots/cakephp-rest-api/blob/6c2a73bbe3073c58ade3f24cd015dd58e71ebd50/src/Controller/AppController.php#L63-L82 |
multidots/cakephp-rest-api | src/Controller/AppController.php | AppController.beforeRender | public function beforeRender(Event $event)
{
parent::beforeRender($event);
$this->response->getStatusCode($this->httpStatusCode);
if (200 != $this->httpStatusCode) {
$this->responseStatus = $this->responseFormat['statusNokText'];
}
$response = [
$this->responseFormat['statusKey'] => $this->responseStatus
];
if (!empty($this->apiResponse)) {
$response[$this->responseFormat['resultKey']] = $this->apiResponse;
}
$this->set('response', $response);
$this->set('responseFormat', $this->responseFormat);
return null;
} | php | public function beforeRender(Event $event)
{
parent::beforeRender($event);
$this->response->getStatusCode($this->httpStatusCode);
if (200 != $this->httpStatusCode) {
$this->responseStatus = $this->responseFormat['statusNokText'];
}
$response = [
$this->responseFormat['statusKey'] => $this->responseStatus
];
if (!empty($this->apiResponse)) {
$response[$this->responseFormat['resultKey']] = $this->apiResponse;
}
$this->set('response', $response);
$this->set('responseFormat', $this->responseFormat);
return null;
} | [
"public",
"function",
"beforeRender",
"(",
"Event",
"$",
"event",
")",
"{",
"parent",
"::",
"beforeRender",
"(",
"$",
"event",
")",
";",
"$",
"this",
"->",
"response",
"->",
"getStatusCode",
"(",
"$",
"this",
"->",
"httpStatusCode",
")",
";",
"if",
"(",
"200",
"!=",
"$",
"this",
"->",
"httpStatusCode",
")",
"{",
"$",
"this",
"->",
"responseStatus",
"=",
"$",
"this",
"->",
"responseFormat",
"[",
"'statusNokText'",
"]",
";",
"}",
"$",
"response",
"=",
"[",
"$",
"this",
"->",
"responseFormat",
"[",
"'statusKey'",
"]",
"=>",
"$",
"this",
"->",
"responseStatus",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"apiResponse",
")",
")",
"{",
"$",
"response",
"[",
"$",
"this",
"->",
"responseFormat",
"[",
"'resultKey'",
"]",
"]",
"=",
"$",
"this",
"->",
"apiResponse",
";",
"}",
"$",
"this",
"->",
"set",
"(",
"'response'",
",",
"$",
"response",
")",
";",
"$",
"this",
"->",
"set",
"(",
"'responseFormat'",
",",
"$",
"this",
"->",
"responseFormat",
")",
";",
"return",
"null",
";",
"}"
] | Before render callback.
@param Event $event The beforeRender event.
@return \Cake\Network\Response|null | [
"Before",
"render",
"callback",
"."
] | train | https://github.com/multidots/cakephp-rest-api/blob/6c2a73bbe3073c58ade3f24cd015dd58e71ebd50/src/Controller/AppController.php#L90-L112 |
jack-theripper/yandex | src/Disk.php | Disk.toArray | public function toArray(array $allowed = null)
{
if ( ! $this->_toArray())
{
$response = $this->send(new Request($this->uri, 'GET'));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if ( ! is_array($response))
{
throw new UnsupportedException('Получен не поддерживаемый формат ответа от API Диска.');
}
$this->setContents($response += [
'free_space' => $response['total_space'] - $response['used_space']
]);
}
}
return $this->_toArray($allowed);
} | php | public function toArray(array $allowed = null)
{
if ( ! $this->_toArray())
{
$response = $this->send(new Request($this->uri, 'GET'));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if ( ! is_array($response))
{
throw new UnsupportedException('Получен не поддерживаемый формат ответа от API Диска.');
}
$this->setContents($response += [
'free_space' => $response['total_space'] - $response['used_space']
]);
}
}
return $this->_toArray($allowed);
} | [
"public",
"function",
"toArray",
"(",
"array",
"$",
"allowed",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_toArray",
"(",
")",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
",",
"'GET'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"response",
")",
")",
"{",
"throw",
"new",
"UnsupportedException",
"(",
"'Получен не поддерживаемый формат ответа от API Диска.');",
"",
"",
"}",
"$",
"this",
"->",
"setContents",
"(",
"$",
"response",
"+=",
"[",
"'free_space'",
"=>",
"$",
"response",
"[",
"'total_space'",
"]",
"-",
"$",
"response",
"[",
"'used_space'",
"]",
"]",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"_toArray",
"(",
"$",
"allowed",
")",
";",
"}"
] | Получает информацию о диске
@param array $allowed
@return array
@example
array (size=5)
'trash_size' => int 9449304
'total_space' => float 33822867456
'used_space' => float 25863284099
'free_space' => float 7959583357
'system_folders' => array (size=2)
'applications' => string 'disk:/Приложения' (length=26)
'downloads' => string 'disk:/Загрузки/' (length=23) | [
"Получает",
"информацию",
"о",
"диске"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk.php#L168-L190 |
jack-theripper/yandex | src/Disk.php | Disk.getResource | public function getResource($path, $limit = 20, $offset = 0)
{
if ( ! is_string($path))
{
throw new \InvalidArgumentException('Ресурс, должен быть строкового типа - путь к файлу/папке.');
}
if (stripos($path, 'app:/') !== 0 && stripos($path, 'disk:/') !== 0)
{
$path = 'disk:/'.ltrim($path, ' /');
}
return (new Disk\Resource\Closed($path, $this, $this->uri))
->setLimit($limit, $offset);
} | php | public function getResource($path, $limit = 20, $offset = 0)
{
if ( ! is_string($path))
{
throw new \InvalidArgumentException('Ресурс, должен быть строкового типа - путь к файлу/папке.');
}
if (stripos($path, 'app:/') !== 0 && stripos($path, 'disk:/') !== 0)
{
$path = 'disk:/'.ltrim($path, ' /');
}
return (new Disk\Resource\Closed($path, $this, $this->uri))
->setLimit($limit, $offset);
} | [
"public",
"function",
"getResource",
"(",
"$",
"path",
",",
"$",
"limit",
"=",
"20",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Ресурс, должен быть строкового типа - путь к файлу/папке.');",
"",
"",
"}",
"if",
"(",
"stripos",
"(",
"$",
"path",
",",
"'app:/'",
")",
"!==",
"0",
"&&",
"stripos",
"(",
"$",
"path",
",",
"'disk:/'",
")",
"!==",
"0",
")",
"{",
"$",
"path",
"=",
"'disk:/'",
".",
"ltrim",
"(",
"$",
"path",
",",
"' /'",
")",
";",
"}",
"return",
"(",
"new",
"Disk",
"\\",
"Resource",
"\\",
"Closed",
"(",
"$",
"path",
",",
"$",
"this",
",",
"$",
"this",
"->",
"uri",
")",
")",
"->",
"setLimit",
"(",
"$",
"limit",
",",
"$",
"offset",
")",
";",
"}"
] | Работа с ресурсами на диске
@param string $path Путь к новому либо уже существующему ресурсу
@param integer $limit
@param integer $offset
@return \Arhitector\Yandex\Disk\Resource\Closed
@example
$disk->getResource('any_file.ext') -> upload( __DIR__.'/file_to_upload');
$disk->getResource('any_file.ext') // Mackey\Yandex\Disk\Resource\Closed
->toArray(); // если ресурса еще нет, то исключение NotFoundException
array (size=11)
'public_key' => string 'wICbu9SPnY3uT4tFA6P99YXJwuAr2TU7oGYu1fTq68Y=' (length=44)
'name' => string 'Gameface - Gangsigns_trapsound.ru.mp3' (length=37)
'created' => string '2014-10-08T22:13:49+00:00' (length=25)
'public_url' => string 'https://yadi.sk/d/g0N4hNtXcrq22' (length=31)
'modified' => string '2014-10-08T22:13:49+00:00' (length=25)
'media_type' => string 'audio' (length=5)
'path' => string 'disk:/applications_swagga/1/Gameface - Gangsigns_trapsound.ru.mp3' (length=65)
'md5' => string '8c2559f3ce1ece12e749f9e5dfbda59f' (length=32)
'type' => string 'file' (length=4)
'mime_type' => string 'audio/mpeg' (length=10)
'size' => int 8099883 | [
"Работа",
"с",
"ресурсами",
"на",
"диске"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk.php#L220-L234 |
jack-theripper/yandex | src/Disk.php | Disk.getPublishResource | public function getPublishResource($public_key, $limit = 20, $offset = 0)
{
if ( ! is_string($public_key))
{
throw new \InvalidArgumentException('Публичный ключ ресурса должен быть строкового типа.');
}
return (new Disk\Resource\Opened($public_key, $this, $this->uri))
->setLimit($limit, $offset);
} | php | public function getPublishResource($public_key, $limit = 20, $offset = 0)
{
if ( ! is_string($public_key))
{
throw new \InvalidArgumentException('Публичный ключ ресурса должен быть строкового типа.');
}
return (new Disk\Resource\Opened($public_key, $this, $this->uri))
->setLimit($limit, $offset);
} | [
"public",
"function",
"getPublishResource",
"(",
"$",
"public_key",
",",
"$",
"limit",
"=",
"20",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"public_key",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Публичный ключ ресурса должен быть строкового типа.');",
"",
"",
"}",
"return",
"(",
"new",
"Disk",
"\\",
"Resource",
"\\",
"Opened",
"(",
"$",
"public_key",
",",
"$",
"this",
",",
"$",
"this",
"->",
"uri",
")",
")",
"->",
"setLimit",
"(",
"$",
"limit",
",",
"$",
"offset",
")",
";",
"}"
] | Работа с опубликованными ресурсами
@param mixed $public_key Публичный ключ к опубликованному ресурсу.
@return \Arhitector\Yandex\Disk\Resource\Opened
@example
$disk->getPublishResource('public_key') -> toArray()
array (size=11)
'public_key' => string 'wICbu9SPnY3uT4tFA6P99YXJwuAr2TU7oGYu1fTq68Y=' (length=44)
'name' => string 'Gameface - Gangsigns_trapsound.ru.mp3' (length=37)
'created' => string '2014-10-08T22:13:49+00:00' (length=25)
'public_url' => string 'https://yadi.sk/d/g0N4hNtXcrq22' (length=31)
'modified' => string '2014-10-08T22:13:49+00:00' (length=25)
'media_type' => string 'audio' (length=5)
'path' => string 'disk:/applications_swagga/1/Gameface - Gangsigns_trapsound.ru.mp3' (length=65)
'md5' => string '8c2559f3ce1ece12e749f9e5dfbda59f' (length=32)
'type' => string 'file' (length=4)
'mime_type' => string 'audio/mpeg' (length=10)
'size' => int 8099883 | [
"Работа",
"с",
"опубликованными",
"ресурсами"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk.php#L300-L309 |
jack-theripper/yandex | src/Disk.php | Disk.getPublishResources | public function getPublishResources($limit = 20, $offset = 0)
{
return (new Disk\Resource\Collection(function($parameters) {
$previous = $this->setAccessTokenRequired(false);
$response = $this->send((new Request($this->uri->withPath($this->uri->getPath().'resources/public')
->withQuery(http_build_query($parameters, null, '&')), 'GET')));
$this->setAccessTokenRequired($previous);
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['items']))
{
return array_map(function($item) {
return new Disk\Resource\Opened($item, $this, $this->uri);
}, $response['items']);
}
}
return [];
}))
->setLimit($limit, $offset);
} | php | public function getPublishResources($limit = 20, $offset = 0)
{
return (new Disk\Resource\Collection(function($parameters) {
$previous = $this->setAccessTokenRequired(false);
$response = $this->send((new Request($this->uri->withPath($this->uri->getPath().'resources/public')
->withQuery(http_build_query($parameters, null, '&')), 'GET')));
$this->setAccessTokenRequired($previous);
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['items']))
{
return array_map(function($item) {
return new Disk\Resource\Opened($item, $this, $this->uri);
}, $response['items']);
}
}
return [];
}))
->setLimit($limit, $offset);
} | [
"public",
"function",
"getPublishResources",
"(",
"$",
"limit",
"=",
"20",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"return",
"(",
"new",
"Disk",
"\\",
"Resource",
"\\",
"Collection",
"(",
"function",
"(",
"$",
"parameters",
")",
"{",
"$",
"previous",
"=",
"$",
"this",
"->",
"setAccessTokenRequired",
"(",
"false",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"send",
"(",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources/public'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"$",
"parameters",
",",
"null",
",",
"'&'",
")",
")",
",",
"'GET'",
")",
")",
")",
";",
"$",
"this",
"->",
"setAccessTokenRequired",
"(",
"$",
"previous",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'items'",
"]",
")",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"$",
"item",
")",
"{",
"return",
"new",
"Disk",
"\\",
"Resource",
"\\",
"Opened",
"(",
"$",
"item",
",",
"$",
"this",
",",
"$",
"this",
"->",
"uri",
")",
";",
"}",
",",
"$",
"response",
"[",
"'items'",
"]",
")",
";",
"}",
"}",
"return",
"[",
"]",
";",
"}",
")",
")",
"->",
"setLimit",
"(",
"$",
"limit",
",",
"$",
"offset",
")",
";",
"}"
] | Получение списка опубликованных файлов и папок
@param int $limit
@param int $offset
@return \Arhitector\Yandex\Disk\Resource\Collection | [
"Получение",
"списка",
"опубликованных",
"файлов",
"и",
"папок"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk.php#L319-L342 |
jack-theripper/yandex | src/Disk.php | Disk.getTrashResource | public function getTrashResource($path, $limit = 20, $offset = 0)
{
if ( ! is_string($path))
{
throw new \InvalidArgumentException('Ресурс, должен быть строкового типа - путь к файлу/папке, либо NULL');
}
if (stripos($path, 'trash:/') === 0)
{
$path = substr($path, 7);
}
return (new Disk\Resource\Removed('trash:/'.ltrim($path, ' /'), $this, $this->uri))
->setLimit($limit, $offset);
} | php | public function getTrashResource($path, $limit = 20, $offset = 0)
{
if ( ! is_string($path))
{
throw new \InvalidArgumentException('Ресурс, должен быть строкового типа - путь к файлу/папке, либо NULL');
}
if (stripos($path, 'trash:/') === 0)
{
$path = substr($path, 7);
}
return (new Disk\Resource\Removed('trash:/'.ltrim($path, ' /'), $this, $this->uri))
->setLimit($limit, $offset);
} | [
"public",
"function",
"getTrashResource",
"(",
"$",
"path",
",",
"$",
"limit",
"=",
"20",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Ресурс, должен быть строкового типа - путь к файлу/папке, либо NULL');",
"",
"",
"}",
"if",
"(",
"stripos",
"(",
"$",
"path",
",",
"'trash:/'",
")",
"===",
"0",
")",
"{",
"$",
"path",
"=",
"substr",
"(",
"$",
"path",
",",
"7",
")",
";",
"}",
"return",
"(",
"new",
"Disk",
"\\",
"Resource",
"\\",
"Removed",
"(",
"'trash:/'",
".",
"ltrim",
"(",
"$",
"path",
",",
"' /'",
")",
",",
"$",
"this",
",",
"$",
"this",
"->",
"uri",
")",
")",
"->",
"setLimit",
"(",
"$",
"limit",
",",
"$",
"offset",
")",
";",
"}"
] | Ресурсы в корзине.
@param string $path путь к файлу в корзине
@param int $limit
@param int $offset
@return \Arhitector\Yandex\Disk\Resource\Removed
@example
$disk->getTrashResource('file.ext') -> toArray() // файл в корзине
$disk->getTrashResource('trash:/file.ext') -> delete() | [
"Ресурсы",
"в",
"корзине",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk.php#L357-L371 |
jack-theripper/yandex | src/Disk.php | Disk.getTrashResources | public function getTrashResources($limit = 20, $offset = 0)
{
return (new Disk\Resource\Collection(function($parameters) {
if ( ! empty($parameters['sort'])
&& ! in_array($parameters['sort'], ['deleted', 'created', '-deleted', '-created'])
)
{
throw new \UnexpectedValueException('Допустимые значения сортировки - deleted, created и со знаком "минус".');
}
$response = $this->send((new Request($this->uri->withPath($this->uri->getPath().'trash/resources')
->withQuery(http_build_query($parameters + ['path' => 'trash:/'], null, '&')), 'GET')));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['_embedded']['items']))
{
return array_map(function($item) {
return new Disk\Resource\Removed($item, $this, $this->uri);
}, $response['_embedded']['items']);
}
}
return [];
}))
->setSort('created')
->setLimit($limit, $offset);
} | php | public function getTrashResources($limit = 20, $offset = 0)
{
return (new Disk\Resource\Collection(function($parameters) {
if ( ! empty($parameters['sort'])
&& ! in_array($parameters['sort'], ['deleted', 'created', '-deleted', '-created'])
)
{
throw new \UnexpectedValueException('Допустимые значения сортировки - deleted, created и со знаком "минус".');
}
$response = $this->send((new Request($this->uri->withPath($this->uri->getPath().'trash/resources')
->withQuery(http_build_query($parameters + ['path' => 'trash:/'], null, '&')), 'GET')));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['_embedded']['items']))
{
return array_map(function($item) {
return new Disk\Resource\Removed($item, $this, $this->uri);
}, $response['_embedded']['items']);
}
}
return [];
}))
->setSort('created')
->setLimit($limit, $offset);
} | [
"public",
"function",
"getTrashResources",
"(",
"$",
"limit",
"=",
"20",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"return",
"(",
"new",
"Disk",
"\\",
"Resource",
"\\",
"Collection",
"(",
"function",
"(",
"$",
"parameters",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"parameters",
"[",
"'sort'",
"]",
")",
"&&",
"!",
"in_array",
"(",
"$",
"parameters",
"[",
"'sort'",
"]",
",",
"[",
"'deleted'",
",",
"'created'",
",",
"'-deleted'",
",",
"'-created'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'Допустимые значения сортировки - deleted, created и со знаком \"минус\".');",
"",
"",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"send",
"(",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'trash/resources'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"$",
"parameters",
"+",
"[",
"'path'",
"=>",
"'trash:/'",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'GET'",
")",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'_embedded'",
"]",
"[",
"'items'",
"]",
")",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"$",
"item",
")",
"{",
"return",
"new",
"Disk",
"\\",
"Resource",
"\\",
"Removed",
"(",
"$",
"item",
",",
"$",
"this",
",",
"$",
"this",
"->",
"uri",
")",
";",
"}",
",",
"$",
"response",
"[",
"'_embedded'",
"]",
"[",
"'items'",
"]",
")",
";",
"}",
"}",
"return",
"[",
"]",
";",
"}",
")",
")",
"->",
"setSort",
"(",
"'created'",
")",
"->",
"setLimit",
"(",
"$",
"limit",
",",
"$",
"offset",
")",
";",
"}"
] | Содержимое всей корзины.
@param int $limit
@param int $offset
@return \Arhitector\Yandex\Disk\Resource\Collection | [
"Содержимое",
"всей",
"корзины",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk.php#L381-L410 |
jack-theripper/yandex | src/Disk.php | Disk.cleanTrash | public function cleanTrash()
{
$response = $this->send(new Request($this->uri->withPath($this->uri->getPath().'trash/resources'), 'DELETE'));
if ($response->getStatusCode() == 204)
{
$response = json_decode($response->getBody(), true);
if ( ! empty($response['operation']))
{
return $response['operation'];
}
return true;
}
return false;
} | php | public function cleanTrash()
{
$response = $this->send(new Request($this->uri->withPath($this->uri->getPath().'trash/resources'), 'DELETE'));
if ($response->getStatusCode() == 204)
{
$response = json_decode($response->getBody(), true);
if ( ! empty($response['operation']))
{
return $response['operation'];
}
return true;
}
return false;
} | [
"public",
"function",
"cleanTrash",
"(",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'trash/resources'",
")",
",",
"'DELETE'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"204",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
")",
"{",
"return",
"$",
"response",
"[",
"'operation'",
"]",
";",
"}",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Очистить корзину.
@return bool|\Arhitector\Yandex\Disk\Operation | [
"Очистить",
"корзину",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk.php#L417-L434 |
jack-theripper/yandex | src/Disk.php | Disk.uploaded | public function uploaded($limit = 20, $offset = 0)
{
return (new Disk\Resource\Collection(function($parameters) {
$response = $this->send((new Request($this->uri->withPath($this->uri->getPath().'resources/last-uploaded')
->withQuery(http_build_query($parameters, null, '&')), 'GET')));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['items']))
{
return array_map(function($item) {
return new Disk\Resource\Closed($item, $this, $this->uri);
}, $response['items']);
}
}
return [];
}))
->setLimit($limit, $offset);
} | php | public function uploaded($limit = 20, $offset = 0)
{
return (new Disk\Resource\Collection(function($parameters) {
$response = $this->send((new Request($this->uri->withPath($this->uri->getPath().'resources/last-uploaded')
->withQuery(http_build_query($parameters, null, '&')), 'GET')));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['items']))
{
return array_map(function($item) {
return new Disk\Resource\Closed($item, $this, $this->uri);
}, $response['items']);
}
}
return [];
}))
->setLimit($limit, $offset);
} | [
"public",
"function",
"uploaded",
"(",
"$",
"limit",
"=",
"20",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"return",
"(",
"new",
"Disk",
"\\",
"Resource",
"\\",
"Collection",
"(",
"function",
"(",
"$",
"parameters",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"send",
"(",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources/last-uploaded'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"$",
"parameters",
",",
"null",
",",
"'&'",
")",
")",
",",
"'GET'",
")",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'items'",
"]",
")",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"$",
"item",
")",
"{",
"return",
"new",
"Disk",
"\\",
"Resource",
"\\",
"Closed",
"(",
"$",
"item",
",",
"$",
"this",
",",
"$",
"this",
"->",
"uri",
")",
";",
"}",
",",
"$",
"response",
"[",
"'items'",
"]",
")",
";",
"}",
"}",
"return",
"[",
"]",
";",
"}",
")",
")",
"->",
"setLimit",
"(",
"$",
"limit",
",",
"$",
"offset",
")",
";",
"}"
] | Последние загруженные файлы
@param integer $limit
@param integer $offset
@return \Arhitector\Yandex\Disk\Resource\Collection
@example
$disk->uploaded(limit, offset) // коллекия закрытых ресурсов | [
"Последние",
"загруженные",
"файлы"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk.php#L448-L469 |
jack-theripper/yandex | src/Disk.php | Disk.send | public function send(RequestInterface $request)
{
$response = parent::send($request);
if ($response->getStatusCode() == 202)
{
if (($responseBody = json_decode($response->getBody(), true)) && isset($responseBody['href']))
{
$operation = new Uri($responseBody['href']);
if ( ! $operation->getQuery())
{
$responseBody['operation'] = substr(strrchr($operation->getPath(), '/'), 1);
$stream = new Stream('php://temp', 'w');
$stream->write(json_encode($responseBody));
$this->addOperation($responseBody['operation']);
return $response->withBody($stream);
}
}
}
return $response;
} | php | public function send(RequestInterface $request)
{
$response = parent::send($request);
if ($response->getStatusCode() == 202)
{
if (($responseBody = json_decode($response->getBody(), true)) && isset($responseBody['href']))
{
$operation = new Uri($responseBody['href']);
if ( ! $operation->getQuery())
{
$responseBody['operation'] = substr(strrchr($operation->getPath(), '/'), 1);
$stream = new Stream('php://temp', 'w');
$stream->write(json_encode($responseBody));
$this->addOperation($responseBody['operation']);
return $response->withBody($stream);
}
}
}
return $response;
} | [
"public",
"function",
"send",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"$",
"response",
"=",
"parent",
"::",
"send",
"(",
"$",
"request",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"202",
")",
"{",
"if",
"(",
"(",
"$",
"responseBody",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
")",
"&&",
"isset",
"(",
"$",
"responseBody",
"[",
"'href'",
"]",
")",
")",
"{",
"$",
"operation",
"=",
"new",
"Uri",
"(",
"$",
"responseBody",
"[",
"'href'",
"]",
")",
";",
"if",
"(",
"!",
"$",
"operation",
"->",
"getQuery",
"(",
")",
")",
"{",
"$",
"responseBody",
"[",
"'operation'",
"]",
"=",
"substr",
"(",
"strrchr",
"(",
"$",
"operation",
"->",
"getPath",
"(",
")",
",",
"'/'",
")",
",",
"1",
")",
";",
"$",
"stream",
"=",
"new",
"Stream",
"(",
"'php://temp'",
",",
"'w'",
")",
";",
"$",
"stream",
"->",
"write",
"(",
"json_encode",
"(",
"$",
"responseBody",
")",
")",
";",
"$",
"this",
"->",
"addOperation",
"(",
"$",
"responseBody",
"[",
"'operation'",
"]",
")",
";",
"return",
"$",
"response",
"->",
"withBody",
"(",
"$",
"stream",
")",
";",
"}",
"}",
"}",
"return",
"$",
"response",
";",
"}"
] | Отправляет запрос.
@param \Psr\Http\Message\RequestInterface $request
@return \Psr\Http\Message\ResponseInterface | [
"Отправляет",
"запрос",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk.php#L523-L546 |
jack-theripper/yandex | src/Disk/Operation.php | Operation.getStatus | public function getStatus()
{
$response = $this->parent->send(new Request($this->uri->withPath($this->uri->getPath().'operations/'
.$this->getIdentifier()), 'GET'));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['status']))
{
return $response['status'];
}
}
return null;
} | php | public function getStatus()
{
$response = $this->parent->send(new Request($this->uri->withPath($this->uri->getPath().'operations/'
.$this->getIdentifier()), 'GET'));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['status']))
{
return $response['status'];
}
}
return null;
} | [
"public",
"function",
"getStatus",
"(",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parent",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'operations/'",
".",
"$",
"this",
"->",
"getIdentifier",
"(",
")",
")",
",",
"'GET'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'status'",
"]",
")",
")",
"{",
"return",
"$",
"response",
"[",
"'status'",
"]",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Текстовый статус операции.
@return string|null NULL если не удалось получить статус. | [
"Текстовый",
"статус",
"операции",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Operation.php#L80-L96 |
jack-theripper/yandex | src/Disk/Filter/PreviewTrait.php | PreviewTrait.setPreviewCrop | public function setPreviewCrop($crop)
{
$this->isModified = true;
$this->parameters['preview_crop'] = (bool) $crop;
return $this;
} | php | public function setPreviewCrop($crop)
{
$this->isModified = true;
$this->parameters['preview_crop'] = (bool) $crop;
return $this;
} | [
"public",
"function",
"setPreviewCrop",
"(",
"$",
"crop",
")",
"{",
"$",
"this",
"->",
"isModified",
"=",
"true",
";",
"$",
"this",
"->",
"parameters",
"[",
"'preview_crop'",
"]",
"=",
"(",
"bool",
")",
"$",
"crop",
";",
"return",
"$",
"this",
";",
"}"
] | Обрезать превью согласно размеру
@param boolean $crop
@return $this | [
"Обрезать",
"превью",
"согласно",
"размеру"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Filter/PreviewTrait.php#L31-L37 |
jack-theripper/yandex | src/Disk/Filter/PreviewTrait.php | PreviewTrait.setPreview | public function setPreview($preview)
{
if (is_scalar($preview))
{
$preview = strtoupper($preview);
$previewNum = str_replace('X', '', $preview, $replaces);
if (in_array($preview, ['S', 'M', 'L', 'XL', 'XXL', 'XXXL']) || (is_numeric($previewNum) && $replaces < 2))
{
if (is_numeric($previewNum))
{
$preview = strtolower($preview);
}
$this->isModified = true;
$this->parameters['preview_size'] = $preview;
return $this;
}
}
throw new \UnexpectedValueException('Допустимые значения размера превью - S, M, L, XL, XXL, XXXL, <ширина>, <ширина>x, x<высота>, <ширина>x<высота>');
} | php | public function setPreview($preview)
{
if (is_scalar($preview))
{
$preview = strtoupper($preview);
$previewNum = str_replace('X', '', $preview, $replaces);
if (in_array($preview, ['S', 'M', 'L', 'XL', 'XXL', 'XXXL']) || (is_numeric($previewNum) && $replaces < 2))
{
if (is_numeric($previewNum))
{
$preview = strtolower($preview);
}
$this->isModified = true;
$this->parameters['preview_size'] = $preview;
return $this;
}
}
throw new \UnexpectedValueException('Допустимые значения размера превью - S, M, L, XL, XXL, XXXL, <ширина>, <ширина>x, x<высота>, <ширина>x<высота>');
} | [
"public",
"function",
"setPreview",
"(",
"$",
"preview",
")",
"{",
"if",
"(",
"is_scalar",
"(",
"$",
"preview",
")",
")",
"{",
"$",
"preview",
"=",
"strtoupper",
"(",
"$",
"preview",
")",
";",
"$",
"previewNum",
"=",
"str_replace",
"(",
"'X'",
",",
"''",
",",
"$",
"preview",
",",
"$",
"replaces",
")",
";",
"if",
"(",
"in_array",
"(",
"$",
"preview",
",",
"[",
"'S'",
",",
"'M'",
",",
"'L'",
",",
"'XL'",
",",
"'XXL'",
",",
"'XXXL'",
"]",
")",
"||",
"(",
"is_numeric",
"(",
"$",
"previewNum",
")",
"&&",
"$",
"replaces",
"<",
"2",
")",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"previewNum",
")",
")",
"{",
"$",
"preview",
"=",
"strtolower",
"(",
"$",
"preview",
")",
";",
"}",
"$",
"this",
"->",
"isModified",
"=",
"true",
";",
"$",
"this",
"->",
"parameters",
"[",
"'preview_size'",
"]",
"=",
"$",
"preview",
";",
"return",
"$",
"this",
";",
"}",
"}",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'Допустимые значения размера превью - S, M, L, XL, XXL, XXXL, <ширина>, <ширина>x, x<высота>, <ширина>x<высота>');",
"",
"",
"}"
] | Размер уменьшенного превью файла
@param mixed $preview S, M, L, XL, XXL, XXXL, <ширина>, <ширина>x, x<высота>, <ширина>x<высота>
@return $this
@throws \UnexpectedValueException | [
"Размер",
"уменьшенного",
"превью",
"файла"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Filter/PreviewTrait.php#L47-L69 |
jack-theripper/yandex | src/Disk/FilterTrait.php | FilterTrait.setLimit | public function setLimit($limit, $offset = null)
{
if (filter_var($limit, FILTER_VALIDATE_INT) === false)
{
throw new \InvalidArgumentException('Параметр "limit" должен быть целым числом.');
}
$this->isModified = true;
$this->parameters['limit'] = (int) $limit;
if ($offset !== null)
{
$this->setOffset($offset);
}
return $this;
} | php | public function setLimit($limit, $offset = null)
{
if (filter_var($limit, FILTER_VALIDATE_INT) === false)
{
throw new \InvalidArgumentException('Параметр "limit" должен быть целым числом.');
}
$this->isModified = true;
$this->parameters['limit'] = (int) $limit;
if ($offset !== null)
{
$this->setOffset($offset);
}
return $this;
} | [
"public",
"function",
"setLimit",
"(",
"$",
"limit",
",",
"$",
"offset",
"=",
"null",
")",
"{",
"if",
"(",
"filter_var",
"(",
"$",
"limit",
",",
"FILTER_VALIDATE_INT",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Параметр \"limit\" должен быть целым числом.');",
"",
"",
"}",
"$",
"this",
"->",
"isModified",
"=",
"true",
";",
"$",
"this",
"->",
"parameters",
"[",
"'limit'",
"]",
"=",
"(",
"int",
")",
"$",
"limit",
";",
"if",
"(",
"$",
"offset",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"setOffset",
"(",
"$",
"offset",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Количество ресурсов, вложенных в папку, описание которых следует вернуть в ответе
@param integer $limit
@param integer $offset установить смещение
@return $this | [
"Количество",
"ресурсов",
"вложенных",
"в",
"папку",
"описание",
"которых",
"следует",
"вернуть",
"в",
"ответе"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/FilterTrait.php#L46-L62 |
jack-theripper/yandex | src/Disk/FilterTrait.php | FilterTrait.setOffset | public function setOffset($offset)
{
if (filter_var($offset, FILTER_VALIDATE_INT) === false)
{
throw new \InvalidArgumentException('Параметр "offset" должен быть целым числом.');
}
$this->isModified = true;
$this->parameters['offset'] = (int) $offset;
return $this;
} | php | public function setOffset($offset)
{
if (filter_var($offset, FILTER_VALIDATE_INT) === false)
{
throw new \InvalidArgumentException('Параметр "offset" должен быть целым числом.');
}
$this->isModified = true;
$this->parameters['offset'] = (int) $offset;
return $this;
} | [
"public",
"function",
"setOffset",
"(",
"$",
"offset",
")",
"{",
"if",
"(",
"filter_var",
"(",
"$",
"offset",
",",
"FILTER_VALIDATE_INT",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Параметр \"offset\" должен быть целым числом.');",
"",
"",
"}",
"$",
"this",
"->",
"isModified",
"=",
"true",
";",
"$",
"this",
"->",
"parameters",
"[",
"'offset'",
"]",
"=",
"(",
"int",
")",
"$",
"offset",
";",
"return",
"$",
"this",
";",
"}"
] | Количество вложенных ресурсов с начала списка, которые следует опустить в ответе
@param integer $offset
@return $this | [
"Количество",
"вложенных",
"ресурсов",
"с",
"начала",
"списка",
"которые",
"следует",
"опустить",
"в",
"ответе"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/FilterTrait.php#L71-L82 |
jack-theripper/yandex | src/Disk/FilterTrait.php | FilterTrait.setSort | public function setSort($sort, $inverse = false)
{
$sort = (string) $sort;
if ( ! in_array($sort, ['name', 'path', 'created', 'modified', 'size', 'deleted']))
{
throw new \UnexpectedValueException('Допустимые значения сортировки - name, path, created, modified, size');
}
if ($inverse)
{
$sort = '-'.$sort;
}
$this->isModified = true;
$this->parameters['sort'] = $sort;
return $this;
} | php | public function setSort($sort, $inverse = false)
{
$sort = (string) $sort;
if ( ! in_array($sort, ['name', 'path', 'created', 'modified', 'size', 'deleted']))
{
throw new \UnexpectedValueException('Допустимые значения сортировки - name, path, created, modified, size');
}
if ($inverse)
{
$sort = '-'.$sort;
}
$this->isModified = true;
$this->parameters['sort'] = $sort;
return $this;
} | [
"public",
"function",
"setSort",
"(",
"$",
"sort",
",",
"$",
"inverse",
"=",
"false",
")",
"{",
"$",
"sort",
"=",
"(",
"string",
")",
"$",
"sort",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"sort",
",",
"[",
"'name'",
",",
"'path'",
",",
"'created'",
",",
"'modified'",
",",
"'size'",
",",
"'deleted'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'Допустимые значения сортировки - name, path, created, modified, size');",
"",
"",
"}",
"if",
"(",
"$",
"inverse",
")",
"{",
"$",
"sort",
"=",
"'-'",
".",
"$",
"sort",
";",
"}",
"$",
"this",
"->",
"isModified",
"=",
"true",
";",
"$",
"this",
"->",
"parameters",
"[",
"'sort'",
"]",
"=",
"$",
"sort",
";",
"return",
"$",
"this",
";",
"}"
] | Атрибут, по которому сортируется список ресурсов, вложенных в папку.
@param string $sort
@param boolean $inverse TRUE чтобы сортировать в обратном порядке
@return $this
@throws \UnexpectedValueException | [
"Атрибут",
"по",
"которому",
"сортируется",
"список",
"ресурсов",
"вложенных",
"в",
"папку",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/FilterTrait.php#L93-L111 |
jack-theripper/yandex | src/Disk/FilterTrait.php | FilterTrait.getParameters | public function getParameters(array $allowed = null)
{
if ($allowed !== null)
{
return array_intersect_key($this->parameters, array_flip($allowed));
}
return $this->parameters;
} | php | public function getParameters(array $allowed = null)
{
if ($allowed !== null)
{
return array_intersect_key($this->parameters, array_flip($allowed));
}
return $this->parameters;
} | [
"public",
"function",
"getParameters",
"(",
"array",
"$",
"allowed",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"allowed",
"!==",
"null",
")",
"{",
"return",
"array_intersect_key",
"(",
"$",
"this",
"->",
"parameters",
",",
"array_flip",
"(",
"$",
"allowed",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"parameters",
";",
"}"
] | Возвращает все параметры
@return array | [
"Возвращает",
"все",
"параметры"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/FilterTrait.php#L118-L126 |
jack-theripper/yandex | src/Disk/Filter/TypeTrait.php | TypeTrait.setType | public function setType($type)
{
if ( ! is_string($type) || ! in_array($type, ['file', 'dir']))
{
throw new \UnexpectedValueException('Тип ресурса, допустимые значения - "file", "dir".');
}
$this->isModified = true;
$this->parameters['type'] = $type;
return $this;
} | php | public function setType($type)
{
if ( ! is_string($type) || ! in_array($type, ['file', 'dir']))
{
throw new \UnexpectedValueException('Тип ресурса, допустимые значения - "file", "dir".');
}
$this->isModified = true;
$this->parameters['type'] = $type;
return $this;
} | [
"public",
"function",
"setType",
"(",
"$",
"type",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"type",
")",
"||",
"!",
"in_array",
"(",
"$",
"type",
",",
"[",
"'file'",
",",
"'dir'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'Тип ресурса, допустимые значения - \"file\", \"dir\".');",
"",
"",
"}",
"$",
"this",
"->",
"isModified",
"=",
"true",
";",
"$",
"this",
"->",
"parameters",
"[",
"'type'",
"]",
"=",
"$",
"type",
";",
"return",
"$",
"this",
";",
"}"
] | Тип ресурса
@param string $type
@return $this
@throws \UnexpectedValueException | [
"Тип",
"ресурса"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Filter/TypeTrait.php#L31-L42 |
jack-theripper/yandex | src/Disk/Filter/RelativePathTrait.php | RelativePathTrait.setRelativePath | public function setRelativePath($path)
{
if ( ! is_string($path))
{
throw new \InvalidArgumentException('Относительный путь к ресурсу должен быть строкового типа.');
}
$this->isModified = true;
$this->parameters['path'] = '/'.ltrim($path, ' /');
return $this;
} | php | public function setRelativePath($path)
{
if ( ! is_string($path))
{
throw new \InvalidArgumentException('Относительный путь к ресурсу должен быть строкового типа.');
}
$this->isModified = true;
$this->parameters['path'] = '/'.ltrim($path, ' /');
return $this;
} | [
"public",
"function",
"setRelativePath",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Относительный путь к ресурсу должен быть строкового типа.');",
"",
"",
"}",
"$",
"this",
"->",
"isModified",
"=",
"true",
";",
"$",
"this",
"->",
"parameters",
"[",
"'path'",
"]",
"=",
"'/'",
".",
"ltrim",
"(",
"$",
"path",
",",
"' /'",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Относительный путь к ресурсу внутри публичной папки.
@param string $path
@return $this | [
"Относительный",
"путь",
"к",
"ресурсу",
"внутри",
"публичной",
"папки",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Filter/RelativePathTrait.php#L30-L41 |
jack-theripper/yandex | src/Disk/Resource/Removed.php | Removed.toArray | public function toArray(array $allowed = null)
{
if ( ! $this->_toArray() || $this->isModified())
{
$response = $this->client->send((new Request($this->uri->withPath($this->uri->getPath().'trash/resources')
->withQuery(http_build_query(array_merge($this->getParameters($this->parametersAllowed), [
'path' => $this->getPath()
]), null, '&')), 'GET')));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if ( ! empty($response))
{
$this->isModified = false;
if (isset($response['_embedded']))
{
$response = array_merge($response, $response['_embedded']);
}
unset($response['_links'], $response['_embedded']);
if (isset($response['items']))
{
$response['items'] = new Container\Collection(array_map(function($item) {
return new self($item, $this->client, $this->uri);
}, $response['items']));
}
$this->setContents($response);
}
}
}
return $this->_toArray($allowed);
} | php | public function toArray(array $allowed = null)
{
if ( ! $this->_toArray() || $this->isModified())
{
$response = $this->client->send((new Request($this->uri->withPath($this->uri->getPath().'trash/resources')
->withQuery(http_build_query(array_merge($this->getParameters($this->parametersAllowed), [
'path' => $this->getPath()
]), null, '&')), 'GET')));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if ( ! empty($response))
{
$this->isModified = false;
if (isset($response['_embedded']))
{
$response = array_merge($response, $response['_embedded']);
}
unset($response['_links'], $response['_embedded']);
if (isset($response['items']))
{
$response['items'] = new Container\Collection(array_map(function($item) {
return new self($item, $this->client, $this->uri);
}, $response['items']));
}
$this->setContents($response);
}
}
}
return $this->_toArray($allowed);
} | [
"public",
"function",
"toArray",
"(",
"array",
"$",
"allowed",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_toArray",
"(",
")",
"||",
"$",
"this",
"->",
"isModified",
"(",
")",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'trash/resources'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"array_merge",
"(",
"$",
"this",
"->",
"getParameters",
"(",
"$",
"this",
"->",
"parametersAllowed",
")",
",",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
"]",
")",
",",
"null",
",",
"'&'",
")",
")",
",",
"'GET'",
")",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"response",
")",
")",
"{",
"$",
"this",
"->",
"isModified",
"=",
"false",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'_embedded'",
"]",
")",
")",
"{",
"$",
"response",
"=",
"array_merge",
"(",
"$",
"response",
",",
"$",
"response",
"[",
"'_embedded'",
"]",
")",
";",
"}",
"unset",
"(",
"$",
"response",
"[",
"'_links'",
"]",
",",
"$",
"response",
"[",
"'_embedded'",
"]",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'items'",
"]",
")",
")",
"{",
"$",
"response",
"[",
"'items'",
"]",
"=",
"new",
"Container",
"\\",
"Collection",
"(",
"array_map",
"(",
"function",
"(",
"$",
"item",
")",
"{",
"return",
"new",
"self",
"(",
"$",
"item",
",",
"$",
"this",
"->",
"client",
",",
"$",
"this",
"->",
"uri",
")",
";",
"}",
",",
"$",
"response",
"[",
"'items'",
"]",
")",
")",
";",
"}",
"$",
"this",
"->",
"setContents",
"(",
"$",
"response",
")",
";",
"}",
"}",
"}",
"return",
"$",
"this",
"->",
"_toArray",
"(",
"$",
"allowed",
")",
";",
"}"
] | Получает информацию о ресурсе
@return mixed | [
"Получает",
"информацию",
"о",
"ресурсе"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Removed.php#L77-L114 |
jack-theripper/yandex | src/Disk/Resource/Removed.php | Removed.restore | public function restore($name = null, $overwrite = false)
{
if (is_bool($name))
{
$overwrite = $name;
$name = null;
}
if ($name instanceof Closed)
{
$name = $name->getPath();
}
if ( ! empty($name) && ! is_string($name))
{
throw new \InvalidArgumentException('Новое имя для восстанавливаемого ресурса должо быть строкой');
}
$request = new Request($this->uri->withPath($this->uri->getPath().'trash/resources/restore')
->withQuery(http_build_query([
'path' => $this->getPath(),
'name' => (string) $name,
'overwrite' => (bool) $overwrite
], null, '&')), 'PUT');
$response = $this->client->send($request);
if ($response->getStatusCode() == 201 || $response->getStatusCode() == 202)
{
$this->setContents([]);
if ($response->getStatusCode() == 202)
{
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
}
return $this->client->getResource($name);
}
return false;
} | php | public function restore($name = null, $overwrite = false)
{
if (is_bool($name))
{
$overwrite = $name;
$name = null;
}
if ($name instanceof Closed)
{
$name = $name->getPath();
}
if ( ! empty($name) && ! is_string($name))
{
throw new \InvalidArgumentException('Новое имя для восстанавливаемого ресурса должо быть строкой');
}
$request = new Request($this->uri->withPath($this->uri->getPath().'trash/resources/restore')
->withQuery(http_build_query([
'path' => $this->getPath(),
'name' => (string) $name,
'overwrite' => (bool) $overwrite
], null, '&')), 'PUT');
$response = $this->client->send($request);
if ($response->getStatusCode() == 201 || $response->getStatusCode() == 202)
{
$this->setContents([]);
if ($response->getStatusCode() == 202)
{
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
}
return $this->client->getResource($name);
}
return false;
} | [
"public",
"function",
"restore",
"(",
"$",
"name",
"=",
"null",
",",
"$",
"overwrite",
"=",
"false",
")",
"{",
"if",
"(",
"is_bool",
"(",
"$",
"name",
")",
")",
"{",
"$",
"overwrite",
"=",
"$",
"name",
";",
"$",
"name",
"=",
"null",
";",
"}",
"if",
"(",
"$",
"name",
"instanceof",
"Closed",
")",
"{",
"$",
"name",
"=",
"$",
"name",
"->",
"getPath",
"(",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"name",
")",
"&&",
"!",
"is_string",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Новое имя для восстанавливаемого ресурса должо быть строкой');",
"",
"",
"}",
"$",
"request",
"=",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'trash/resources/restore'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
",",
"'name'",
"=>",
"(",
"string",
")",
"$",
"name",
",",
"'overwrite'",
"=>",
"(",
"bool",
")",
"$",
"overwrite",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'PUT'",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"$",
"request",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"201",
"||",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"202",
")",
"{",
"$",
"this",
"->",
"setContents",
"(",
"[",
"]",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"202",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
")",
"{",
"$",
"response",
"[",
"'operation'",
"]",
"=",
"$",
"this",
"->",
"client",
"->",
"getOperation",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"$",
"this",
"->",
"client",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"return",
"$",
"response",
"[",
"'operation'",
"]",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"client",
"->",
"getResource",
"(",
"$",
"name",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Восстановление файла или папки из Корзины
В корзине файлы с одинаковыми именами в действительности именют постфикс к имени в виде unixtime
@param mixed $name оставляет имя как есть и если boolean это заменяет overwrite
@param boolean $overwrite
@return mixed | [
"Восстановление",
"файла",
"или",
"папки",
"из",
"Корзины",
"В",
"корзине",
"файлы",
"с",
"одинаковыми",
"именами",
"в",
"действительности",
"именют",
"постфикс",
"к",
"имени",
"в",
"виде",
"unixtime"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Removed.php#L124-L173 |
jack-theripper/yandex | src/Disk/Resource/Opened.php | Opened.download | public function download($destination, $overwrite = false, $check_hash = false)
{
$destination_type = gettype($destination);
if (is_resource($destination))
{
$destination = new Stream($destination);
}
if ($destination instanceof StreamInterface)
{
if ( ! $destination->isWritable())
{
throw new \OutOfBoundsException('Дескриптор файла должен быть открыт с правами на запись.');
}
}
else if ($destination_type == 'string')
{
if (is_file($destination) && ! $overwrite)
{
throw new AlreadyExistsException('По указанному пути "'.$destination.'" уже существует ресурс.');
}
if ( ! is_writable(dirname($destination)))
{
throw new \OutOfBoundsException('Запрещена запись в директорию, в которой должен быть расположен файл.');
}
$destination = new Stream($destination, 'w+b');
}
else
{
throw new \InvalidArgumentException('Такой тип параметра $destination не поддерживается.');
}
$response = $this->client->send(new Request($this->getLink(), 'GET'));
if ($response->getStatusCode() == 200)
{
$stream = $response->getBody();
if ($check_hash)
{
$ctx = hash_init('md5');
while ( ! $stream->eof())
{
$read_data = $stream->read(1048576);
$destination->write($read_data);
hash_update($ctx, $read_data);
}
}
else
{
while ( ! $stream->eof())
{
$destination->write($stream->read(16384));
}
}
$stream->close();
$this->emit('downloaded', $this, $destination, $this->client);
$this->client->emit('downloaded', $this, $destination, $this->client);
if ($destination_type == 'object')
{
return $destination;
}
else if ($check_hash && $destination_type == 'string' && $this->isFile())
{
if (hash_final($ctx, false) !== $this->get('md5', null))
{
throw new \RangeException('Ресурс скачан, но контрольные суммы различаются.');
}
}
return $destination->getSize();
}
return false;
} | php | public function download($destination, $overwrite = false, $check_hash = false)
{
$destination_type = gettype($destination);
if (is_resource($destination))
{
$destination = new Stream($destination);
}
if ($destination instanceof StreamInterface)
{
if ( ! $destination->isWritable())
{
throw new \OutOfBoundsException('Дескриптор файла должен быть открыт с правами на запись.');
}
}
else if ($destination_type == 'string')
{
if (is_file($destination) && ! $overwrite)
{
throw new AlreadyExistsException('По указанному пути "'.$destination.'" уже существует ресурс.');
}
if ( ! is_writable(dirname($destination)))
{
throw new \OutOfBoundsException('Запрещена запись в директорию, в которой должен быть расположен файл.');
}
$destination = new Stream($destination, 'w+b');
}
else
{
throw new \InvalidArgumentException('Такой тип параметра $destination не поддерживается.');
}
$response = $this->client->send(new Request($this->getLink(), 'GET'));
if ($response->getStatusCode() == 200)
{
$stream = $response->getBody();
if ($check_hash)
{
$ctx = hash_init('md5');
while ( ! $stream->eof())
{
$read_data = $stream->read(1048576);
$destination->write($read_data);
hash_update($ctx, $read_data);
}
}
else
{
while ( ! $stream->eof())
{
$destination->write($stream->read(16384));
}
}
$stream->close();
$this->emit('downloaded', $this, $destination, $this->client);
$this->client->emit('downloaded', $this, $destination, $this->client);
if ($destination_type == 'object')
{
return $destination;
}
else if ($check_hash && $destination_type == 'string' && $this->isFile())
{
if (hash_final($ctx, false) !== $this->get('md5', null))
{
throw new \RangeException('Ресурс скачан, но контрольные суммы различаются.');
}
}
return $destination->getSize();
}
return false;
} | [
"public",
"function",
"download",
"(",
"$",
"destination",
",",
"$",
"overwrite",
"=",
"false",
",",
"$",
"check_hash",
"=",
"false",
")",
"{",
"$",
"destination_type",
"=",
"gettype",
"(",
"$",
"destination",
")",
";",
"if",
"(",
"is_resource",
"(",
"$",
"destination",
")",
")",
"{",
"$",
"destination",
"=",
"new",
"Stream",
"(",
"$",
"destination",
")",
";",
"}",
"if",
"(",
"$",
"destination",
"instanceof",
"StreamInterface",
")",
"{",
"if",
"(",
"!",
"$",
"destination",
"->",
"isWritable",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"OutOfBoundsException",
"(",
"'Дескриптор файла должен быть открыт с правами на запись.');",
"",
"",
"}",
"}",
"else",
"if",
"(",
"$",
"destination_type",
"==",
"'string'",
")",
"{",
"if",
"(",
"is_file",
"(",
"$",
"destination",
")",
"&&",
"!",
"$",
"overwrite",
")",
"{",
"throw",
"new",
"AlreadyExistsException",
"(",
"'По указанному пути \"'.$destination.'\"",
" ",
"у",
"же существу",
"е",
"т ресурс.');",
"",
"",
"}",
"if",
"(",
"!",
"is_writable",
"(",
"dirname",
"(",
"$",
"destination",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"OutOfBoundsException",
"(",
"'Запрещена запись в директорию, в которой должен быть расположен файл.');",
"",
"",
"}",
"$",
"destination",
"=",
"new",
"Stream",
"(",
"$",
"destination",
",",
"'w+b'",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Такой тип параметра $destination не поддерживается.');",
"",
"",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"getLink",
"(",
")",
",",
"'GET'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"stream",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"if",
"(",
"$",
"check_hash",
")",
"{",
"$",
"ctx",
"=",
"hash_init",
"(",
"'md5'",
")",
";",
"while",
"(",
"!",
"$",
"stream",
"->",
"eof",
"(",
")",
")",
"{",
"$",
"read_data",
"=",
"$",
"stream",
"->",
"read",
"(",
"1048576",
")",
";",
"$",
"destination",
"->",
"write",
"(",
"$",
"read_data",
")",
";",
"hash_update",
"(",
"$",
"ctx",
",",
"$",
"read_data",
")",
";",
"}",
"}",
"else",
"{",
"while",
"(",
"!",
"$",
"stream",
"->",
"eof",
"(",
")",
")",
"{",
"$",
"destination",
"->",
"write",
"(",
"$",
"stream",
"->",
"read",
"(",
"16384",
")",
")",
";",
"}",
"}",
"$",
"stream",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'downloaded'",
",",
"$",
"this",
",",
"$",
"destination",
",",
"$",
"this",
"->",
"client",
")",
";",
"$",
"this",
"->",
"client",
"->",
"emit",
"(",
"'downloaded'",
",",
"$",
"this",
",",
"$",
"destination",
",",
"$",
"this",
"->",
"client",
")",
";",
"if",
"(",
"$",
"destination_type",
"==",
"'object'",
")",
"{",
"return",
"$",
"destination",
";",
"}",
"else",
"if",
"(",
"$",
"check_hash",
"&&",
"$",
"destination_type",
"==",
"'string'",
"&&",
"$",
"this",
"->",
"isFile",
"(",
")",
")",
"{",
"if",
"(",
"hash_final",
"(",
"$",
"ctx",
",",
"false",
")",
"!==",
"$",
"this",
"->",
"get",
"(",
"'md5'",
",",
"null",
")",
")",
"{",
"throw",
"new",
"\\",
"RangeException",
"(",
"'Ресурс скачан, но контрольные суммы различаются.');",
"",
"",
"}",
"}",
"return",
"$",
"destination",
"->",
"getSize",
"(",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Скачивание публичного файла или папки
@param resource|StreamInterface|string $destination Путь, по которому будет сохранён файл
StreamInterface будет записан в поток
resource открытый на запись
@param boolean $overwrite флаг перезаписи
@param boolean $check_hash провести проверку целостности скачанного файла
на основе хэша MD5
@return bool | [
"Скачивание",
"публичного",
"файла",
"или",
"папки"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Opened.php#L182-L263 |
jack-theripper/yandex | src/Disk/Resource/Opened.php | Opened.hasEqual | public function hasEqual()
{
if ($this->has() && ($path = $this->get('name')))
{
try
{
return $this->client->getResource(((string) $this->get('path')).'/'.$path)
->get('md5', false) === $this->get('md5');
}
catch (\Exception $exc)
{
}
}
return false;
} | php | public function hasEqual()
{
if ($this->has() && ($path = $this->get('name')))
{
try
{
return $this->client->getResource(((string) $this->get('path')).'/'.$path)
->get('md5', false) === $this->get('md5');
}
catch (\Exception $exc)
{
}
}
return false;
} | [
"public",
"function",
"hasEqual",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"has",
"(",
")",
"&&",
"(",
"$",
"path",
"=",
"$",
"this",
"->",
"get",
"(",
"'name'",
")",
")",
")",
"{",
"try",
"{",
"return",
"$",
"this",
"->",
"client",
"->",
"getResource",
"(",
"(",
"(",
"string",
")",
"$",
"this",
"->",
"get",
"(",
"'path'",
")",
")",
".",
"'/'",
".",
"$",
"path",
")",
"->",
"get",
"(",
"'md5'",
",",
"false",
")",
"===",
"$",
"this",
"->",
"get",
"(",
"'md5'",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"exc",
")",
"{",
"}",
"}",
"return",
"false",
";",
"}"
] | Этот файл или такой же находится на моём диске
Метод требует Access Token
@return boolean | [
"Этот",
"файл",
"или",
"такой",
"же",
"находится",
"на",
"моём",
"диске",
"Метод",
"требует",
"Access",
"Token"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Opened.php#L271-L287 |
jack-theripper/yandex | src/Disk/Resource/Opened.php | Opened.save | public function save($name = null, $path = null)
{
$parameters = [];
/**
* @var mixed $name Имя, под которым файл следует сохранить в папку «Загрузки»
*/
if (is_string($name))
{
$parameters['name'] = $name;
}
else if ($name instanceof Closed)
{
$parameters['name'] = substr(strrchr($name->getPath(), '/'), 1);
}
/**
* @var string $path (необязательный)
* Путь внутри публичной папки. Следует указать, если в значении параметра public_key передан
* ключ публичной папки, в которой находится нужный файл.
* Путь в значении параметра следует кодировать в URL-формате.
*/
if (is_string($path))
{
$parameters['path'] = $path;
}
else if ($this->getPath() !== null)
{
$parameters['path'] = $this->getPath();
}
/**
* Если к моменту ответа запрос удалось обработать без ошибок, API отвечает кодом 201 Created и возвращает
* ссылку на сохраненный файл в теле ответа (в объекте Link).
* Если операция сохранения была запущена, но еще не завершилась, Яндекс.Диск отвечает кодом 202 Accepted.
*/
$response = $this->client->send((new Request($this->uri->withPath($this->uri->getPath()
.'public/resources/save-to-disk')
->withQuery(http_build_query([
'public_key' => $this->getPublicKey()
] + $parameters, null, '&')), 'POST')));
if ($response->getStatusCode() == 202 || $response->getStatusCode() == 201)
{
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
if (isset($response['href']))
{
parse_str((new Uri($response['href']))->getQuery(), $path);
if (isset($path['path']))
{
return $this->client->getResource($path['path']);
}
}
}
return false;
} | php | public function save($name = null, $path = null)
{
$parameters = [];
/**
* @var mixed $name Имя, под которым файл следует сохранить в папку «Загрузки»
*/
if (is_string($name))
{
$parameters['name'] = $name;
}
else if ($name instanceof Closed)
{
$parameters['name'] = substr(strrchr($name->getPath(), '/'), 1);
}
/**
* @var string $path (необязательный)
* Путь внутри публичной папки. Следует указать, если в значении параметра public_key передан
* ключ публичной папки, в которой находится нужный файл.
* Путь в значении параметра следует кодировать в URL-формате.
*/
if (is_string($path))
{
$parameters['path'] = $path;
}
else if ($this->getPath() !== null)
{
$parameters['path'] = $this->getPath();
}
/**
* Если к моменту ответа запрос удалось обработать без ошибок, API отвечает кодом 201 Created и возвращает
* ссылку на сохраненный файл в теле ответа (в объекте Link).
* Если операция сохранения была запущена, но еще не завершилась, Яндекс.Диск отвечает кодом 202 Accepted.
*/
$response = $this->client->send((new Request($this->uri->withPath($this->uri->getPath()
.'public/resources/save-to-disk')
->withQuery(http_build_query([
'public_key' => $this->getPublicKey()
] + $parameters, null, '&')), 'POST')));
if ($response->getStatusCode() == 202 || $response->getStatusCode() == 201)
{
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
if (isset($response['href']))
{
parse_str((new Uri($response['href']))->getQuery(), $path);
if (isset($path['path']))
{
return $this->client->getResource($path['path']);
}
}
}
return false;
} | [
"public",
"function",
"save",
"(",
"$",
"name",
"=",
"null",
",",
"$",
"path",
"=",
"null",
")",
"{",
"$",
"parameters",
"=",
"[",
"]",
";",
"/**\n\t\t * @var mixed $name Имя, под которым файл следует сохранить в папку «Загрузки»\n\t\t */",
"if",
"(",
"is_string",
"(",
"$",
"name",
")",
")",
"{",
"$",
"parameters",
"[",
"'name'",
"]",
"=",
"$",
"name",
";",
"}",
"else",
"if",
"(",
"$",
"name",
"instanceof",
"Closed",
")",
"{",
"$",
"parameters",
"[",
"'name'",
"]",
"=",
"substr",
"(",
"strrchr",
"(",
"$",
"name",
"->",
"getPath",
"(",
")",
",",
"'/'",
")",
",",
"1",
")",
";",
"}",
"/**\n\t\t * @var string $path (необязательный)\n\t\t * Путь внутри публичной папки. Следует указать, если в значении параметра public_key передан\n\t\t * ключ публичной папки, в которой находится нужный файл.\n\t\t * Путь в значении параметра следует кодировать в URL-формате.\n\t\t */",
"if",
"(",
"is_string",
"(",
"$",
"path",
")",
")",
"{",
"$",
"parameters",
"[",
"'path'",
"]",
"=",
"$",
"path",
";",
"}",
"else",
"if",
"(",
"$",
"this",
"->",
"getPath",
"(",
")",
"!==",
"null",
")",
"{",
"$",
"parameters",
"[",
"'path'",
"]",
"=",
"$",
"this",
"->",
"getPath",
"(",
")",
";",
"}",
"/**\n\t\t * Если к моменту ответа запрос удалось обработать без ошибок, API отвечает кодом 201 Created и возвращает\n\t\t * ссылку на сохраненный файл в теле ответа (в объекте Link).\n\t\t * Если операция сохранения была запущена, но еще не завершилась, Яндекс.Диск отвечает кодом 202 Accepted.\n\t\t */",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'public/resources/save-to-disk'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'public_key'",
"=>",
"$",
"this",
"->",
"getPublicKey",
"(",
")",
"]",
"+",
"$",
"parameters",
",",
"null",
",",
"'&'",
")",
")",
",",
"'POST'",
")",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"202",
"||",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"201",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
")",
"{",
"$",
"response",
"[",
"'operation'",
"]",
"=",
"$",
"this",
"->",
"client",
"->",
"getOperation",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"$",
"this",
"->",
"client",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"return",
"$",
"response",
"[",
"'operation'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'href'",
"]",
")",
")",
"{",
"parse_str",
"(",
"(",
"new",
"Uri",
"(",
"$",
"response",
"[",
"'href'",
"]",
")",
")",
"->",
"getQuery",
"(",
")",
",",
"$",
"path",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"path",
"[",
"'path'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"client",
"->",
"getResource",
"(",
"$",
"path",
"[",
"'path'",
"]",
")",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] | Сохранение публичного файла в «Загрузки» или отдельный файл из публичной папки
@param string $name Имя, под которым файл следует сохранить в папку «Загрузки»
@param string $path Путь внутри публичной папки.
@return mixed | [
"Сохранение",
"публичного",
"файла",
"в",
"«Загрузки»",
"или",
"отдельный",
"файл",
"из",
"публичной",
"папки"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Opened.php#L297-L364 |
jack-theripper/yandex | src/Disk/Resource/Opened.php | Opened.setPath | public function setPath($path)
{
if ( ! is_scalar($path))
{
throw new \InvalidArgumentException('Параметр "path" должен быть строкового типа.');
}
$this->path = (string) $path;
return $this;
} | php | public function setPath($path)
{
if ( ! is_scalar($path))
{
throw new \InvalidArgumentException('Параметр "path" должен быть строкового типа.');
}
$this->path = (string) $path;
return $this;
} | [
"public",
"function",
"setPath",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Параметр \"path\" должен быть строкового типа.');",
"",
"",
"}",
"$",
"this",
"->",
"path",
"=",
"(",
"string",
")",
"$",
"path",
";",
"return",
"$",
"this",
";",
"}"
] | Устанавливает путь внутри публичной папки
@param string $path
@return $this | [
"Устанавливает",
"путь",
"внутри",
"публичной",
"папки"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Opened.php#L373-L383 |
jack-theripper/yandex | src/Disk/Resource/Opened.php | Opened.createDocViewerUrl | protected function createDocViewerUrl()
{
if ($this->isFile())
{
$docviewer = [
'name' => $this->get('name'),
'url' => sprintf('ya-disk-public://%s', $this->get('public_key'))
];
return (string) (new Uri('https://docviewer.yandex.ru/'))
->withQuery(http_build_query($docviewer, null, '&'));
}
return false;
} | php | protected function createDocViewerUrl()
{
if ($this->isFile())
{
$docviewer = [
'name' => $this->get('name'),
'url' => sprintf('ya-disk-public://%s', $this->get('public_key'))
];
return (string) (new Uri('https://docviewer.yandex.ru/'))
->withQuery(http_build_query($docviewer, null, '&'));
}
return false;
} | [
"protected",
"function",
"createDocViewerUrl",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isFile",
"(",
")",
")",
"{",
"$",
"docviewer",
"=",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"get",
"(",
"'name'",
")",
",",
"'url'",
"=>",
"sprintf",
"(",
"'ya-disk-public://%s'",
",",
"$",
"this",
"->",
"get",
"(",
"'public_key'",
")",
")",
"]",
";",
"return",
"(",
"string",
")",
"(",
"new",
"Uri",
"(",
"'https://docviewer.yandex.ru/'",
")",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"$",
"docviewer",
",",
"null",
",",
"'&'",
")",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Получает ссылку для просмотра документа.
@return bool|string
@throws \InvalidArgumentException | [
"Получает",
"ссылку",
"для",
"просмотра",
"документа",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Opened.php#L391-L405 |
jack-theripper/yandex | src/Disk/Resource/Collection.php | Collection.toArray | public function toArray(array $allowed = null)
{
if ( ! parent::toArray() || $this->isModified())
{
$this->setContents(call_user_func($this->closure, $this->getParameters($this->parametersAllowed)));
$this->isModified = false;
}
return parent::toArray();
} | php | public function toArray(array $allowed = null)
{
if ( ! parent::toArray() || $this->isModified())
{
$this->setContents(call_user_func($this->closure, $this->getParameters($this->parametersAllowed)));
$this->isModified = false;
}
return parent::toArray();
} | [
"public",
"function",
"toArray",
"(",
"array",
"$",
"allowed",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"parent",
"::",
"toArray",
"(",
")",
"||",
"$",
"this",
"->",
"isModified",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setContents",
"(",
"call_user_func",
"(",
"$",
"this",
"->",
"closure",
",",
"$",
"this",
"->",
"getParameters",
"(",
"$",
"this",
"->",
"parametersAllowed",
")",
")",
")",
";",
"$",
"this",
"->",
"isModified",
"=",
"false",
";",
"}",
"return",
"parent",
"::",
"toArray",
"(",
")",
";",
"}"
] | Получает информацию
@return array | [
"Получает",
"информацию"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Collection.php#L52-L61 |
jack-theripper/yandex | src/Client/HttpClient.php | HttpClient.sendRequest | public function sendRequest(RequestInterface $request)
{
$responseBuilder = $this->createResponseBuilder();
$options = $this->createCurlOptions($request, $responseBuilder);
curl_reset($this->handle);
curl_setopt_array($this->handle, $options);
curl_exec($this->handle);
if (curl_errno($this->handle) > 0) {
throw new RequestException(curl_error($this->handle), $request);
}
$response = $responseBuilder->getResponse();
$response->getBody()->seek(0);
return $response;
} | php | public function sendRequest(RequestInterface $request)
{
$responseBuilder = $this->createResponseBuilder();
$options = $this->createCurlOptions($request, $responseBuilder);
curl_reset($this->handle);
curl_setopt_array($this->handle, $options);
curl_exec($this->handle);
if (curl_errno($this->handle) > 0) {
throw new RequestException(curl_error($this->handle), $request);
}
$response = $responseBuilder->getResponse();
$response->getBody()->seek(0);
return $response;
} | [
"public",
"function",
"sendRequest",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"$",
"responseBuilder",
"=",
"$",
"this",
"->",
"createResponseBuilder",
"(",
")",
";",
"$",
"options",
"=",
"$",
"this",
"->",
"createCurlOptions",
"(",
"$",
"request",
",",
"$",
"responseBuilder",
")",
";",
"curl_reset",
"(",
"$",
"this",
"->",
"handle",
")",
";",
"curl_setopt_array",
"(",
"$",
"this",
"->",
"handle",
",",
"$",
"options",
")",
";",
"curl_exec",
"(",
"$",
"this",
"->",
"handle",
")",
";",
"if",
"(",
"curl_errno",
"(",
"$",
"this",
"->",
"handle",
")",
">",
"0",
")",
"{",
"throw",
"new",
"RequestException",
"(",
"curl_error",
"(",
"$",
"this",
"->",
"handle",
")",
",",
"$",
"request",
")",
";",
"}",
"$",
"response",
"=",
"$",
"responseBuilder",
"->",
"getResponse",
"(",
")",
";",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"seek",
"(",
"0",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Sends a PSR-7 request.
@param RequestInterface $request
@return ResponseInterface
@throws \RuntimeException If creating the body stream fails.
@throws \UnexpectedValueException if unsupported HTTP version requested
@throws RequestException
@since 1.0 | [
"Sends",
"a",
"PSR",
"-",
"7",
"request",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/HttpClient.php#L116-L133 |
jack-theripper/yandex | src/Client/HttpClient.php | HttpClient.createCurlOptions | protected function createCurlOptions(RequestInterface $request, ResponseBuilder $responseBuilder)
{
$options = array_diff_key($this->options, array_flip([CURLOPT_INFILE, CURLOPT_INFILESIZE]));
$options[CURLOPT_HTTP_VERSION] = $this->getCurlHttpVersion($request->getProtocolVersion());
$options[CURLOPT_HEADERFUNCTION] = function ($ch, $data) use ($responseBuilder) {
$str = trim($data);
if ('' !== $str)
{
if (strpos(strtolower($str), 'http/') === 0)
{
$responseBuilder->setStatus($str)->getResponse();
}
else
{
$responseBuilder->addHeader($str);
}
}
return strlen($data);
};
$options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
$options[CURLOPT_URL] = (string) $request->getUri();
$options[CURLOPT_HEADER] = false;
if (in_array($request->getMethod(), ['GET', 'HEAD', 'TRACE', 'CONNECT']))
{
if ($request->getMethod() == 'HEAD')
{
$options[CURLOPT_NOBODY] = true;
unset($options[CURLOPT_READFUNCTION], $options[CURLOPT_WRITEFUNCTION]);
}
}
else
{
$options = $this->createCurlBody($request, $options);
}
$options[CURLOPT_WRITEFUNCTION] = function ($ch, $data) use ($responseBuilder) {
return $responseBuilder->getResponse()->getBody()->write($data);
};
$options[CURLOPT_HTTPHEADER] = $this->createHeaders($request, $options);
if ($request->getUri()->getUserInfo())
{
$options[CURLOPT_USERPWD] = $request->getUri()->getUserInfo();
}
$options[CURLOPT_FOLLOWLOCATION] = false;
return $options;
} | php | protected function createCurlOptions(RequestInterface $request, ResponseBuilder $responseBuilder)
{
$options = array_diff_key($this->options, array_flip([CURLOPT_INFILE, CURLOPT_INFILESIZE]));
$options[CURLOPT_HTTP_VERSION] = $this->getCurlHttpVersion($request->getProtocolVersion());
$options[CURLOPT_HEADERFUNCTION] = function ($ch, $data) use ($responseBuilder) {
$str = trim($data);
if ('' !== $str)
{
if (strpos(strtolower($str), 'http/') === 0)
{
$responseBuilder->setStatus($str)->getResponse();
}
else
{
$responseBuilder->addHeader($str);
}
}
return strlen($data);
};
$options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
$options[CURLOPT_URL] = (string) $request->getUri();
$options[CURLOPT_HEADER] = false;
if (in_array($request->getMethod(), ['GET', 'HEAD', 'TRACE', 'CONNECT']))
{
if ($request->getMethod() == 'HEAD')
{
$options[CURLOPT_NOBODY] = true;
unset($options[CURLOPT_READFUNCTION], $options[CURLOPT_WRITEFUNCTION]);
}
}
else
{
$options = $this->createCurlBody($request, $options);
}
$options[CURLOPT_WRITEFUNCTION] = function ($ch, $data) use ($responseBuilder) {
return $responseBuilder->getResponse()->getBody()->write($data);
};
$options[CURLOPT_HTTPHEADER] = $this->createHeaders($request, $options);
if ($request->getUri()->getUserInfo())
{
$options[CURLOPT_USERPWD] = $request->getUri()->getUserInfo();
}
$options[CURLOPT_FOLLOWLOCATION] = false;
return $options;
} | [
"protected",
"function",
"createCurlOptions",
"(",
"RequestInterface",
"$",
"request",
",",
"ResponseBuilder",
"$",
"responseBuilder",
")",
"{",
"$",
"options",
"=",
"array_diff_key",
"(",
"$",
"this",
"->",
"options",
",",
"array_flip",
"(",
"[",
"CURLOPT_INFILE",
",",
"CURLOPT_INFILESIZE",
"]",
")",
")",
";",
"$",
"options",
"[",
"CURLOPT_HTTP_VERSION",
"]",
"=",
"$",
"this",
"->",
"getCurlHttpVersion",
"(",
"$",
"request",
"->",
"getProtocolVersion",
"(",
")",
")",
";",
"$",
"options",
"[",
"CURLOPT_HEADERFUNCTION",
"]",
"=",
"function",
"(",
"$",
"ch",
",",
"$",
"data",
")",
"use",
"(",
"$",
"responseBuilder",
")",
"{",
"$",
"str",
"=",
"trim",
"(",
"$",
"data",
")",
";",
"if",
"(",
"''",
"!==",
"$",
"str",
")",
"{",
"if",
"(",
"strpos",
"(",
"strtolower",
"(",
"$",
"str",
")",
",",
"'http/'",
")",
"===",
"0",
")",
"{",
"$",
"responseBuilder",
"->",
"setStatus",
"(",
"$",
"str",
")",
"->",
"getResponse",
"(",
")",
";",
"}",
"else",
"{",
"$",
"responseBuilder",
"->",
"addHeader",
"(",
"$",
"str",
")",
";",
"}",
"}",
"return",
"strlen",
"(",
"$",
"data",
")",
";",
"}",
";",
"$",
"options",
"[",
"CURLOPT_CUSTOMREQUEST",
"]",
"=",
"$",
"request",
"->",
"getMethod",
"(",
")",
";",
"$",
"options",
"[",
"CURLOPT_URL",
"]",
"=",
"(",
"string",
")",
"$",
"request",
"->",
"getUri",
"(",
")",
";",
"$",
"options",
"[",
"CURLOPT_HEADER",
"]",
"=",
"false",
";",
"if",
"(",
"in_array",
"(",
"$",
"request",
"->",
"getMethod",
"(",
")",
",",
"[",
"'GET'",
",",
"'HEAD'",
",",
"'TRACE'",
",",
"'CONNECT'",
"]",
")",
")",
"{",
"if",
"(",
"$",
"request",
"->",
"getMethod",
"(",
")",
"==",
"'HEAD'",
")",
"{",
"$",
"options",
"[",
"CURLOPT_NOBODY",
"]",
"=",
"true",
";",
"unset",
"(",
"$",
"options",
"[",
"CURLOPT_READFUNCTION",
"]",
",",
"$",
"options",
"[",
"CURLOPT_WRITEFUNCTION",
"]",
")",
";",
"}",
"}",
"else",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"createCurlBody",
"(",
"$",
"request",
",",
"$",
"options",
")",
";",
"}",
"$",
"options",
"[",
"CURLOPT_WRITEFUNCTION",
"]",
"=",
"function",
"(",
"$",
"ch",
",",
"$",
"data",
")",
"use",
"(",
"$",
"responseBuilder",
")",
"{",
"return",
"$",
"responseBuilder",
"->",
"getResponse",
"(",
")",
"->",
"getBody",
"(",
")",
"->",
"write",
"(",
"$",
"data",
")",
";",
"}",
";",
"$",
"options",
"[",
"CURLOPT_HTTPHEADER",
"]",
"=",
"$",
"this",
"->",
"createHeaders",
"(",
"$",
"request",
",",
"$",
"options",
")",
";",
"if",
"(",
"$",
"request",
"->",
"getUri",
"(",
")",
"->",
"getUserInfo",
"(",
")",
")",
"{",
"$",
"options",
"[",
"CURLOPT_USERPWD",
"]",
"=",
"$",
"request",
"->",
"getUri",
"(",
")",
"->",
"getUserInfo",
"(",
")",
";",
"}",
"$",
"options",
"[",
"CURLOPT_FOLLOWLOCATION",
"]",
"=",
"false",
";",
"return",
"$",
"options",
";",
"}"
] | Generates cURL options
@param RequestInterface $request
@param ResponseBuilder $responseBuilder
@throws \UnexpectedValueException if unsupported HTTP version requested
@throws \RuntimeException if can not read body
@return array | [
"Generates",
"cURL",
"options"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/HttpClient.php#L178-L232 |
jack-theripper/yandex | src/Client/HttpClient.php | HttpClient.createHeaders | protected function createHeaders(RequestInterface $request, array $options)
{
$headers = [];
$body = $request->getBody();
$size = $body->getSize();
foreach ($request->getHeaders() as $header => $values)
{
foreach ((array) $values as $value)
{
$headers[] = sprintf('%s: %s', $header, $value);
}
}
if ( ! $request->hasHeader('Transfer-Encoding') && $size === null)
{
$headers[] = 'Transfer-Encoding: chunked';
}
if ( ! $request->hasHeader('Expect') && in_array($request->getMethod(), ['POST', 'PUT']))
{
if ($request->getProtocolVersion() < 2.0 && ! $body->isSeekable() || $size === null || $size > 1048576)
{
$headers[] = 'Expect: 100-Continue';
}
else
{
$headers[] = 'Expect: ';
}
}
return $headers;
} | php | protected function createHeaders(RequestInterface $request, array $options)
{
$headers = [];
$body = $request->getBody();
$size = $body->getSize();
foreach ($request->getHeaders() as $header => $values)
{
foreach ((array) $values as $value)
{
$headers[] = sprintf('%s: %s', $header, $value);
}
}
if ( ! $request->hasHeader('Transfer-Encoding') && $size === null)
{
$headers[] = 'Transfer-Encoding: chunked';
}
if ( ! $request->hasHeader('Expect') && in_array($request->getMethod(), ['POST', 'PUT']))
{
if ($request->getProtocolVersion() < 2.0 && ! $body->isSeekable() || $size === null || $size > 1048576)
{
$headers[] = 'Expect: 100-Continue';
}
else
{
$headers[] = 'Expect: ';
}
}
return $headers;
} | [
"protected",
"function",
"createHeaders",
"(",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
"options",
")",
"{",
"$",
"headers",
"=",
"[",
"]",
";",
"$",
"body",
"=",
"$",
"request",
"->",
"getBody",
"(",
")",
";",
"$",
"size",
"=",
"$",
"body",
"->",
"getSize",
"(",
")",
";",
"foreach",
"(",
"$",
"request",
"->",
"getHeaders",
"(",
")",
"as",
"$",
"header",
"=>",
"$",
"values",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"values",
"as",
"$",
"value",
")",
"{",
"$",
"headers",
"[",
"]",
"=",
"sprintf",
"(",
"'%s: %s'",
",",
"$",
"header",
",",
"$",
"value",
")",
";",
"}",
"}",
"if",
"(",
"!",
"$",
"request",
"->",
"hasHeader",
"(",
"'Transfer-Encoding'",
")",
"&&",
"$",
"size",
"===",
"null",
")",
"{",
"$",
"headers",
"[",
"]",
"=",
"'Transfer-Encoding: chunked'",
";",
"}",
"if",
"(",
"!",
"$",
"request",
"->",
"hasHeader",
"(",
"'Expect'",
")",
"&&",
"in_array",
"(",
"$",
"request",
"->",
"getMethod",
"(",
")",
",",
"[",
"'POST'",
",",
"'PUT'",
"]",
")",
")",
"{",
"if",
"(",
"$",
"request",
"->",
"getProtocolVersion",
"(",
")",
"<",
"2.0",
"&&",
"!",
"$",
"body",
"->",
"isSeekable",
"(",
")",
"||",
"$",
"size",
"===",
"null",
"||",
"$",
"size",
">",
"1048576",
")",
"{",
"$",
"headers",
"[",
"]",
"=",
"'Expect: 100-Continue'",
";",
"}",
"else",
"{",
"$",
"headers",
"[",
"]",
"=",
"'Expect: '",
";",
"}",
"}",
"return",
"$",
"headers",
";",
"}"
] | Create headers array for CURLOPT_HTTPHEADER
@param RequestInterface $request
@param array $options cURL options
@return string[] | [
"Create",
"headers",
"array",
"for",
"CURLOPT_HTTPHEADER"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/HttpClient.php#L242-L274 |
jack-theripper/yandex | src/Client/HttpClient.php | HttpClient.createCurlBody | protected function createCurlBody(RequestInterface $request, array $options)
{
$body = clone $request->getBody();
$size = $body->getSize();
// Avoid full loading large or unknown size body into memory. It doesn't replace "CURLOPT_READFUNCTION".
if ($size === null || $size > 1048576)
{
if ($body->isSeekable())
{
$body->rewind();
}
$options[CURLOPT_UPLOAD] = true;
if (isset($options[CURLOPT_READFUNCTION]) && is_callable($options[CURLOPT_READFUNCTION]))
{
$body = $body->detach();
$options[CURLOPT_READFUNCTION] = function($curl_handler, $handler, $length) use ($body, $options) {
return call_user_func($options[CURLOPT_READFUNCTION], $curl_handler, $body, $length);
};
}
else
{
$options[CURLOPT_READFUNCTION] = function($curl, $handler, $length) use ($body) {
return $body->read($length);
};
}
}
else
{
$options[CURLOPT_POSTFIELDS] = (string) $request->getBody();
}
return $options;
} | php | protected function createCurlBody(RequestInterface $request, array $options)
{
$body = clone $request->getBody();
$size = $body->getSize();
// Avoid full loading large or unknown size body into memory. It doesn't replace "CURLOPT_READFUNCTION".
if ($size === null || $size > 1048576)
{
if ($body->isSeekable())
{
$body->rewind();
}
$options[CURLOPT_UPLOAD] = true;
if (isset($options[CURLOPT_READFUNCTION]) && is_callable($options[CURLOPT_READFUNCTION]))
{
$body = $body->detach();
$options[CURLOPT_READFUNCTION] = function($curl_handler, $handler, $length) use ($body, $options) {
return call_user_func($options[CURLOPT_READFUNCTION], $curl_handler, $body, $length);
};
}
else
{
$options[CURLOPT_READFUNCTION] = function($curl, $handler, $length) use ($body) {
return $body->read($length);
};
}
}
else
{
$options[CURLOPT_POSTFIELDS] = (string) $request->getBody();
}
return $options;
} | [
"protected",
"function",
"createCurlBody",
"(",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
"options",
")",
"{",
"$",
"body",
"=",
"clone",
"$",
"request",
"->",
"getBody",
"(",
")",
";",
"$",
"size",
"=",
"$",
"body",
"->",
"getSize",
"(",
")",
";",
"// Avoid full loading large or unknown size body into memory. It doesn't replace \"CURLOPT_READFUNCTION\".",
"if",
"(",
"$",
"size",
"===",
"null",
"||",
"$",
"size",
">",
"1048576",
")",
"{",
"if",
"(",
"$",
"body",
"->",
"isSeekable",
"(",
")",
")",
"{",
"$",
"body",
"->",
"rewind",
"(",
")",
";",
"}",
"$",
"options",
"[",
"CURLOPT_UPLOAD",
"]",
"=",
"true",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"CURLOPT_READFUNCTION",
"]",
")",
"&&",
"is_callable",
"(",
"$",
"options",
"[",
"CURLOPT_READFUNCTION",
"]",
")",
")",
"{",
"$",
"body",
"=",
"$",
"body",
"->",
"detach",
"(",
")",
";",
"$",
"options",
"[",
"CURLOPT_READFUNCTION",
"]",
"=",
"function",
"(",
"$",
"curl_handler",
",",
"$",
"handler",
",",
"$",
"length",
")",
"use",
"(",
"$",
"body",
",",
"$",
"options",
")",
"{",
"return",
"call_user_func",
"(",
"$",
"options",
"[",
"CURLOPT_READFUNCTION",
"]",
",",
"$",
"curl_handler",
",",
"$",
"body",
",",
"$",
"length",
")",
";",
"}",
";",
"}",
"else",
"{",
"$",
"options",
"[",
"CURLOPT_READFUNCTION",
"]",
"=",
"function",
"(",
"$",
"curl",
",",
"$",
"handler",
",",
"$",
"length",
")",
"use",
"(",
"$",
"body",
")",
"{",
"return",
"$",
"body",
"->",
"read",
"(",
"$",
"length",
")",
";",
"}",
";",
"}",
"}",
"else",
"{",
"$",
"options",
"[",
"CURLOPT_POSTFIELDS",
"]",
"=",
"(",
"string",
")",
"$",
"request",
"->",
"getBody",
"(",
")",
";",
"}",
"return",
"$",
"options",
";",
"}"
] | Create body
@param RequestInterface $request
@param array $options
@return array | [
"Create",
"body"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/HttpClient.php#L284-L320 |
jack-theripper/yandex | src/Client/HttpClient.php | HttpClient.createResponseBuilder | protected function createResponseBuilder()
{
try
{
$body = $this->streamFactory->createStream(fopen('php://temp', 'w+'));
}
catch (\InvalidArgumentException $e)
{
throw new \RuntimeException('Can not create "php://temp" stream.');
}
$response = $this->messageFactory->createResponse(200, null, [], $body);
return new ResponseBuilder($response);
} | php | protected function createResponseBuilder()
{
try
{
$body = $this->streamFactory->createStream(fopen('php://temp', 'w+'));
}
catch (\InvalidArgumentException $e)
{
throw new \RuntimeException('Can not create "php://temp" stream.');
}
$response = $this->messageFactory->createResponse(200, null, [], $body);
return new ResponseBuilder($response);
} | [
"protected",
"function",
"createResponseBuilder",
"(",
")",
"{",
"try",
"{",
"$",
"body",
"=",
"$",
"this",
"->",
"streamFactory",
"->",
"createStream",
"(",
"fopen",
"(",
"'php://temp'",
",",
"'w+'",
")",
")",
";",
"}",
"catch",
"(",
"\\",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Can not create \"php://temp\" stream.'",
")",
";",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"messageFactory",
"->",
"createResponse",
"(",
"200",
",",
"null",
",",
"[",
"]",
",",
"$",
"body",
")",
";",
"return",
"new",
"ResponseBuilder",
"(",
"$",
"response",
")",
";",
"}"
] | Create new ResponseBuilder instance
@return ResponseBuilder
@throws \RuntimeException If creating the stream from $body fails. | [
"Create",
"new",
"ResponseBuilder",
"instance"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/HttpClient.php#L362-L376 |
jack-theripper/yandex | src/Client/Stream/Progress.php | Progress.read | public function read($length)
{
$this->readSize += $length;
$percent = round(100 / $this->totalSize * $this->readSize, 2);
$this->emit('progress', min(100.0, $percent));
return parent::read($length);
} | php | public function read($length)
{
$this->readSize += $length;
$percent = round(100 / $this->totalSize * $this->readSize, 2);
$this->emit('progress', min(100.0, $percent));
return parent::read($length);
} | [
"public",
"function",
"read",
"(",
"$",
"length",
")",
"{",
"$",
"this",
"->",
"readSize",
"+=",
"$",
"length",
";",
"$",
"percent",
"=",
"round",
"(",
"100",
"/",
"$",
"this",
"->",
"totalSize",
"*",
"$",
"this",
"->",
"readSize",
",",
"2",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'progress'",
",",
"min",
"(",
"100.0",
",",
"$",
"percent",
")",
")",
";",
"return",
"parent",
"::",
"read",
"(",
"$",
"length",
")",
";",
"}"
] | Read data from the stream.
@param int $length Read up to $length bytes from the object and return
them. Fewer than $length bytes may be returned if underlying stream
call returns fewer bytes.
@return string Returns the data read from the stream, or an empty string
if no bytes are available.
@throws \RuntimeException if an error occurs. | [
"Read",
"data",
"from",
"the",
"stream",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/Stream/Progress.php#L62-L69 |
jack-theripper/yandex | src/Client/Stream/Progress.php | Progress.seek | public function seek($offset, $whence = SEEK_SET)
{
if (parent::seek($offset, $whence))
{
$this->readSize = $offset;
return true;
}
return false;
} | php | public function seek($offset, $whence = SEEK_SET)
{
if (parent::seek($offset, $whence))
{
$this->readSize = $offset;
return true;
}
return false;
} | [
"public",
"function",
"seek",
"(",
"$",
"offset",
",",
"$",
"whence",
"=",
"SEEK_SET",
")",
"{",
"if",
"(",
"parent",
"::",
"seek",
"(",
"$",
"offset",
",",
"$",
"whence",
")",
")",
"{",
"$",
"this",
"->",
"readSize",
"=",
"$",
"offset",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Seek to a position in the stream.
@param int $offset Stream offset
@param int $whence Specifies how the cursor position will be calculated
based on the seek offset. Valid values are identical to the built-in
PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
offset bytes SEEK_CUR: Set position to current location plus offset
SEEK_END: Set position to end-of-stream plus offset.
@return bool
@throws \RuntimeException on failure. | [
"Seek",
"to",
"a",
"position",
"in",
"the",
"stream",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/Stream/Progress.php#L99-L109 |
jack-theripper/yandex | src/Client/SimpleKey.php | SimpleKey.authentication | protected function authentication(RequestInterface $request)
{
$uri = $request->getUri();
$key = http_build_query(['key' => $this->getAccessKey()], null, '&');
if (strlen($uri->getQuery()) > 0)
{
$key = '&'.$key;
}
return $request->withUri($uri->withQuery($uri->getQuery().$key));
} | php | protected function authentication(RequestInterface $request)
{
$uri = $request->getUri();
$key = http_build_query(['key' => $this->getAccessKey()], null, '&');
if (strlen($uri->getQuery()) > 0)
{
$key = '&'.$key;
}
return $request->withUri($uri->withQuery($uri->getQuery().$key));
} | [
"protected",
"function",
"authentication",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"$",
"uri",
"=",
"$",
"request",
"->",
"getUri",
"(",
")",
";",
"$",
"key",
"=",
"http_build_query",
"(",
"[",
"'key'",
"=>",
"$",
"this",
"->",
"getAccessKey",
"(",
")",
"]",
",",
"null",
",",
"'&'",
")",
";",
"if",
"(",
"strlen",
"(",
"$",
"uri",
"->",
"getQuery",
"(",
")",
")",
">",
"0",
")",
"{",
"$",
"key",
"=",
"'&'",
".",
"$",
"key",
";",
"}",
"return",
"$",
"request",
"->",
"withUri",
"(",
"$",
"uri",
"->",
"withQuery",
"(",
"$",
"uri",
"->",
"getQuery",
"(",
")",
".",
"$",
"key",
")",
")",
";",
"}"
] | Провести аунтификацию в соостветствии с типом сервиса
@param RequestInterface $request
@return RequestInterface | [
"Провести",
"аунтификацию",
"в",
"соостветствии",
"с",
"типом",
"сервиса"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/SimpleKey.php#L86-L97 |
jack-theripper/yandex | src/Disk/AbstractResource.php | AbstractResource.has | public function has($index = null)
{
try
{
if ($this->toArray())
{
if ($index === null)
{
return true;
}
return $this->hasProperty($index);
}
}
catch (\Exception $exc)
{
}
return false;
} | php | public function has($index = null)
{
try
{
if ($this->toArray())
{
if ($index === null)
{
return true;
}
return $this->hasProperty($index);
}
}
catch (\Exception $exc)
{
}
return false;
} | [
"public",
"function",
"has",
"(",
"$",
"index",
"=",
"null",
")",
"{",
"try",
"{",
"if",
"(",
"$",
"this",
"->",
"toArray",
"(",
")",
")",
"{",
"if",
"(",
"$",
"index",
"===",
"null",
")",
"{",
"return",
"true",
";",
"}",
"return",
"$",
"this",
"->",
"hasProperty",
"(",
"$",
"index",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"exc",
")",
"{",
"}",
"return",
"false",
";",
"}"
] | Есть такой файл/папка на диске или свойство
@param mixed $index
@return bool | [
"Есть",
"такой",
"файл",
"/",
"папка",
"на",
"диске",
"или",
"свойство"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/AbstractResource.php#L58-L78 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.getProperty | public function getProperty($index, $default = null)
{
$properties = $this->get('custom_properties', []);
if (isset($properties[$index]))
{
return $properties[$index];
}
if ($default instanceof \Closure)
{
return $default($this);
}
return $default;
} | php | public function getProperty($index, $default = null)
{
$properties = $this->get('custom_properties', []);
if (isset($properties[$index]))
{
return $properties[$index];
}
if ($default instanceof \Closure)
{
return $default($this);
}
return $default;
} | [
"public",
"function",
"getProperty",
"(",
"$",
"index",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"properties",
"=",
"$",
"this",
"->",
"get",
"(",
"'custom_properties'",
",",
"[",
"]",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"properties",
"[",
"$",
"index",
"]",
")",
")",
"{",
"return",
"$",
"properties",
"[",
"$",
"index",
"]",
";",
"}",
"if",
"(",
"$",
"default",
"instanceof",
"\\",
"Closure",
")",
"{",
"return",
"$",
"default",
"(",
"$",
"this",
")",
";",
"}",
"return",
"$",
"default",
";",
"}"
] | Позводляет получить метаинформацию из custom_properties
@param string $index
@param mixed $default
@return mixed|null | [
"Позводляет",
"получить",
"метаинформацию",
"из",
"custom_properties"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L136-L151 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.set | public function set($meta, $value = null)
{
if ( ! is_array($meta))
{
if ( ! is_scalar($meta))
{
throw new \InvalidArgumentException('Индекс метаинформации должен быть простого типа.');
}
$meta = [(string) $meta => $value];
}
if (empty($meta))
{
throw new \OutOfBoundsException('Не было передано ни одного значения для добавления метаинформации.');
}
/*if (mb_strlen(json_encode($meta, JSON_UNESCAPED_UNICODE), 'UTF-8') > 1024)
{
throw new \LengthException('Максимальный допустимый размер объекта метаинформации составляет 1024 байт.');
}*/
$request = (new Request($this->uri->withPath($this->uri->getPath().'resources')
->withQuery(http_build_query(['path' => $this->getPath()], null, '&')), 'PATCH'));
$request->getBody()
->write(json_encode(['custom_properties' => $meta]));
$response = $this->client->send($request);
if ($response->getStatusCode() == 200)
{
$this->setContents(json_decode($response->getBody(), true));
$this->store['docviewer'] = $this->createDocViewerUrl();
}
return $this;
} | php | public function set($meta, $value = null)
{
if ( ! is_array($meta))
{
if ( ! is_scalar($meta))
{
throw new \InvalidArgumentException('Индекс метаинформации должен быть простого типа.');
}
$meta = [(string) $meta => $value];
}
if (empty($meta))
{
throw new \OutOfBoundsException('Не было передано ни одного значения для добавления метаинформации.');
}
/*if (mb_strlen(json_encode($meta, JSON_UNESCAPED_UNICODE), 'UTF-8') > 1024)
{
throw new \LengthException('Максимальный допустимый размер объекта метаинформации составляет 1024 байт.');
}*/
$request = (new Request($this->uri->withPath($this->uri->getPath().'resources')
->withQuery(http_build_query(['path' => $this->getPath()], null, '&')), 'PATCH'));
$request->getBody()
->write(json_encode(['custom_properties' => $meta]));
$response = $this->client->send($request);
if ($response->getStatusCode() == 200)
{
$this->setContents(json_decode($response->getBody(), true));
$this->store['docviewer'] = $this->createDocViewerUrl();
}
return $this;
} | [
"public",
"function",
"set",
"(",
"$",
"meta",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"meta",
")",
")",
"{",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"meta",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Индекс метаинформации должен быть простого типа.');",
"",
"",
"}",
"$",
"meta",
"=",
"[",
"(",
"string",
")",
"$",
"meta",
"=>",
"$",
"value",
"]",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"meta",
")",
")",
"{",
"throw",
"new",
"\\",
"OutOfBoundsException",
"(",
"'Не было передано ни одного значения для добавления метаинформации.');",
"",
"",
"}",
"/*if (mb_strlen(json_encode($meta, JSON_UNESCAPED_UNICODE), 'UTF-8') > 1024)\n\t\t{\n\t\t\tthrow new \\LengthException('Максимальный допустимый размер объекта метаинформации составляет 1024 байт.');\n\t\t}*/",
"$",
"request",
"=",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'PATCH'",
")",
")",
";",
"$",
"request",
"->",
"getBody",
"(",
")",
"->",
"write",
"(",
"json_encode",
"(",
"[",
"'custom_properties'",
"=>",
"$",
"meta",
"]",
")",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"$",
"request",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"this",
"->",
"setContents",
"(",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
")",
";",
"$",
"this",
"->",
"store",
"[",
"'docviewer'",
"]",
"=",
"$",
"this",
"->",
"createDocViewerUrl",
"(",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Добавление метаинформации для ресурса
@param mixed $meta строка либо массив значений
@param mixed $value NULL чтобы удалить определённую метаинформаию когда $meta строка
@return Closed
@throws \LengthException | [
"Добавление",
"метаинформации",
"для",
"ресурса"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L172-L209 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.delete | public function delete($permanently = false)
{
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources')
->withQuery(http_build_query([
'path' => $this->getPath(),
'permanently' => (bool) $permanently
])), 'DELETE'));
if ($response->getStatusCode() == 202 || $response->getStatusCode() == 204)
{
$this->setContents([]);
$this->emit('delete', $this, $this->client);
$this->client->emit('delete', $this, $this->client);
if ($response->getStatusCode() == 202)
{
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
}
try
{
/*$resource = $this->client->getTrashResource('/', 0);
$resource = $this->client->getTrashResources(1, $resource->get('total', 0) - 1)->getFirst();
if ($resource->has() && $resource->get('origin_path') == $this->getPath())
{
return $resource;
}*/
}
catch (\Exception $exc)
{
}
return true;
}
return false;
} | php | public function delete($permanently = false)
{
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources')
->withQuery(http_build_query([
'path' => $this->getPath(),
'permanently' => (bool) $permanently
])), 'DELETE'));
if ($response->getStatusCode() == 202 || $response->getStatusCode() == 204)
{
$this->setContents([]);
$this->emit('delete', $this, $this->client);
$this->client->emit('delete', $this, $this->client);
if ($response->getStatusCode() == 202)
{
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
}
try
{
/*$resource = $this->client->getTrashResource('/', 0);
$resource = $this->client->getTrashResources(1, $resource->get('total', 0) - 1)->getFirst();
if ($resource->has() && $resource->get('origin_path') == $this->getPath())
{
return $resource;
}*/
}
catch (\Exception $exc)
{
}
return true;
}
return false;
} | [
"public",
"function",
"delete",
"(",
"$",
"permanently",
"=",
"false",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
",",
"'permanently'",
"=>",
"(",
"bool",
")",
"$",
"permanently",
"]",
")",
")",
",",
"'DELETE'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"202",
"||",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"204",
")",
"{",
"$",
"this",
"->",
"setContents",
"(",
"[",
"]",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'delete'",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"$",
"this",
"->",
"client",
"->",
"emit",
"(",
"'delete'",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"202",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
")",
"{",
"$",
"response",
"[",
"'operation'",
"]",
"=",
"$",
"this",
"->",
"client",
"->",
"getOperation",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"$",
"this",
"->",
"client",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"return",
"$",
"response",
"[",
"'operation'",
"]",
";",
"}",
"}",
"try",
"{",
"/*$resource = $this->client->getTrashResource('/', 0);\n\t\t\t\t$resource = $this->client->getTrashResources(1, $resource->get('total', 0) - 1)->getFirst();\n\n\t\t\t\tif ($resource->has() && $resource->get('origin_path') == $this->getPath())\n\t\t\t\t{\n\t\t\t\t\treturn $resource;\n\t\t\t\t}*/",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"exc",
")",
"{",
"}",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Удаление файла или папки
@param boolean $permanently TRUE Признак безвозвратного удаления
@return bool|\Arhitector\Yandex\Disk\Operation|\Arhitector\Yandex\Disk\Resource\Removed | [
"Удаление",
"файла",
"или",
"папки"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L264-L312 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.move | public function move($destination, $overwrite = false)
{
if ($destination instanceof Closed)
{
$destination = $destination->getPath();
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/move')
->withQuery(http_build_query([
'from' => $this->getPath(),
'path' => $destination,
'overwrite' => (bool) $overwrite
], null, '&')), 'POST'));
if ($response->getStatusCode() == 202 || $response->getStatusCode() == 201)
{
$this->path = $destination;
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
return true;
}
return false;
} | php | public function move($destination, $overwrite = false)
{
if ($destination instanceof Closed)
{
$destination = $destination->getPath();
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/move')
->withQuery(http_build_query([
'from' => $this->getPath(),
'path' => $destination,
'overwrite' => (bool) $overwrite
], null, '&')), 'POST'));
if ($response->getStatusCode() == 202 || $response->getStatusCode() == 201)
{
$this->path = $destination;
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
return true;
}
return false;
} | [
"public",
"function",
"move",
"(",
"$",
"destination",
",",
"$",
"overwrite",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"destination",
"instanceof",
"Closed",
")",
"{",
"$",
"destination",
"=",
"$",
"destination",
"->",
"getPath",
"(",
")",
";",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources/move'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'from'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
",",
"'path'",
"=>",
"$",
"destination",
",",
"'overwrite'",
"=>",
"(",
"bool",
")",
"$",
"overwrite",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'POST'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"202",
"||",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"201",
")",
"{",
"$",
"this",
"->",
"path",
"=",
"$",
"destination",
";",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
")",
"{",
"$",
"response",
"[",
"'operation'",
"]",
"=",
"$",
"this",
"->",
"client",
"->",
"getOperation",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"$",
"this",
"->",
"client",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"return",
"$",
"response",
"[",
"'operation'",
"]",
";",
"}",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Перемещение файла или папки.
Перемещать файлы и папки на Диске можно, указывая текущий путь к ресурсу и его новое положение.
Если запрос был обработан без ошибок, API составляет тело ответа в зависимости от вида указанного ресурса –
ответ для пустой папки или файла отличается от ответа для непустой папки. (Если запрос вызвал ошибку,
возвращается подходящий код ответа, а тело ответа содержит описание ошибки).
Приложения должны самостоятельно следить за статусами запрошенных операций.
@param string|\Arhitector\Yandex\Disk\Resource\Closed $destination новый путь.
@param boolean $overwrite признак перезаписи файлов. Учитывается,
если ресурс перемещается в папку, в которой
уже есть ресурс с таким именем.
@return bool|\Arhitector\Yandex\Disk\Operation | [
"Перемещение",
"файла",
"или",
"папки",
".",
"Перемещать",
"файлы",
"и",
"папки",
"на",
"Диске",
"можно",
"указывая",
"текущий",
"путь",
"к",
"ресурсу",
"и",
"его",
"новое",
"положение",
".",
"Если",
"запрос",
"был",
"обработан",
"без",
"ошибок",
"API",
"составляет",
"тело",
"ответа",
"в",
"зависимости",
"от",
"вида",
"указанного",
"ресурса",
"–",
"ответ",
"для",
"пустой",
"папки",
"или",
"файла",
"отличается",
"от",
"ответа",
"для",
"непустой",
"папки",
".",
"(",
"Если",
"запрос",
"вызвал",
"ошибку",
"возвращается",
"подходящий",
"код",
"ответа",
"а",
"тело",
"ответа",
"содержит",
"описание",
"ошибки",
")",
".",
"Приложения",
"должны",
"самостоятельно",
"следить",
"за",
"статусами",
"запрошенных",
"операций",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L329-L361 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.create | public function create()
{
try
{
$this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources')
->withQuery(http_build_query([
'path' => $this->getPath()
], null, '&')), 'PUT'));
$this->setContents([]);
}
catch (\Exception $exc)
{
throw $exc;
}
return $this;
} | php | public function create()
{
try
{
$this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources')
->withQuery(http_build_query([
'path' => $this->getPath()
], null, '&')), 'PUT'));
$this->setContents([]);
}
catch (\Exception $exc)
{
throw $exc;
}
return $this;
} | [
"public",
"function",
"create",
"(",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'PUT'",
")",
")",
";",
"$",
"this",
"->",
"setContents",
"(",
"[",
"]",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"exc",
")",
"{",
"throw",
"$",
"exc",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Создание папки, если ресурса с таким же именем нет
@return \Arhitector\Yandex\Disk\Resource\Closed
@throws mixed | [
"Создание",
"папки",
"если",
"ресурса",
"с",
"таким",
"же",
"именем",
"нет"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L369-L385 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.setPublish | public function setPublish($publish = true)
{
$request = 'resources/unpublish';
if ($publish)
{
$request = 'resources/publish';
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().$request)
->withQuery(http_build_query([
'path' => $this->getPath()
], null, '&')), 'PUT'));
if ($response->getStatusCode() == 200)
{
$this->setContents([]);
if ($publish && $this->has('public_key'))
{
return $this->client->getPublishResource($this->get('public_key'));
}
}
return $this;
} | php | public function setPublish($publish = true)
{
$request = 'resources/unpublish';
if ($publish)
{
$request = 'resources/publish';
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().$request)
->withQuery(http_build_query([
'path' => $this->getPath()
], null, '&')), 'PUT'));
if ($response->getStatusCode() == 200)
{
$this->setContents([]);
if ($publish && $this->has('public_key'))
{
return $this->client->getPublishResource($this->get('public_key'));
}
}
return $this;
} | [
"public",
"function",
"setPublish",
"(",
"$",
"publish",
"=",
"true",
")",
"{",
"$",
"request",
"=",
"'resources/unpublish'",
";",
"if",
"(",
"$",
"publish",
")",
"{",
"$",
"request",
"=",
"'resources/publish'",
";",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"$",
"request",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'PUT'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"this",
"->",
"setContents",
"(",
"[",
"]",
")",
";",
"if",
"(",
"$",
"publish",
"&&",
"$",
"this",
"->",
"has",
"(",
"'public_key'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"client",
"->",
"getPublishResource",
"(",
"$",
"this",
"->",
"get",
"(",
"'public_key'",
")",
")",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | Публикация ресурса\Закрытие доступа
@param boolean $publish TRUE открыть доступ, FALSE закрыть доступ
@return \Arhitector\Yandex\Disk\Resource\Closed|\Arhitector\Yandex\Disk\Resource\Opened | [
"Публикация",
"ресурса",
"\\",
"Закрытие",
"доступа"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L394-L419 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.download | public function download($destination, $overwrite = false)
{
$destination_type = gettype($destination);
if ( ! $this->has())
{
throw new NotFoundException('Не удалось найти запрошенный ресурс.');
}
if (is_resource($destination))
{
$destination = new Stream($destination);
}
if ($destination instanceof StreamInterface)
{
if ( ! $destination->isWritable())
{
throw new \OutOfBoundsException('Дескриптор файла должен быть открыт с правами на запись.');
}
}
else
{
if ($destination_type == 'string')
{
if (is_file($destination) && ! $overwrite)
{
throw new AlreadyExistsException('По указанному пути "'.$destination.'" уже существует ресурс.');
}
if ( ! is_writable(dirname($destination)))
{
throw new \OutOfBoundsException('Запрещена запись в директорию, в которой должен быть расположен файл.');
}
$destination = new Stream($destination, 'w+b');
}
else
{
throw new \InvalidArgumentException('Такой тип параметра $destination не поддерживается.');
}
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/download')
->withQuery(http_build_query(['path' => $this->getPath()], null, '&')), 'GET'));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['href']))
{
$response = $this->client->send(new Request($response['href'], 'GET'));
if ($response->getStatusCode() == 200)
{
$stream = $response->getBody();
while ( ! $stream->eof())
{
$destination->write($stream->read(16384));
}
$stream->close();
$this->emit('downloaded', $this, $destination, $this->client);
$this->client->emit('downloaded', $this, $destination, $this->client);
if ($destination_type == 'object')
{
return $destination;
}
return $destination->getSize();
}
return false;
}
}
throw new \UnexpectedValueException('Не удалось запросить разрешение на скачивание, повторите заново.');
} | php | public function download($destination, $overwrite = false)
{
$destination_type = gettype($destination);
if ( ! $this->has())
{
throw new NotFoundException('Не удалось найти запрошенный ресурс.');
}
if (is_resource($destination))
{
$destination = new Stream($destination);
}
if ($destination instanceof StreamInterface)
{
if ( ! $destination->isWritable())
{
throw new \OutOfBoundsException('Дескриптор файла должен быть открыт с правами на запись.');
}
}
else
{
if ($destination_type == 'string')
{
if (is_file($destination) && ! $overwrite)
{
throw new AlreadyExistsException('По указанному пути "'.$destination.'" уже существует ресурс.');
}
if ( ! is_writable(dirname($destination)))
{
throw new \OutOfBoundsException('Запрещена запись в директорию, в которой должен быть расположен файл.');
}
$destination = new Stream($destination, 'w+b');
}
else
{
throw new \InvalidArgumentException('Такой тип параметра $destination не поддерживается.');
}
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/download')
->withQuery(http_build_query(['path' => $this->getPath()], null, '&')), 'GET'));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['href']))
{
$response = $this->client->send(new Request($response['href'], 'GET'));
if ($response->getStatusCode() == 200)
{
$stream = $response->getBody();
while ( ! $stream->eof())
{
$destination->write($stream->read(16384));
}
$stream->close();
$this->emit('downloaded', $this, $destination, $this->client);
$this->client->emit('downloaded', $this, $destination, $this->client);
if ($destination_type == 'object')
{
return $destination;
}
return $destination->getSize();
}
return false;
}
}
throw new \UnexpectedValueException('Не удалось запросить разрешение на скачивание, повторите заново.');
} | [
"public",
"function",
"download",
"(",
"$",
"destination",
",",
"$",
"overwrite",
"=",
"false",
")",
"{",
"$",
"destination_type",
"=",
"gettype",
"(",
"$",
"destination",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"has",
"(",
")",
")",
"{",
"throw",
"new",
"NotFoundException",
"(",
"'Не удалось найти запрошенный ресурс.');",
"",
"",
"}",
"if",
"(",
"is_resource",
"(",
"$",
"destination",
")",
")",
"{",
"$",
"destination",
"=",
"new",
"Stream",
"(",
"$",
"destination",
")",
";",
"}",
"if",
"(",
"$",
"destination",
"instanceof",
"StreamInterface",
")",
"{",
"if",
"(",
"!",
"$",
"destination",
"->",
"isWritable",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"OutOfBoundsException",
"(",
"'Дескриптор файла должен быть открыт с правами на запись.');",
"",
"",
"}",
"}",
"else",
"{",
"if",
"(",
"$",
"destination_type",
"==",
"'string'",
")",
"{",
"if",
"(",
"is_file",
"(",
"$",
"destination",
")",
"&&",
"!",
"$",
"overwrite",
")",
"{",
"throw",
"new",
"AlreadyExistsException",
"(",
"'По указанному пути \"'.$destination.'\"",
" ",
"у",
"же существу",
"е",
"т ресурс.');",
"",
"",
"}",
"if",
"(",
"!",
"is_writable",
"(",
"dirname",
"(",
"$",
"destination",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"OutOfBoundsException",
"(",
"'Запрещена запись в директорию, в которой должен быть расположен файл.');",
"",
"",
"}",
"$",
"destination",
"=",
"new",
"Stream",
"(",
"$",
"destination",
",",
"'w+b'",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Такой тип параметра $destination не поддерживается.');",
"",
"",
"}",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources/download'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'GET'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'href'",
"]",
")",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"response",
"[",
"'href'",
"]",
",",
"'GET'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"stream",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"while",
"(",
"!",
"$",
"stream",
"->",
"eof",
"(",
")",
")",
"{",
"$",
"destination",
"->",
"write",
"(",
"$",
"stream",
"->",
"read",
"(",
"16384",
")",
")",
";",
"}",
"$",
"stream",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'downloaded'",
",",
"$",
"this",
",",
"$",
"destination",
",",
"$",
"this",
"->",
"client",
")",
";",
"$",
"this",
"->",
"client",
"->",
"emit",
"(",
"'downloaded'",
",",
"$",
"this",
",",
"$",
"destination",
",",
"$",
"this",
"->",
"client",
")",
";",
"if",
"(",
"$",
"destination_type",
"==",
"'object'",
")",
"{",
"return",
"$",
"destination",
";",
"}",
"return",
"$",
"destination",
"->",
"getSize",
"(",
")",
";",
"}",
"return",
"false",
";",
"}",
"}",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'Не удалось запросить разрешение на скачивание, повторите заново.');",
"",
"",
"}"
] | Скачивает файл
@param resource|StreamInterface|string $destination Путь, по которому будет сохранён файл
StreamInterface будет записан в поток
resource открытый на запись
@param mixed $overwrite
@return bool
@throws NotFoundException
@throws AlreadyExistsException
@throws \OutOfBoundsException
@throws \UnexpectedValueException | [
"Скачивает",
"файл"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L436-L516 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.upload | public function upload($file_path, $overwrite = false, $disable_redirects = false)
{
if (is_string($file_path))
{
$scheme = substr($file_path, 0, 7);
if ($scheme == 'http://' or $scheme == 'https:/')
{
try
{
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/upload')
->withQuery(http_build_query([
'url' => $file_path,
'path' => $this->getPath(),
'disable_redirects' => (int) $disable_redirects
], null, '&')), 'POST'));
}
catch (AlreadyExistsException $exc)
{
// параметр $overwrite не работает т.к. диск не поддерживает {AlreadyExistsException:409}->rename->delete
throw new AlreadyExistsException($exc->getMessage().' Перезапись для удалённой загрузки не доступна.',
$exc->getCode(), $exc);
}
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
return false;
}
$file_path = realpath($file_path);
if ( ! is_file($file_path))
{
throw new \OutOfBoundsException('Локальный файл по такому пути: "'.$file_path.'" отсутствует.');
}
}
else
{
if ( ! is_resource($file_path))
{
throw new \InvalidArgumentException('Параметр "путь к файлу" должен быть строкового типа или открытый файловый дескриптор на чтение.');
}
}
$access_upload = json_decode($this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/upload')
->withQuery(http_build_query([
'path' => $this->getPath(),
'overwrite' => (int) ((boolean) $overwrite),
], null, '&')), 'GET'))
->getBody(), true);
if ( ! isset($access_upload['href']))
{
// $this->client->setRetries = 1
throw new \RuntimeException('Не возможно загрузить локальный файл - не получено разрешение.');
}
if ($this->getEmitter()->hasListeners('progress'))
{
$stream = new Progress($file_path, 'rb');
$stream->addListener('progress', function (Event $event, $percent) {
$this->emit('progress', $percent);
});
}
else
{
$stream = new Stream($file_path, 'rb');
}
$response = $this->client->send((new Request($access_upload['href'], 'PUT', $stream)));
$this->emit('uploaded', $this, $this->client);
$this->client->emit('uploaded', $this, $this->client);
return $response->getStatusCode() == 201;
} | php | public function upload($file_path, $overwrite = false, $disable_redirects = false)
{
if (is_string($file_path))
{
$scheme = substr($file_path, 0, 7);
if ($scheme == 'http://' or $scheme == 'https:/')
{
try
{
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/upload')
->withQuery(http_build_query([
'url' => $file_path,
'path' => $this->getPath(),
'disable_redirects' => (int) $disable_redirects
], null, '&')), 'POST'));
}
catch (AlreadyExistsException $exc)
{
// параметр $overwrite не работает т.к. диск не поддерживает {AlreadyExistsException:409}->rename->delete
throw new AlreadyExistsException($exc->getMessage().' Перезапись для удалённой загрузки не доступна.',
$exc->getCode(), $exc);
}
$response = json_decode($response->getBody(), true);
if (isset($response['operation']))
{
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
return false;
}
$file_path = realpath($file_path);
if ( ! is_file($file_path))
{
throw new \OutOfBoundsException('Локальный файл по такому пути: "'.$file_path.'" отсутствует.');
}
}
else
{
if ( ! is_resource($file_path))
{
throw new \InvalidArgumentException('Параметр "путь к файлу" должен быть строкового типа или открытый файловый дескриптор на чтение.');
}
}
$access_upload = json_decode($this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/upload')
->withQuery(http_build_query([
'path' => $this->getPath(),
'overwrite' => (int) ((boolean) $overwrite),
], null, '&')), 'GET'))
->getBody(), true);
if ( ! isset($access_upload['href']))
{
// $this->client->setRetries = 1
throw new \RuntimeException('Не возможно загрузить локальный файл - не получено разрешение.');
}
if ($this->getEmitter()->hasListeners('progress'))
{
$stream = new Progress($file_path, 'rb');
$stream->addListener('progress', function (Event $event, $percent) {
$this->emit('progress', $percent);
});
}
else
{
$stream = new Stream($file_path, 'rb');
}
$response = $this->client->send((new Request($access_upload['href'], 'PUT', $stream)));
$this->emit('uploaded', $this, $this->client);
$this->client->emit('uploaded', $this, $this->client);
return $response->getStatusCode() == 201;
} | [
"public",
"function",
"upload",
"(",
"$",
"file_path",
",",
"$",
"overwrite",
"=",
"false",
",",
"$",
"disable_redirects",
"=",
"false",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"file_path",
")",
")",
"{",
"$",
"scheme",
"=",
"substr",
"(",
"$",
"file_path",
",",
"0",
",",
"7",
")",
";",
"if",
"(",
"$",
"scheme",
"==",
"'http://'",
"or",
"$",
"scheme",
"==",
"'https:/'",
")",
"{",
"try",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources/upload'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'url'",
"=>",
"$",
"file_path",
",",
"'path'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
",",
"'disable_redirects'",
"=>",
"(",
"int",
")",
"$",
"disable_redirects",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'POST'",
")",
")",
";",
"}",
"catch",
"(",
"AlreadyExistsException",
"$",
"exc",
")",
"{",
"// параметр $overwrite не работает т.к. диск не поддерживает {AlreadyExistsException:409}->rename->delete",
"throw",
"new",
"AlreadyExistsException",
"(",
"$",
"exc",
"->",
"getMessage",
"(",
")",
".",
"' Перезапись для удалённой загрузки не доступна.',",
"",
"$",
"exc",
"->",
"getCode",
"(",
")",
",",
"$",
"exc",
")",
";",
"}",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
")",
"{",
"$",
"response",
"[",
"'operation'",
"]",
"=",
"$",
"this",
"->",
"client",
"->",
"getOperation",
"(",
"$",
"response",
"[",
"'operation'",
"]",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"$",
"this",
"->",
"client",
"->",
"emit",
"(",
"'operation'",
",",
"$",
"response",
"[",
"'operation'",
"]",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"return",
"$",
"response",
"[",
"'operation'",
"]",
";",
"}",
"return",
"false",
";",
"}",
"$",
"file_path",
"=",
"realpath",
"(",
"$",
"file_path",
")",
";",
"if",
"(",
"!",
"is_file",
"(",
"$",
"file_path",
")",
")",
"{",
"throw",
"new",
"\\",
"OutOfBoundsException",
"(",
"'Локальный файл по такому пути: \"'.$file_path.'\" отсутствуе",
"т",
".",
"');",
"",
"",
"",
"",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"file_path",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Параметр \"путь к файлу\" должен быть строкового типа или открытый файловый дескриптор на чтение.');",
"",
"",
"}",
"}",
"$",
"access_upload",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources/upload'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'path'",
"=>",
"$",
"this",
"->",
"getPath",
"(",
")",
",",
"'overwrite'",
"=>",
"(",
"int",
")",
"(",
"(",
"boolean",
")",
"$",
"overwrite",
")",
",",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'GET'",
")",
")",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"access_upload",
"[",
"'href'",
"]",
")",
")",
"{",
"// $this->client->setRetries = 1",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Не возможно загрузить локальный файл - не получено разрешение.');",
"",
"",
"}",
"if",
"(",
"$",
"this",
"->",
"getEmitter",
"(",
")",
"->",
"hasListeners",
"(",
"'progress'",
")",
")",
"{",
"$",
"stream",
"=",
"new",
"Progress",
"(",
"$",
"file_path",
",",
"'rb'",
")",
";",
"$",
"stream",
"->",
"addListener",
"(",
"'progress'",
",",
"function",
"(",
"Event",
"$",
"event",
",",
"$",
"percent",
")",
"{",
"$",
"this",
"->",
"emit",
"(",
"'progress'",
",",
"$",
"percent",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"$",
"stream",
"=",
"new",
"Stream",
"(",
"$",
"file_path",
",",
"'rb'",
")",
";",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"(",
"new",
"Request",
"(",
"$",
"access_upload",
"[",
"'href'",
"]",
",",
"'PUT'",
",",
"$",
"stream",
")",
")",
")",
";",
"$",
"this",
"->",
"emit",
"(",
"'uploaded'",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"$",
"this",
"->",
"client",
"->",
"emit",
"(",
"'uploaded'",
",",
"$",
"this",
",",
"$",
"this",
"->",
"client",
")",
";",
"return",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"201",
";",
"}"
] | Загрузить файл на диск
@param mixed $file_path может быть как путь к локальному файлу, так и URL к файлу.
@param bool $overwrite если ресурс существует на Яндекс.Диске TRUE перезапишет ресурс.
@param bool $disable_redirects помогает запретить редиректы по адресу, TRUE запретит пере адресацию.
@return bool|\Arhitector\Yandex\Disk\Operation
@throws mixed
@TODO Добавить, если передана папка - сжать папку в архив и загрузить. | [
"Загрузить",
"файл",
"на",
"диск"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L572-L655 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.getLink | public function getLink()
{
if ( ! $this->has())
{
throw new NotFoundException('Не удалось найти запрошенный ресурс.');
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/download')
->withQuery(http_build_query([
'path' => (string) $this->getPath()
], null, '&')), 'GET'));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['href']))
{
return $response['href'];
}
}
throw new \UnexpectedValueException('Не удалось запросить разрешение на скачивание, повторите заново');
} | php | public function getLink()
{
if ( ! $this->has())
{
throw new NotFoundException('Не удалось найти запрошенный ресурс.');
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources/download')
->withQuery(http_build_query([
'path' => (string) $this->getPath()
], null, '&')), 'GET'));
if ($response->getStatusCode() == 200)
{
$response = json_decode($response->getBody(), true);
if (isset($response['href']))
{
return $response['href'];
}
}
throw new \UnexpectedValueException('Не удалось запросить разрешение на скачивание, повторите заново');
} | [
"public",
"function",
"getLink",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"has",
"(",
")",
")",
"{",
"throw",
"new",
"NotFoundException",
"(",
"'Не удалось найти запрошенный ресурс.');",
"",
"",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"new",
"Request",
"(",
"$",
"this",
"->",
"uri",
"->",
"withPath",
"(",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
".",
"'resources/download'",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"[",
"'path'",
"=>",
"(",
"string",
")",
"$",
"this",
"->",
"getPath",
"(",
")",
"]",
",",
"null",
",",
"'&'",
")",
")",
",",
"'GET'",
")",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"==",
"200",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'href'",
"]",
")",
")",
"{",
"return",
"$",
"response",
"[",
"'href'",
"]",
";",
"}",
"}",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'Не удалось запросить разрешение на скачивание, повторите заново');",
"",
"",
"}"
] | Получает прямую ссылку
@return string
@throws mixed
@TODO Не работает для файлов вложенных в публичную папку. | [
"Получает",
"прямую",
"ссылку"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L665-L688 |
jack-theripper/yandex | src/Disk/Resource/Closed.php | Closed.createDocViewerUrl | protected function createDocViewerUrl()
{
if ($this->isFile())
{
$docviewer = [
'url' => $this->get('path'),
'name' => $this->get('name')
];
if (strpos($docviewer['url'], 'disk:/') === 0)
{
$docviewer['url'] = substr($docviewer['url'], 6);
}
$docviewer['url'] = "ya-disk:///disk/{$docviewer['url']}";
return (string) (new Uri('https://docviewer.yandex.ru'))
->withQuery(http_build_query($docviewer, null, '&'));
}
return false;
} | php | protected function createDocViewerUrl()
{
if ($this->isFile())
{
$docviewer = [
'url' => $this->get('path'),
'name' => $this->get('name')
];
if (strpos($docviewer['url'], 'disk:/') === 0)
{
$docviewer['url'] = substr($docviewer['url'], 6);
}
$docviewer['url'] = "ya-disk:///disk/{$docviewer['url']}";
return (string) (new Uri('https://docviewer.yandex.ru'))
->withQuery(http_build_query($docviewer, null, '&'));
}
return false;
} | [
"protected",
"function",
"createDocViewerUrl",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isFile",
"(",
")",
")",
"{",
"$",
"docviewer",
"=",
"[",
"'url'",
"=>",
"$",
"this",
"->",
"get",
"(",
"'path'",
")",
",",
"'name'",
"=>",
"$",
"this",
"->",
"get",
"(",
"'name'",
")",
"]",
";",
"if",
"(",
"strpos",
"(",
"$",
"docviewer",
"[",
"'url'",
"]",
",",
"'disk:/'",
")",
"===",
"0",
")",
"{",
"$",
"docviewer",
"[",
"'url'",
"]",
"=",
"substr",
"(",
"$",
"docviewer",
"[",
"'url'",
"]",
",",
"6",
")",
";",
"}",
"$",
"docviewer",
"[",
"'url'",
"]",
"=",
"\"ya-disk:///disk/{$docviewer['url']}\"",
";",
"return",
"(",
"string",
")",
"(",
"new",
"Uri",
"(",
"'https://docviewer.yandex.ru'",
")",
")",
"->",
"withQuery",
"(",
"http_build_query",
"(",
"$",
"docviewer",
",",
"null",
",",
"'&'",
")",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Получает ссылку для просмотра документа. Достпно владельцу аккаунта.
@return bool|string | [
"Получает",
"ссылку",
"для",
"просмотра",
"документа",
".",
"Достпно",
"владельцу",
"аккаунта",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Resource/Closed.php#L695-L716 |
jack-theripper/yandex | src/AbstractClient.php | AbstractClient.send | public function send(RequestInterface $request)
{
$request = $this->authentication($request);
$defaultHeaders = [
'Accept' => $this->getContentType(),
'Content-Type' => $this->getContentType()
];
foreach ($defaultHeaders as $defaultHeader => $value)
{
if ( ! $request->hasHeader($defaultHeader))
{
$request = $request->withHeader($defaultHeader, $value);
}
}
$response = $this->client->sendRequest($request);
$response = $this->transformResponseToException($request, $response);
return $response;
} | php | public function send(RequestInterface $request)
{
$request = $this->authentication($request);
$defaultHeaders = [
'Accept' => $this->getContentType(),
'Content-Type' => $this->getContentType()
];
foreach ($defaultHeaders as $defaultHeader => $value)
{
if ( ! $request->hasHeader($defaultHeader))
{
$request = $request->withHeader($defaultHeader, $value);
}
}
$response = $this->client->sendRequest($request);
$response = $this->transformResponseToException($request, $response);
return $response;
} | [
"public",
"function",
"send",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"authentication",
"(",
"$",
"request",
")",
";",
"$",
"defaultHeaders",
"=",
"[",
"'Accept'",
"=>",
"$",
"this",
"->",
"getContentType",
"(",
")",
",",
"'Content-Type'",
"=>",
"$",
"this",
"->",
"getContentType",
"(",
")",
"]",
";",
"foreach",
"(",
"$",
"defaultHeaders",
"as",
"$",
"defaultHeader",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"hasHeader",
"(",
"$",
"defaultHeader",
")",
")",
"{",
"$",
"request",
"=",
"$",
"request",
"->",
"withHeader",
"(",
"$",
"defaultHeader",
",",
"$",
"value",
")",
";",
"}",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"sendRequest",
"(",
"$",
"request",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"transformResponseToException",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Модифицирует и отправляет запрос.
@param \Psr\Http\Message\RequestInterface $request
@return \Psr\Http\Message\ResponseInterface | [
"Модифицирует",
"и",
"отправляет",
"запрос",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/AbstractClient.php#L128-L148 |
jack-theripper/yandex | src/AbstractClient.php | AbstractClient.setAccessTokenRequired | protected function setAccessTokenRequired($tokenRequired)
{
$previous = $this->tokenRequired;
$this->tokenRequired = (bool) $tokenRequired;
return $previous;
} | php | protected function setAccessTokenRequired($tokenRequired)
{
$previous = $this->tokenRequired;
$this->tokenRequired = (bool) $tokenRequired;
return $previous;
} | [
"protected",
"function",
"setAccessTokenRequired",
"(",
"$",
"tokenRequired",
")",
"{",
"$",
"previous",
"=",
"$",
"this",
"->",
"tokenRequired",
";",
"$",
"this",
"->",
"tokenRequired",
"=",
"(",
"bool",
")",
"$",
"tokenRequired",
";",
"return",
"$",
"previous",
";",
"}"
] | Устаналивает необходимость токена при запросе.
@param $tokenRequired
@return boolean возвращает предыдущее состояние | [
"Устаналивает",
"необходимость",
"токена",
"при",
"запросе",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/AbstractClient.php#L157-L163 |
jack-theripper/yandex | src/AbstractClient.php | AbstractClient.transformResponseToException | protected function transformResponseToException(RequestInterface $request, ResponseInterface $response)
{
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500)
{
throw new \RuntimeException($response->getReasonPhrase(), $response->getStatusCode());
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600)
{
throw new ServiceException($response->getReasonPhrase(), $response->getStatusCode());
}
return $response;
} | php | protected function transformResponseToException(RequestInterface $request, ResponseInterface $response)
{
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500)
{
throw new \RuntimeException($response->getReasonPhrase(), $response->getStatusCode());
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600)
{
throw new ServiceException($response->getReasonPhrase(), $response->getStatusCode());
}
return $response;
} | [
"protected",
"function",
"transformResponseToException",
"(",
"RequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
")",
"{",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
">=",
"400",
"&&",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"<",
"500",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"$",
"response",
"->",
"getReasonPhrase",
"(",
")",
",",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
">=",
"500",
"&&",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"<",
"600",
")",
"{",
"throw",
"new",
"ServiceException",
"(",
"$",
"response",
"->",
"getReasonPhrase",
"(",
")",
",",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | Трансформирует ответ в исключения
@param \Psr\Http\Message\RequestInterface $request
@param \Psr\Http\Message\ResponseInterface $response
@return \Psr\Http\Message\ResponseInterface если статус код не является ошибочным, то вернуть объект ответа
@throws \Arhitector\Yandex\Client\Exception\ServiceException | [
"Трансформирует",
"ответ",
"в",
"исключения"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/AbstractClient.php#L174-L187 |
jack-theripper/yandex | src/Disk/Filter/MediaTypeTrait.php | MediaTypeTrait.setMediaType | public function setMediaType($media_type)
{
$media_type = (string) $media_type;
if ( ! in_array($media_type, $this->getMediaTypes()))
{
throw new \UnexpectedValueException('Тип файла, значения - "'.implode('", "', $this->getMediaTypes()).'".');
}
$this->isModified = true;
$this->parameters['media_type'] = $media_type;
return $this;
} | php | public function setMediaType($media_type)
{
$media_type = (string) $media_type;
if ( ! in_array($media_type, $this->getMediaTypes()))
{
throw new \UnexpectedValueException('Тип файла, значения - "'.implode('", "', $this->getMediaTypes()).'".');
}
$this->isModified = true;
$this->parameters['media_type'] = $media_type;
return $this;
} | [
"public",
"function",
"setMediaType",
"(",
"$",
"media_type",
")",
"{",
"$",
"media_type",
"=",
"(",
"string",
")",
"$",
"media_type",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"media_type",
",",
"$",
"this",
"->",
"getMediaTypes",
"(",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'Тип файла, значения - \"'.implode('\", \"',",
" ",
"$this->",
"g",
"etMedi",
"a",
"y",
"pes(",
"))",
".'\".');",
"",
"",
"",
"",
"",
"",
"",
"}",
"$",
"this",
"->",
"isModified",
"=",
"true",
";",
"$",
"this",
"->",
"parameters",
"[",
"'media_type'",
"]",
"=",
"$",
"media_type",
";",
"return",
"$",
"this",
";",
"}"
] | Тип файлов, которые нужно включить в список
@param string $media_type
@return $this
@throws \UnexpectedValueException | [
"Тип",
"файлов",
"которые",
"нужно",
"включить",
"в",
"список"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Disk/Filter/MediaTypeTrait.php#L132-L145 |
jack-theripper/yandex | src/Client/Stream/Factory.php | Factory.createStream | public function createStream($body = null)
{
if ( ! $body instanceof StreamInterface)
{
if (is_resource($body))
{
$body = new Stream($body);
}
else
{
$stream = new Stream('php://temp', 'rb+');
if (null !== $body)
{
$stream->write((string) $body);
}
$body = $stream;
}
}
$body->rewind();
return $body;
} | php | public function createStream($body = null)
{
if ( ! $body instanceof StreamInterface)
{
if (is_resource($body))
{
$body = new Stream($body);
}
else
{
$stream = new Stream('php://temp', 'rb+');
if (null !== $body)
{
$stream->write((string) $body);
}
$body = $stream;
}
}
$body->rewind();
return $body;
} | [
"public",
"function",
"createStream",
"(",
"$",
"body",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"body",
"instanceof",
"StreamInterface",
")",
"{",
"if",
"(",
"is_resource",
"(",
"$",
"body",
")",
")",
"{",
"$",
"body",
"=",
"new",
"Stream",
"(",
"$",
"body",
")",
";",
"}",
"else",
"{",
"$",
"stream",
"=",
"new",
"Stream",
"(",
"'php://temp'",
",",
"'rb+'",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"body",
")",
"{",
"$",
"stream",
"->",
"write",
"(",
"(",
"string",
")",
"$",
"body",
")",
";",
"}",
"$",
"body",
"=",
"$",
"stream",
";",
"}",
"}",
"$",
"body",
"->",
"rewind",
"(",
")",
";",
"return",
"$",
"body",
";",
"}"
] | Create a new stream instance.
@param StreamInterface $body
@return null|\Zend\Diactoros\Stream
@throws \RuntimeException
@throws \InvalidArgumentException | [
"Create",
"a",
"new",
"stream",
"instance",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/Stream/Factory.php#L36-L60 |
jack-theripper/yandex | src/Client/OAuth.php | OAuth.refreshAccessToken | public function refreshAccessToken($username, $password, $onlyToken = false)
{
if ( ! is_scalar($username) || ! is_scalar($password))
{
throw new \InvalidArgumentException('Параметры "имя пользователя" и "пароль" должны быть простого типа.');
}
$previous = $this->setAccessTokenRequired(false);
$request = new Request(rtrim(self::API_BASEPATH, ' /').'/token', 'POST');
$request->getBody()
->write(http_build_query([
'grant_type' => 'password',
'client_id' => $this->getClientOauth(),
'client_secret' => $this->getClientOauthSecret(),
'username' => (string) $username,
'password' => (string) $password
]));
try
{
$response = json_decode($this->send($request)->wait()->getBody());
if ($onlyToken)
{
return (string) $response->access_token;
}
$response->created_at = time();
return $response;
}
catch (\Exception $exc)
{
$response = json_decode($exc->getMessage());
if (isset($response->error_description))
{
throw new UnauthorizedException($response->error_description);
}
throw $exc;
}
finally
{
$this->setAccessTokenRequired($previous);
}
} | php | public function refreshAccessToken($username, $password, $onlyToken = false)
{
if ( ! is_scalar($username) || ! is_scalar($password))
{
throw new \InvalidArgumentException('Параметры "имя пользователя" и "пароль" должны быть простого типа.');
}
$previous = $this->setAccessTokenRequired(false);
$request = new Request(rtrim(self::API_BASEPATH, ' /').'/token', 'POST');
$request->getBody()
->write(http_build_query([
'grant_type' => 'password',
'client_id' => $this->getClientOauth(),
'client_secret' => $this->getClientOauthSecret(),
'username' => (string) $username,
'password' => (string) $password
]));
try
{
$response = json_decode($this->send($request)->wait()->getBody());
if ($onlyToken)
{
return (string) $response->access_token;
}
$response->created_at = time();
return $response;
}
catch (\Exception $exc)
{
$response = json_decode($exc->getMessage());
if (isset($response->error_description))
{
throw new UnauthorizedException($response->error_description);
}
throw $exc;
}
finally
{
$this->setAccessTokenRequired($previous);
}
} | [
"public",
"function",
"refreshAccessToken",
"(",
"$",
"username",
",",
"$",
"password",
",",
"$",
"onlyToken",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"username",
")",
"||",
"!",
"is_scalar",
"(",
"$",
"password",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Параметры \"имя пользователя\" и \"пароль\" должны быть простого типа.');",
"",
"",
"}",
"$",
"previous",
"=",
"$",
"this",
"->",
"setAccessTokenRequired",
"(",
"false",
")",
";",
"$",
"request",
"=",
"new",
"Request",
"(",
"rtrim",
"(",
"self",
"::",
"API_BASEPATH",
",",
"' /'",
")",
".",
"'/token'",
",",
"'POST'",
")",
";",
"$",
"request",
"->",
"getBody",
"(",
")",
"->",
"write",
"(",
"http_build_query",
"(",
"[",
"'grant_type'",
"=>",
"'password'",
",",
"'client_id'",
"=>",
"$",
"this",
"->",
"getClientOauth",
"(",
")",
",",
"'client_secret'",
"=>",
"$",
"this",
"->",
"getClientOauthSecret",
"(",
")",
",",
"'username'",
"=>",
"(",
"string",
")",
"$",
"username",
",",
"'password'",
"=>",
"(",
"string",
")",
"$",
"password",
"]",
")",
")",
";",
"try",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"send",
"(",
"$",
"request",
")",
"->",
"wait",
"(",
")",
"->",
"getBody",
"(",
")",
")",
";",
"if",
"(",
"$",
"onlyToken",
")",
"{",
"return",
"(",
"string",
")",
"$",
"response",
"->",
"access_token",
";",
"}",
"$",
"response",
"->",
"created_at",
"=",
"time",
"(",
")",
";",
"return",
"$",
"response",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"exc",
")",
"{",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"exc",
"->",
"getMessage",
"(",
")",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"->",
"error_description",
")",
")",
"{",
"throw",
"new",
"UnauthorizedException",
"(",
"$",
"response",
"->",
"error_description",
")",
";",
"}",
"throw",
"$",
"exc",
";",
"}",
"finally",
"{",
"$",
"this",
"->",
"setAccessTokenRequired",
"(",
"$",
"previous",
")",
";",
"}",
"}"
] | Запрашивает или обновляет токен
@param string $username имя пользователя yandex
@param string $password пароль от аккаунта
@param bool $onlyToken вернуть только строковый токен
@return object|string
@throws UnauthorizedException
@throws \Exception
@example
$client->refreshAccessToken('username', 'password');
object(stdClass)[28]
public 'token_type' => string 'bearer' (length=6)
public 'access_token' => string 'c7621`6b09032dwf9a6a7ca765eb39b8' (length=32)
public 'expires_in' => int 31536000
public 'uid' => int 241`68329
public 'created_at' => int 1456882032
@example
$client->refreshAccessToken('username', 'password', true);
string 'c7621`6b09032dwf9a6a7ca765eb39b8' (length=32) | [
"Запрашивает",
"или",
"обновляет",
"токен"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/OAuth.php#L177-L223 |
jack-theripper/yandex | src/Client/OAuth.php | OAuth.authentication | protected function authentication(RequestInterface $request)
{
if ($this->tokenRequired)
{
return $request->withHeader('Authorization', sprintf('OAuth %s', $this->getAccessToken()));
}
return $request;
} | php | protected function authentication(RequestInterface $request)
{
if ($this->tokenRequired)
{
return $request->withHeader('Authorization', sprintf('OAuth %s', $this->getAccessToken()));
}
return $request;
} | [
"protected",
"function",
"authentication",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"tokenRequired",
")",
"{",
"return",
"$",
"request",
"->",
"withHeader",
"(",
"'Authorization'",
",",
"sprintf",
"(",
"'OAuth %s'",
",",
"$",
"this",
"->",
"getAccessToken",
"(",
")",
")",
")",
";",
"}",
"return",
"$",
"request",
";",
"}"
] | Провести аунтификацию в соостветствии с типом сервиса
@param \Psr\Http\Message\RequestInterface $request
@return \Psr\Http\Message\RequestInterface | [
"Провести",
"аунтификацию",
"в",
"соостветствии",
"с",
"типом",
"сервиса"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/OAuth.php#L232-L240 |
jack-theripper/yandex | src/Client/OAuth.php | OAuth.transformResponseToException | protected function transformResponseToException(RequestInterface $request, ResponseInterface $response)
{
if (isset($this->exceptions[$response->getStatusCode()]))
{
$exception = $this->exceptions[$response->getStatusCode()];
if ($response->hasHeader('Content-Type')
&& stripos($response->getHeaderLine('Content-Type'), 'json') !== false
)
{
$responseBody = json_decode($response->getBody(), true);
if ( ! isset($responseBody['message']))
{
$responseBody['message'] = (string) $response->getBody();
}
if (is_array($exception))
{
if ( ! isset($responseBody['error'], $exception[$responseBody['error']]))
{
return parent::transformResponseToException($request, $response);
}
$exception = $exception[$responseBody['error']];
}
throw new $exception($responseBody['message'], $response->getStatusCode());
}
}
return parent::transformResponseToException($request, $response);
} | php | protected function transformResponseToException(RequestInterface $request, ResponseInterface $response)
{
if (isset($this->exceptions[$response->getStatusCode()]))
{
$exception = $this->exceptions[$response->getStatusCode()];
if ($response->hasHeader('Content-Type')
&& stripos($response->getHeaderLine('Content-Type'), 'json') !== false
)
{
$responseBody = json_decode($response->getBody(), true);
if ( ! isset($responseBody['message']))
{
$responseBody['message'] = (string) $response->getBody();
}
if (is_array($exception))
{
if ( ! isset($responseBody['error'], $exception[$responseBody['error']]))
{
return parent::transformResponseToException($request, $response);
}
$exception = $exception[$responseBody['error']];
}
throw new $exception($responseBody['message'], $response->getStatusCode());
}
}
return parent::transformResponseToException($request, $response);
} | [
"protected",
"function",
"transformResponseToException",
"(",
"RequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"exceptions",
"[",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"]",
")",
")",
"{",
"$",
"exception",
"=",
"$",
"this",
"->",
"exceptions",
"[",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"]",
";",
"if",
"(",
"$",
"response",
"->",
"hasHeader",
"(",
"'Content-Type'",
")",
"&&",
"stripos",
"(",
"$",
"response",
"->",
"getHeaderLine",
"(",
"'Content-Type'",
")",
",",
"'json'",
")",
"!==",
"false",
")",
"{",
"$",
"responseBody",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"responseBody",
"[",
"'message'",
"]",
")",
")",
"{",
"$",
"responseBody",
"[",
"'message'",
"]",
"=",
"(",
"string",
")",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"exception",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"responseBody",
"[",
"'error'",
"]",
",",
"$",
"exception",
"[",
"$",
"responseBody",
"[",
"'error'",
"]",
"]",
")",
")",
"{",
"return",
"parent",
"::",
"transformResponseToException",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
"$",
"exception",
"=",
"$",
"exception",
"[",
"$",
"responseBody",
"[",
"'error'",
"]",
"]",
";",
"}",
"throw",
"new",
"$",
"exception",
"(",
"$",
"responseBody",
"[",
"'message'",
"]",
",",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
";",
"}",
"}",
"return",
"parent",
"::",
"transformResponseToException",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"}"
] | Трансформирует ответ в исключения.
Ответ API, где использует OAuth, отличается от других сервисов.
@param \Psr\Http\Message\RequestInterface $request
@param \Psr\Http\Message\ResponseInterface $response
@return \Psr\Http\Message\ResponseInterface если статус код не является ошибочным, то вернуть объект ответа | [
"Трансформирует",
"ответ",
"в",
"исключения",
".",
"Ответ",
"API",
"где",
"использует",
"OAuth",
"отличается",
"от",
"других",
"сервисов",
"."
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/OAuth.php#L251-L283 |
jack-theripper/yandex | src/Client/Container/ContainerTrait.php | ContainerTrait.toArray | public function toArray(array $allowed = null)
{
$contents = $this->store;
if ($allowed !== null)
{
$contents = array_intersect_key($this->store, array_flip($allowed));
}
/*foreach ($contents as $index => $value)
{
if ($value instanceof Container || $value instanceof AbstractResource)
{
$contents[$index] = $value->toArray();
}
}*/
return $contents;
} | php | public function toArray(array $allowed = null)
{
$contents = $this->store;
if ($allowed !== null)
{
$contents = array_intersect_key($this->store, array_flip($allowed));
}
/*foreach ($contents as $index => $value)
{
if ($value instanceof Container || $value instanceof AbstractResource)
{
$contents[$index] = $value->toArray();
}
}*/
return $contents;
} | [
"public",
"function",
"toArray",
"(",
"array",
"$",
"allowed",
"=",
"null",
")",
"{",
"$",
"contents",
"=",
"$",
"this",
"->",
"store",
";",
"if",
"(",
"$",
"allowed",
"!==",
"null",
")",
"{",
"$",
"contents",
"=",
"array_intersect_key",
"(",
"$",
"this",
"->",
"store",
",",
"array_flip",
"(",
"$",
"allowed",
")",
")",
";",
"}",
"/*foreach ($contents as $index => $value)\n\t\t{\n\t\t\tif ($value instanceof Container || $value instanceof AbstractResource)\n\t\t\t{\n\t\t\t\t$contents[$index] = $value->toArray();\n\t\t\t}\n\t\t}*/",
"return",
"$",
"contents",
";",
"}"
] | Получить данные контейнера в виде массива
@param array $allowed получить только эти ключи
@return array контейнер | [
"Получить",
"данные",
"контейнера",
"в",
"виде",
"массива"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/Container/ContainerTrait.php#L45-L63 |
jack-theripper/yandex | src/Client/Container/ContainerTrait.php | ContainerTrait.get | public function get($index, $default = null)
{
if ($this->hasByIndex($index))
{
return $this->store[$index];
}
if ($default instanceof \Closure)
{
return $default($this);
}
return $default;
} | php | public function get($index, $default = null)
{
if ($this->hasByIndex($index))
{
return $this->store[$index];
}
if ($default instanceof \Closure)
{
return $default($this);
}
return $default;
} | [
"public",
"function",
"get",
"(",
"$",
"index",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasByIndex",
"(",
"$",
"index",
")",
")",
"{",
"return",
"$",
"this",
"->",
"store",
"[",
"$",
"index",
"]",
";",
"}",
"if",
"(",
"$",
"default",
"instanceof",
"\\",
"Closure",
")",
"{",
"return",
"$",
"default",
"(",
"$",
"this",
")",
";",
"}",
"return",
"$",
"default",
";",
"}"
] | Получить значение из контейнера по ключу
@param string $index
@param mixed $default может быть функцией
@return mixed | [
"Получить",
"значение",
"из",
"контейнера",
"по",
"ключу"
] | train | https://github.com/jack-theripper/yandex/blob/db78fae891552c9b1c8d0b043e9ebf879b918a18/src/Client/Container/ContainerTrait.php#L139-L152 |
acquia/drupal-spec-tool | src/Context/ContentModelContext.php | ContentModelContext.assertBundles | public function assertBundles(TableNode $expected) {
$bundle_info = [];
foreach ($this->getContentEntityTypes() as $entity_type) {
$bundles = $this->entityTypeManager()
->getStorage($entity_type->getBundleEntityType())
->loadMultiple();
foreach ($bundles as $bundle) {
$description = '';
$description_getter = 'getDescription';
if (method_exists($bundle, $description_getter)) {
$description = call_user_func([
$bundle,
$description_getter,
]);
}
if (!isset($description) || !$description) {
$description = '';
}
$bundle_info[] = [
$bundle->label(),
$bundle->id(),
$entity_type->getBundleLabel(),
$description,
];
}
}
$actual = new TableNode($bundle_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Name',
'Machine name',
'Type',
'Description',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
->assert();
} | php | public function assertBundles(TableNode $expected) {
$bundle_info = [];
foreach ($this->getContentEntityTypes() as $entity_type) {
$bundles = $this->entityTypeManager()
->getStorage($entity_type->getBundleEntityType())
->loadMultiple();
foreach ($bundles as $bundle) {
$description = '';
$description_getter = 'getDescription';
if (method_exists($bundle, $description_getter)) {
$description = call_user_func([
$bundle,
$description_getter,
]);
}
if (!isset($description) || !$description) {
$description = '';
}
$bundle_info[] = [
$bundle->label(),
$bundle->id(),
$entity_type->getBundleLabel(),
$description,
];
}
}
$actual = new TableNode($bundle_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Name',
'Machine name',
'Type',
'Description',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
->assert();
} | [
"public",
"function",
"assertBundles",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"bundle_info",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getContentEntityTypes",
"(",
")",
"as",
"$",
"entity_type",
")",
"{",
"$",
"bundles",
"=",
"$",
"this",
"->",
"entityTypeManager",
"(",
")",
"->",
"getStorage",
"(",
"$",
"entity_type",
"->",
"getBundleEntityType",
"(",
")",
")",
"->",
"loadMultiple",
"(",
")",
";",
"foreach",
"(",
"$",
"bundles",
"as",
"$",
"bundle",
")",
"{",
"$",
"description",
"=",
"''",
";",
"$",
"description_getter",
"=",
"'getDescription'",
";",
"if",
"(",
"method_exists",
"(",
"$",
"bundle",
",",
"$",
"description_getter",
")",
")",
"{",
"$",
"description",
"=",
"call_user_func",
"(",
"[",
"$",
"bundle",
",",
"$",
"description_getter",
",",
"]",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"description",
")",
"||",
"!",
"$",
"description",
")",
"{",
"$",
"description",
"=",
"''",
";",
"}",
"$",
"bundle_info",
"[",
"]",
"=",
"[",
"$",
"bundle",
"->",
"label",
"(",
")",
",",
"$",
"bundle",
"->",
"id",
"(",
")",
",",
"$",
"entity_type",
"->",
"getBundleLabel",
"(",
")",
",",
"$",
"description",
",",
"]",
";",
"}",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"bundle_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Name'",
",",
"'Machine name'",
",",
"'Type'",
",",
"'Description'",
",",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'bundles'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'bundles'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of content entity type bundles.
@Then exactly the following content entity type bundles should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"content",
"entity",
"type",
"bundles",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/ContentModelContext.php#L54-L94 |
acquia/drupal-spec-tool | src/Context/ContentModelContext.php | ContentModelContext.assertFields | public function assertFields(TableNode $expected) {
$fields = [];
foreach ($this->getContentEntityTypes() as $entity_type) {
$bundles = $this->entityTypeManager()
->getStorage($entity_type->getBundleEntityType())
->loadMultiple();
foreach ($bundles as $bundle) {
/** @var string[] $ids */
$ids = \Drupal::entityQuery('field_config')
->condition('bundle', $bundle->id())
->condition('entity_type', $entity_type->id())
->execute();
if (!$ids) {
continue;
}
$display_id = "{$entity_type->id()}.{$bundle->id()}.default";
$form_display = EntityFormDisplay::load($display_id);
if (is_null($form_display)) {
throw new \Exception(sprintf('No such form display: %s. Try saving the "Manage form display" form for the "%s" %s.', $display_id, $bundle->label(), strtolower($entity_type->getBundleLabel())));
}
$form_components = $form_display->getComponents();
/** @var \Drupal\field\FieldConfigInterface $field_config */
foreach (FieldConfig::loadMultiple($ids) as $id => $field_config) {
$machine_name = $this->getFieldMachineNameFromConfigId($id);
$field_storage = $field_config->getFieldStorageDefinition();
$fields[] = [
$bundle->label(),
$field_config->getLabel(),
$machine_name,
(string) $this->fieldTypeManager->getDefinition($field_config->getType())['label'],
$field_config->isRequired() ? 'Required' : '',
$field_storage->getCardinality() === -1 ? 'Unlimited' : $field_storage->getCardinality(),
isset($form_components[$machine_name]['type']) ? (string) $this->fieldWidgetManager->getDefinition($form_components[$machine_name]['type'])['label'] : '-- Disabled --',
$field_config->isTranslatable() ? 'Translatable' : '',
$field_config->getDescription(),
];
}
}
}
$actual = new TableNode($fields);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Bundle',
'Field label',
'Machine name',
'Field type',
'Required',
'Cardinality',
'Form widget',
'Translatable',
'Help text',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('fields'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('fields'))
->assert();
} | php | public function assertFields(TableNode $expected) {
$fields = [];
foreach ($this->getContentEntityTypes() as $entity_type) {
$bundles = $this->entityTypeManager()
->getStorage($entity_type->getBundleEntityType())
->loadMultiple();
foreach ($bundles as $bundle) {
/** @var string[] $ids */
$ids = \Drupal::entityQuery('field_config')
->condition('bundle', $bundle->id())
->condition('entity_type', $entity_type->id())
->execute();
if (!$ids) {
continue;
}
$display_id = "{$entity_type->id()}.{$bundle->id()}.default";
$form_display = EntityFormDisplay::load($display_id);
if (is_null($form_display)) {
throw new \Exception(sprintf('No such form display: %s. Try saving the "Manage form display" form for the "%s" %s.', $display_id, $bundle->label(), strtolower($entity_type->getBundleLabel())));
}
$form_components = $form_display->getComponents();
/** @var \Drupal\field\FieldConfigInterface $field_config */
foreach (FieldConfig::loadMultiple($ids) as $id => $field_config) {
$machine_name = $this->getFieldMachineNameFromConfigId($id);
$field_storage = $field_config->getFieldStorageDefinition();
$fields[] = [
$bundle->label(),
$field_config->getLabel(),
$machine_name,
(string) $this->fieldTypeManager->getDefinition($field_config->getType())['label'],
$field_config->isRequired() ? 'Required' : '',
$field_storage->getCardinality() === -1 ? 'Unlimited' : $field_storage->getCardinality(),
isset($form_components[$machine_name]['type']) ? (string) $this->fieldWidgetManager->getDefinition($form_components[$machine_name]['type'])['label'] : '-- Disabled --',
$field_config->isTranslatable() ? 'Translatable' : '',
$field_config->getDescription(),
];
}
}
}
$actual = new TableNode($fields);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Bundle',
'Field label',
'Machine name',
'Field type',
'Required',
'Cardinality',
'Form widget',
'Translatable',
'Help text',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('fields'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('fields'))
->assert();
} | [
"public",
"function",
"assertFields",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"fields",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getContentEntityTypes",
"(",
")",
"as",
"$",
"entity_type",
")",
"{",
"$",
"bundles",
"=",
"$",
"this",
"->",
"entityTypeManager",
"(",
")",
"->",
"getStorage",
"(",
"$",
"entity_type",
"->",
"getBundleEntityType",
"(",
")",
")",
"->",
"loadMultiple",
"(",
")",
";",
"foreach",
"(",
"$",
"bundles",
"as",
"$",
"bundle",
")",
"{",
"/** @var string[] $ids */",
"$",
"ids",
"=",
"\\",
"Drupal",
"::",
"entityQuery",
"(",
"'field_config'",
")",
"->",
"condition",
"(",
"'bundle'",
",",
"$",
"bundle",
"->",
"id",
"(",
")",
")",
"->",
"condition",
"(",
"'entity_type'",
",",
"$",
"entity_type",
"->",
"id",
"(",
")",
")",
"->",
"execute",
"(",
")",
";",
"if",
"(",
"!",
"$",
"ids",
")",
"{",
"continue",
";",
"}",
"$",
"display_id",
"=",
"\"{$entity_type->id()}.{$bundle->id()}.default\"",
";",
"$",
"form_display",
"=",
"EntityFormDisplay",
"::",
"load",
"(",
"$",
"display_id",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"form_display",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"sprintf",
"(",
"'No such form display: %s. Try saving the \"Manage form display\" form for the \"%s\" %s.'",
",",
"$",
"display_id",
",",
"$",
"bundle",
"->",
"label",
"(",
")",
",",
"strtolower",
"(",
"$",
"entity_type",
"->",
"getBundleLabel",
"(",
")",
")",
")",
")",
";",
"}",
"$",
"form_components",
"=",
"$",
"form_display",
"->",
"getComponents",
"(",
")",
";",
"/** @var \\Drupal\\field\\FieldConfigInterface $field_config */",
"foreach",
"(",
"FieldConfig",
"::",
"loadMultiple",
"(",
"$",
"ids",
")",
"as",
"$",
"id",
"=>",
"$",
"field_config",
")",
"{",
"$",
"machine_name",
"=",
"$",
"this",
"->",
"getFieldMachineNameFromConfigId",
"(",
"$",
"id",
")",
";",
"$",
"field_storage",
"=",
"$",
"field_config",
"->",
"getFieldStorageDefinition",
"(",
")",
";",
"$",
"fields",
"[",
"]",
"=",
"[",
"$",
"bundle",
"->",
"label",
"(",
")",
",",
"$",
"field_config",
"->",
"getLabel",
"(",
")",
",",
"$",
"machine_name",
",",
"(",
"string",
")",
"$",
"this",
"->",
"fieldTypeManager",
"->",
"getDefinition",
"(",
"$",
"field_config",
"->",
"getType",
"(",
")",
")",
"[",
"'label'",
"]",
",",
"$",
"field_config",
"->",
"isRequired",
"(",
")",
"?",
"'Required'",
":",
"''",
",",
"$",
"field_storage",
"->",
"getCardinality",
"(",
")",
"===",
"-",
"1",
"?",
"'Unlimited'",
":",
"$",
"field_storage",
"->",
"getCardinality",
"(",
")",
",",
"isset",
"(",
"$",
"form_components",
"[",
"$",
"machine_name",
"]",
"[",
"'type'",
"]",
")",
"?",
"(",
"string",
")",
"$",
"this",
"->",
"fieldWidgetManager",
"->",
"getDefinition",
"(",
"$",
"form_components",
"[",
"$",
"machine_name",
"]",
"[",
"'type'",
"]",
")",
"[",
"'label'",
"]",
":",
"'-- Disabled --'",
",",
"$",
"field_config",
"->",
"isTranslatable",
"(",
")",
"?",
"'Translatable'",
":",
"''",
",",
"$",
"field_config",
"->",
"getDescription",
"(",
")",
",",
"]",
";",
"}",
"}",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"fields",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Bundle'",
",",
"'Field label'",
",",
"'Machine name'",
",",
"'Field type'",
",",
"'Required'",
",",
"'Cardinality'",
",",
"'Form widget'",
",",
"'Translatable'",
",",
"'Help text'",
",",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'fields'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'fields'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of fields on select content entity types.
@Then exactly the following fields should exist
@throws \Exception
@see ContentModelContext::getContentEntityTypes | [
"Asserts",
"the",
"configuration",
"of",
"fields",
"on",
"select",
"content",
"entity",
"types",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/ContentModelContext.php#L105-L165 |
acquia/drupal-spec-tool | src/Context/ContentModelContext.php | ContentModelContext.getContentEntityTypes | protected function getContentEntityTypes() {
$ids = [
'block_content',
'media',
'node',
'paragraph',
'taxonomy_term',
];
$entity_types = [];
foreach ($ids as $id) {
try {
$entity_types[] = $this->entityTypeManager()->getDefinition($id);
}
catch (PluginNotFoundException $e) {
// A PluginNotFoundException here just means that the module providing
// the entity type in question isn't installed. Continue.
}
}
return $entity_types;
} | php | protected function getContentEntityTypes() {
$ids = [
'block_content',
'media',
'node',
'paragraph',
'taxonomy_term',
];
$entity_types = [];
foreach ($ids as $id) {
try {
$entity_types[] = $this->entityTypeManager()->getDefinition($id);
}
catch (PluginNotFoundException $e) {
// A PluginNotFoundException here just means that the module providing
// the entity type in question isn't installed. Continue.
}
}
return $entity_types;
} | [
"protected",
"function",
"getContentEntityTypes",
"(",
")",
"{",
"$",
"ids",
"=",
"[",
"'block_content'",
",",
"'media'",
",",
"'node'",
",",
"'paragraph'",
",",
"'taxonomy_term'",
",",
"]",
";",
"$",
"entity_types",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"ids",
"as",
"$",
"id",
")",
"{",
"try",
"{",
"$",
"entity_types",
"[",
"]",
"=",
"$",
"this",
"->",
"entityTypeManager",
"(",
")",
"->",
"getDefinition",
"(",
"$",
"id",
")",
";",
"}",
"catch",
"(",
"PluginNotFoundException",
"$",
"e",
")",
"{",
"// A PluginNotFoundException here just means that the module providing",
"// the entity type in question isn't installed. Continue.",
"}",
"}",
"return",
"$",
"entity_types",
";",
"}"
] | Gets the content entity types of interest.
@return \Drupal\Core\Entity\EntityTypeInterface[]
An array of entity types. | [
"Gets",
"the",
"content",
"entity",
"types",
"of",
"interest",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/ContentModelContext.php#L173-L192 |
acquia/drupal-spec-tool | src/Context/MenuContext.php | MenuContext.assertMenusExist | public function assertMenusExist(TableNode $expected) {
$menu_info = [];
/** @var \Drupal\system\Entity\Menu $menu */
$menus = $this->entityTypeManager()
->getStorage('menu')
->loadMultiple();
foreach ($menus as $id => $menu) {
$menu_info[] = [$menu->label(), $id, $menu->getDescription()];
}
$actual = new TableNode($menu_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader(['Name', 'Machine name', 'Description'])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('menus'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('menus'))
->assert();
} | php | public function assertMenusExist(TableNode $expected) {
$menu_info = [];
/** @var \Drupal\system\Entity\Menu $menu */
$menus = $this->entityTypeManager()
->getStorage('menu')
->loadMultiple();
foreach ($menus as $id => $menu) {
$menu_info[] = [$menu->label(), $id, $menu->getDescription()];
}
$actual = new TableNode($menu_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader(['Name', 'Machine name', 'Description'])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('menus'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('menus'))
->assert();
} | [
"public",
"function",
"assertMenusExist",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"menu_info",
"=",
"[",
"]",
";",
"/** @var \\Drupal\\system\\Entity\\Menu $menu */",
"$",
"menus",
"=",
"$",
"this",
"->",
"entityTypeManager",
"(",
")",
"->",
"getStorage",
"(",
"'menu'",
")",
"->",
"loadMultiple",
"(",
")",
";",
"foreach",
"(",
"$",
"menus",
"as",
"$",
"id",
"=>",
"$",
"menu",
")",
"{",
"$",
"menu_info",
"[",
"]",
"=",
"[",
"$",
"menu",
"->",
"label",
"(",
")",
",",
"$",
"id",
",",
"$",
"menu",
"->",
"getDescription",
"(",
")",
"]",
";",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"menu_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Name'",
",",
"'Machine name'",
",",
"'Description'",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'menus'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'menus'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of menus.
@Then exactly the following menus should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"menus",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/MenuContext.php#L20-L37 |
acquia/drupal-spec-tool | src/Context/MediaContext.php | MediaContext.assertImageStyles | public function assertImageStyles(TableNode $expected) {
$image_style_info = [];
foreach ($this->getImageStyles() as $image_style) {
$image_style_info[] = [
$image_style->label(),
$image_style->id(),
];
}
$actual = new TableNode($image_style_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Style name',
'Machine name',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('workflow'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow'))
->assert();
} | php | public function assertImageStyles(TableNode $expected) {
$image_style_info = [];
foreach ($this->getImageStyles() as $image_style) {
$image_style_info[] = [
$image_style->label(),
$image_style->id(),
];
}
$actual = new TableNode($image_style_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Style name',
'Machine name',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('workflow'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow'))
->assert();
} | [
"public",
"function",
"assertImageStyles",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"image_style_info",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getImageStyles",
"(",
")",
"as",
"$",
"image_style",
")",
"{",
"$",
"image_style_info",
"[",
"]",
"=",
"[",
"$",
"image_style",
"->",
"label",
"(",
")",
",",
"$",
"image_style",
"->",
"id",
"(",
")",
",",
"]",
";",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"image_style_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Style name'",
",",
"'Machine name'",
",",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'workflow'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'workflow'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of image styles.
@Then exactly the following image styles should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"image",
"styles",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/MediaContext.php#L43-L62 |
acquia/drupal-spec-tool | src/Context/MediaContext.php | MediaContext.assertImageEffects | public function assertImageEffects(TableNode $expected) {
$image_style_info = [];
foreach ($this->getImageStyles() as $image_style) {
foreach ($image_style->getEffects() as $effect) {
$image_style_info[] = [
$image_style->label(),
(string) $effect->label(),
$this->formatImageEffectSummary($effect->getSummary()),
];
}
}
$actual = new TableNode($image_style_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Image style',
'Effect',
'Summary',
])
->setMissingRowsLabel(self::missingRowsLabelFor('workflow'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow'))
->assert();
} | php | public function assertImageEffects(TableNode $expected) {
$image_style_info = [];
foreach ($this->getImageStyles() as $image_style) {
foreach ($image_style->getEffects() as $effect) {
$image_style_info[] = [
$image_style->label(),
(string) $effect->label(),
$this->formatImageEffectSummary($effect->getSummary()),
];
}
}
$actual = new TableNode($image_style_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Image style',
'Effect',
'Summary',
])
->setMissingRowsLabel(self::missingRowsLabelFor('workflow'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow'))
->assert();
} | [
"public",
"function",
"assertImageEffects",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"image_style_info",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getImageStyles",
"(",
")",
"as",
"$",
"image_style",
")",
"{",
"foreach",
"(",
"$",
"image_style",
"->",
"getEffects",
"(",
")",
"as",
"$",
"effect",
")",
"{",
"$",
"image_style_info",
"[",
"]",
"=",
"[",
"$",
"image_style",
"->",
"label",
"(",
")",
",",
"(",
"string",
")",
"$",
"effect",
"->",
"label",
"(",
")",
",",
"$",
"this",
"->",
"formatImageEffectSummary",
"(",
"$",
"effect",
"->",
"getSummary",
"(",
")",
")",
",",
"]",
";",
"}",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"image_style_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Image style'",
",",
"'Effect'",
",",
"'Summary'",
",",
"]",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'workflow'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'workflow'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of image effects.
@Then exactly the following image effects should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"image",
"effects",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/MediaContext.php#L71-L93 |
acquia/drupal-spec-tool | src/Context/MediaContext.php | MediaContext.formatImageEffectSummary | private function formatImageEffectSummary(array $summary) {
$rendered = (string) $this->renderer->renderPlain($summary);
$plaintext = strip_tags($rendered);
$trimmed = trim($plaintext);
$one_line = preg_replace('/[ \n]+/', ' ', $trimmed);
return $one_line;
} | php | private function formatImageEffectSummary(array $summary) {
$rendered = (string) $this->renderer->renderPlain($summary);
$plaintext = strip_tags($rendered);
$trimmed = trim($plaintext);
$one_line = preg_replace('/[ \n]+/', ' ', $trimmed);
return $one_line;
} | [
"private",
"function",
"formatImageEffectSummary",
"(",
"array",
"$",
"summary",
")",
"{",
"$",
"rendered",
"=",
"(",
"string",
")",
"$",
"this",
"->",
"renderer",
"->",
"renderPlain",
"(",
"$",
"summary",
")",
";",
"$",
"plaintext",
"=",
"strip_tags",
"(",
"$",
"rendered",
")",
";",
"$",
"trimmed",
"=",
"trim",
"(",
"$",
"plaintext",
")",
";",
"$",
"one_line",
"=",
"preg_replace",
"(",
"'/[ \\n]+/'",
",",
"' '",
",",
"$",
"trimmed",
")",
";",
"return",
"$",
"one_line",
";",
"}"
] | Formats an image effect summary for use in a Gherkin data table.
@param array $summary
An image effect summary render array.
@return string
The summary formatted for use in a Gherkin data table. | [
"Formats",
"an",
"image",
"effect",
"summary",
"for",
"use",
"in",
"a",
"Gherkin",
"data",
"table",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/MediaContext.php#L120-L126 |
acquia/drupal-spec-tool | src/Context/WorkflowContext.php | WorkflowContext.assertWorkflows | public function assertWorkflows(TableNode $expected) {
$workflow_info = [];
foreach ($this->getWorkflows() as $workflow) {
$workflow_info[] = [
$workflow->label(),
$workflow->id(),
(string) $workflow->getTypePlugin()->label(),
];
}
$actual = new TableNode($workflow_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Label',
'Machine name',
'Type',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('workflow'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow'))
->assert();
} | php | public function assertWorkflows(TableNode $expected) {
$workflow_info = [];
foreach ($this->getWorkflows() as $workflow) {
$workflow_info[] = [
$workflow->label(),
$workflow->id(),
(string) $workflow->getTypePlugin()->label(),
];
}
$actual = new TableNode($workflow_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Label',
'Machine name',
'Type',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('workflow'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow'))
->assert();
} | [
"public",
"function",
"assertWorkflows",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"workflow_info",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getWorkflows",
"(",
")",
"as",
"$",
"workflow",
")",
"{",
"$",
"workflow_info",
"[",
"]",
"=",
"[",
"$",
"workflow",
"->",
"label",
"(",
")",
",",
"$",
"workflow",
"->",
"id",
"(",
")",
",",
"(",
"string",
")",
"$",
"workflow",
"->",
"getTypePlugin",
"(",
")",
"->",
"label",
"(",
")",
",",
"]",
";",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"workflow_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Label'",
",",
"'Machine name'",
",",
"'Type'",
",",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'workflow'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'workflow'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of workflows.
@Then exactly the following workflows should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"workflows",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/WorkflowContext.php#L35-L56 |
acquia/drupal-spec-tool | src/Context/WorkflowContext.php | WorkflowContext.assertWorkflowStates | public function assertWorkflowStates(TableNode $expected) {
$states_info = [];
foreach ($this->getWorkflows() as $workflow) {
/** @var \Drupal\workflows\StateInterface[] $states */
$states = $workflow->getTypePlugin()->getStates();
foreach ($states as $state) {
$states_info[] = [
$workflow->label(),
$state->label(),
$state->id(),
];
}
}
$actual = new TableNode($states_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Workflow',
'Label',
'Machine name',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('workflow states'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow states'))
->assert();
} | php | public function assertWorkflowStates(TableNode $expected) {
$states_info = [];
foreach ($this->getWorkflows() as $workflow) {
/** @var \Drupal\workflows\StateInterface[] $states */
$states = $workflow->getTypePlugin()->getStates();
foreach ($states as $state) {
$states_info[] = [
$workflow->label(),
$state->label(),
$state->id(),
];
}
}
$actual = new TableNode($states_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Workflow',
'Label',
'Machine name',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('workflow states'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow states'))
->assert();
} | [
"public",
"function",
"assertWorkflowStates",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"states_info",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getWorkflows",
"(",
")",
"as",
"$",
"workflow",
")",
"{",
"/** @var \\Drupal\\workflows\\StateInterface[] $states */",
"$",
"states",
"=",
"$",
"workflow",
"->",
"getTypePlugin",
"(",
")",
"->",
"getStates",
"(",
")",
";",
"foreach",
"(",
"$",
"states",
"as",
"$",
"state",
")",
"{",
"$",
"states_info",
"[",
"]",
"=",
"[",
"$",
"workflow",
"->",
"label",
"(",
")",
",",
"$",
"state",
"->",
"label",
"(",
")",
",",
"$",
"state",
"->",
"id",
"(",
")",
",",
"]",
";",
"}",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"states_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Workflow'",
",",
"'Label'",
",",
"'Machine name'",
",",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'workflow states'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'workflow states'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of workflow states.
@Then exactly the following workflow states should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"workflow",
"states",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/WorkflowContext.php#L65-L90 |
acquia/drupal-spec-tool | src/Context/WorkflowContext.php | WorkflowContext.assertWorkflowTransitions | public function assertWorkflowTransitions(TableNode $expected) {
$states_info = [];
foreach ($this->getWorkflows() as $workflow) {
/** @var \Drupal\workflows\TransitionInterface[] $transitions */
$transitions = $workflow->getTypePlugin()->getTransitions();
foreach ($transitions as $transition) {
foreach ($transition->from() as $from_state) {
$states_info[] = [
$workflow->label(),
$transition->label(),
$transition->id(),
$from_state->label(),
$transition->to()->label(),
];
}
}
}
$actual = new TableNode($states_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Workflow',
'Label',
'Machine name',
'From state',
'To state',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('workflow states'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow states'))
->assert();
} | php | public function assertWorkflowTransitions(TableNode $expected) {
$states_info = [];
foreach ($this->getWorkflows() as $workflow) {
/** @var \Drupal\workflows\TransitionInterface[] $transitions */
$transitions = $workflow->getTypePlugin()->getTransitions();
foreach ($transitions as $transition) {
foreach ($transition->from() as $from_state) {
$states_info[] = [
$workflow->label(),
$transition->label(),
$transition->id(),
$from_state->label(),
$transition->to()->label(),
];
}
}
}
$actual = new TableNode($states_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Workflow',
'Label',
'Machine name',
'From state',
'To state',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('workflow states'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow states'))
->assert();
} | [
"public",
"function",
"assertWorkflowTransitions",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"states_info",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getWorkflows",
"(",
")",
"as",
"$",
"workflow",
")",
"{",
"/** @var \\Drupal\\workflows\\TransitionInterface[] $transitions */",
"$",
"transitions",
"=",
"$",
"workflow",
"->",
"getTypePlugin",
"(",
")",
"->",
"getTransitions",
"(",
")",
";",
"foreach",
"(",
"$",
"transitions",
"as",
"$",
"transition",
")",
"{",
"foreach",
"(",
"$",
"transition",
"->",
"from",
"(",
")",
"as",
"$",
"from_state",
")",
"{",
"$",
"states_info",
"[",
"]",
"=",
"[",
"$",
"workflow",
"->",
"label",
"(",
")",
",",
"$",
"transition",
"->",
"label",
"(",
")",
",",
"$",
"transition",
"->",
"id",
"(",
")",
",",
"$",
"from_state",
"->",
"label",
"(",
")",
",",
"$",
"transition",
"->",
"to",
"(",
")",
"->",
"label",
"(",
")",
",",
"]",
";",
"}",
"}",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"states_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Workflow'",
",",
"'Label'",
",",
"'Machine name'",
",",
"'From state'",
",",
"'To state'",
",",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'workflow states'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'workflow states'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of workflow transitions.
@Then exactly the following workflow transitions should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"workflow",
"transitions",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/WorkflowContext.php#L99-L133 |
acquia/drupal-spec-tool | src/Context/AccessControlContext.php | AccessControlContext.assertRolesExist | public function assertRolesExist(TableNode $expected) {
$role_info = [];
/** @var \Drupal\user\Entity\Role[] $roles */
$roles = $this->entityTypeManager()
->getStorage('user_role')
->loadMultiple();
foreach ($roles as $id => $role) {
$role_info[] = [$role->label(), $id];
}
$actual = new TableNode($role_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader(['Name', 'Machine name'])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('roles'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('roles'))
->assert();
} | php | public function assertRolesExist(TableNode $expected) {
$role_info = [];
/** @var \Drupal\user\Entity\Role[] $roles */
$roles = $this->entityTypeManager()
->getStorage('user_role')
->loadMultiple();
foreach ($roles as $id => $role) {
$role_info[] = [$role->label(), $id];
}
$actual = new TableNode($role_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader(['Name', 'Machine name'])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('roles'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('roles'))
->assert();
} | [
"public",
"function",
"assertRolesExist",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"role_info",
"=",
"[",
"]",
";",
"/** @var \\Drupal\\user\\Entity\\Role[] $roles */",
"$",
"roles",
"=",
"$",
"this",
"->",
"entityTypeManager",
"(",
")",
"->",
"getStorage",
"(",
"'user_role'",
")",
"->",
"loadMultiple",
"(",
")",
";",
"foreach",
"(",
"$",
"roles",
"as",
"$",
"id",
"=>",
"$",
"role",
")",
"{",
"$",
"role_info",
"[",
"]",
"=",
"[",
"$",
"role",
"->",
"label",
"(",
")",
",",
"$",
"id",
"]",
";",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"role_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Name'",
",",
"'Machine name'",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'roles'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'roles'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of roles.
@Then exactly the following roles should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"roles",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/AccessControlContext.php#L20-L37 |
acquia/drupal-spec-tool | src/Context/ViewsContext.php | ViewsContext.assertViewsExist | public function assertViewsExist(TableNode $expected) {
$views_info = [];
foreach ($this->getViews() as $id => $view) {
$views_info[] = [
$view->label(),
$id,
$this->getBaseTableLabel($view->get('base_table')),
$view->status() ? 'Enabled' : 'Disabled',
$view->get('description'),
];
}
$actual = new TableNode($views_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Name',
'Machine name',
'Base table',
'Status',
'Description',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('views'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('views'))
->assert();
} | php | public function assertViewsExist(TableNode $expected) {
$views_info = [];
foreach ($this->getViews() as $id => $view) {
$views_info[] = [
$view->label(),
$id,
$this->getBaseTableLabel($view->get('base_table')),
$view->status() ? 'Enabled' : 'Disabled',
$view->get('description'),
];
}
$actual = new TableNode($views_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'Name',
'Machine name',
'Base table',
'Status',
'Description',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('views'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('views'))
->assert();
} | [
"public",
"function",
"assertViewsExist",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"views_info",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getViews",
"(",
")",
"as",
"$",
"id",
"=>",
"$",
"view",
")",
"{",
"$",
"views_info",
"[",
"]",
"=",
"[",
"$",
"view",
"->",
"label",
"(",
")",
",",
"$",
"id",
",",
"$",
"this",
"->",
"getBaseTableLabel",
"(",
"$",
"view",
"->",
"get",
"(",
"'base_table'",
")",
")",
",",
"$",
"view",
"->",
"status",
"(",
")",
"?",
"'Enabled'",
":",
"'Disabled'",
",",
"$",
"view",
"->",
"get",
"(",
"'description'",
")",
",",
"]",
";",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"views_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'Name'",
",",
"'Machine name'",
",",
"'Base table'",
",",
"'Status'",
",",
"'Description'",
",",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'views'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'views'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of views.
@Then exactly the following views should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"views",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/ViewsContext.php#L51-L76 |
acquia/drupal-spec-tool | src/Context/ViewsContext.php | ViewsContext.assertViewDisplaysExist | public function assertViewDisplaysExist(TableNode $expected) {
$displays_info = [];
foreach ($this->getViews() as $view) {
/** @var array $display */
foreach ($view->get('display') as $display) {
$definition = $this->viewsDisplayManager
->getDefinition($display['display_plugin']);
$displays_info[] = [
$view->label(),
$display['display_title'],
$display['id'],
(string) $definition['title'],
];
}
}
$actual = new TableNode($displays_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'View',
'Title',
'Machine name',
'Display plugin',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('views'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('views'))
->assert();
} | php | public function assertViewDisplaysExist(TableNode $expected) {
$displays_info = [];
foreach ($this->getViews() as $view) {
/** @var array $display */
foreach ($view->get('display') as $display) {
$definition = $this->viewsDisplayManager
->getDefinition($display['display_plugin']);
$displays_info[] = [
$view->label(),
$display['display_title'],
$display['id'],
(string) $definition['title'],
];
}
}
$actual = new TableNode($displays_info);
(new TableEqualityAssertion($expected, $actual))
->expectHeader([
'View',
'Title',
'Machine name',
'Display plugin',
])
->ignoreRowOrder()
->setMissingRowsLabel(self::missingRowsLabelFor('views'))
->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('views'))
->assert();
} | [
"public",
"function",
"assertViewDisplaysExist",
"(",
"TableNode",
"$",
"expected",
")",
"{",
"$",
"displays_info",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getViews",
"(",
")",
"as",
"$",
"view",
")",
"{",
"/** @var array $display */",
"foreach",
"(",
"$",
"view",
"->",
"get",
"(",
"'display'",
")",
"as",
"$",
"display",
")",
"{",
"$",
"definition",
"=",
"$",
"this",
"->",
"viewsDisplayManager",
"->",
"getDefinition",
"(",
"$",
"display",
"[",
"'display_plugin'",
"]",
")",
";",
"$",
"displays_info",
"[",
"]",
"=",
"[",
"$",
"view",
"->",
"label",
"(",
")",
",",
"$",
"display",
"[",
"'display_title'",
"]",
",",
"$",
"display",
"[",
"'id'",
"]",
",",
"(",
"string",
")",
"$",
"definition",
"[",
"'title'",
"]",
",",
"]",
";",
"}",
"}",
"$",
"actual",
"=",
"new",
"TableNode",
"(",
"$",
"displays_info",
")",
";",
"(",
"new",
"TableEqualityAssertion",
"(",
"$",
"expected",
",",
"$",
"actual",
")",
")",
"->",
"expectHeader",
"(",
"[",
"'View'",
",",
"'Title'",
",",
"'Machine name'",
",",
"'Display plugin'",
",",
"]",
")",
"->",
"ignoreRowOrder",
"(",
")",
"->",
"setMissingRowsLabel",
"(",
"self",
"::",
"missingRowsLabelFor",
"(",
"'views'",
")",
")",
"->",
"setUnexpectedRowsLabel",
"(",
"self",
"::",
"unexpectedRowsLabelFor",
"(",
"'views'",
")",
")",
"->",
"assert",
"(",
")",
";",
"}"
] | Asserts the configuration of views displays.
@Then exactly the following views displays should exist
@throws \Exception | [
"Asserts",
"the",
"configuration",
"of",
"views",
"displays",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/ViewsContext.php#L85-L113 |
acquia/drupal-spec-tool | src/Context/ViewsContext.php | ViewsContext.getBaseTables | private function getBaseTables() {
$base_tables = [];
/** @var array[] $wizard_plugins */
$wizard_plugins = $this->viewsWizardManager->getDefinitions();
foreach ($wizard_plugins as $wizard) {
if (!array_key_exists('base_table', $wizard)) {
continue;
}
$base_tables[$wizard['base_table']] = (string) $wizard['title'];
}
return $base_tables;
} | php | private function getBaseTables() {
$base_tables = [];
/** @var array[] $wizard_plugins */
$wizard_plugins = $this->viewsWizardManager->getDefinitions();
foreach ($wizard_plugins as $wizard) {
if (!array_key_exists('base_table', $wizard)) {
continue;
}
$base_tables[$wizard['base_table']] = (string) $wizard['title'];
}
return $base_tables;
} | [
"private",
"function",
"getBaseTables",
"(",
")",
"{",
"$",
"base_tables",
"=",
"[",
"]",
";",
"/** @var array[] $wizard_plugins */",
"$",
"wizard_plugins",
"=",
"$",
"this",
"->",
"viewsWizardManager",
"->",
"getDefinitions",
"(",
")",
";",
"foreach",
"(",
"$",
"wizard_plugins",
"as",
"$",
"wizard",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"'base_table'",
",",
"$",
"wizard",
")",
")",
"{",
"continue",
";",
"}",
"$",
"base_tables",
"[",
"$",
"wizard",
"[",
"'base_table'",
"]",
"]",
"=",
"(",
"string",
")",
"$",
"wizard",
"[",
"'title'",
"]",
";",
"}",
"return",
"$",
"base_tables",
";",
"}"
] | Gets the list of Views base tables.
@return array|string[]
An array of base table human-readable labels keyed by the corresponding
IDs. | [
"Gets",
"the",
"list",
"of",
"Views",
"base",
"tables",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/ViewsContext.php#L122-L135 |
acquia/drupal-spec-tool | src/Context/ViewsContext.php | ViewsContext.getBaseTableLabel | private function getBaseTableLabel($id) {
return array_key_exists($id, $this->baseTables) ? $this->baseTables[$id] : $id;
} | php | private function getBaseTableLabel($id) {
return array_key_exists($id, $this->baseTables) ? $this->baseTables[$id] : $id;
} | [
"private",
"function",
"getBaseTableLabel",
"(",
"$",
"id",
")",
"{",
"return",
"array_key_exists",
"(",
"$",
"id",
",",
"$",
"this",
"->",
"baseTables",
")",
"?",
"$",
"this",
"->",
"baseTables",
"[",
"$",
"id",
"]",
":",
"$",
"id",
";",
"}"
] | Gets the human-readable label for a given base table ID.
@param string $id
A base table ID.
@return string
A human-readable label for the given base table ID if found, or the ID if
not. | [
"Gets",
"the",
"human",
"-",
"readable",
"label",
"for",
"a",
"given",
"base",
"table",
"ID",
"."
] | train | https://github.com/acquia/drupal-spec-tool/blob/4bbc93c2ec171c6b36f68d08be3eb302ca1869ee/src/Context/ViewsContext.php#L147-L149 |
contentful/ContentfulBundle | src/Command/Delivery/InfoCommand.php | InfoCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Contentful clients');
if (0 === \count($this->info)) {
$io->error('There are no Contentful clients currently configured.');
return 0;
}
$data = \array_map(function (array $item, string $name) {
return [
$name,
$item['service'],
$item['api'],
$item['space'],
$item['environment'],
$item['cache'] ?: 'Not enabled',
];
}, $this->info, \array_keys($this->info));
$io->table(
['Name', 'Service', 'API', 'Space', 'Environment', 'Cache'],
$data
);
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Contentful clients');
if (0 === \count($this->info)) {
$io->error('There are no Contentful clients currently configured.');
return 0;
}
$data = \array_map(function (array $item, string $name) {
return [
$name,
$item['service'],
$item['api'],
$item['space'],
$item['environment'],
$item['cache'] ?: 'Not enabled',
];
}, $this->info, \array_keys($this->info));
$io->table(
['Name', 'Service', 'API', 'Space', 'Environment', 'Cache'],
$data
);
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"io",
"=",
"new",
"SymfonyStyle",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"$",
"io",
"->",
"title",
"(",
"'Contentful clients'",
")",
";",
"if",
"(",
"0",
"===",
"\\",
"count",
"(",
"$",
"this",
"->",
"info",
")",
")",
"{",
"$",
"io",
"->",
"error",
"(",
"'There are no Contentful clients currently configured.'",
")",
";",
"return",
"0",
";",
"}",
"$",
"data",
"=",
"\\",
"array_map",
"(",
"function",
"(",
"array",
"$",
"item",
",",
"string",
"$",
"name",
")",
"{",
"return",
"[",
"$",
"name",
",",
"$",
"item",
"[",
"'service'",
"]",
",",
"$",
"item",
"[",
"'api'",
"]",
",",
"$",
"item",
"[",
"'space'",
"]",
",",
"$",
"item",
"[",
"'environment'",
"]",
",",
"$",
"item",
"[",
"'cache'",
"]",
"?",
":",
"'Not enabled'",
",",
"]",
";",
"}",
",",
"$",
"this",
"->",
"info",
",",
"\\",
"array_keys",
"(",
"$",
"this",
"->",
"info",
")",
")",
";",
"$",
"io",
"->",
"table",
"(",
"[",
"'Name'",
",",
"'Service'",
",",
"'API'",
",",
"'Space'",
",",
"'Environment'",
",",
"'Cache'",
"]",
",",
"$",
"data",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/Command/Delivery/InfoCommand.php#L39-L65 |
contentful/ContentfulBundle | src/Controller/Delivery/ProfilerController.php | ProfilerController.detailsAction | public function detailsAction(string $token, int $requestIndex): Response
{
$this->profiler->disable();
$profile = $this->profiler->loadProfile($token);
/** @var ClientDataCollector $collector */
$collector = $profile->getCollector('contentful');
$messages = $collector->getMessages();
$message = $messages[$requestIndex];
$body = $this->twig->render('@Contentful/Collector/details.html.twig', [
'requestIndex' => $requestIndex,
'message' => $message,
]);
return new Response($body);
} | php | public function detailsAction(string $token, int $requestIndex): Response
{
$this->profiler->disable();
$profile = $this->profiler->loadProfile($token);
/** @var ClientDataCollector $collector */
$collector = $profile->getCollector('contentful');
$messages = $collector->getMessages();
$message = $messages[$requestIndex];
$body = $this->twig->render('@Contentful/Collector/details.html.twig', [
'requestIndex' => $requestIndex,
'message' => $message,
]);
return new Response($body);
} | [
"public",
"function",
"detailsAction",
"(",
"string",
"$",
"token",
",",
"int",
"$",
"requestIndex",
")",
":",
"Response",
"{",
"$",
"this",
"->",
"profiler",
"->",
"disable",
"(",
")",
";",
"$",
"profile",
"=",
"$",
"this",
"->",
"profiler",
"->",
"loadProfile",
"(",
"$",
"token",
")",
";",
"/** @var ClientDataCollector $collector */",
"$",
"collector",
"=",
"$",
"profile",
"->",
"getCollector",
"(",
"'contentful'",
")",
";",
"$",
"messages",
"=",
"$",
"collector",
"->",
"getMessages",
"(",
")",
";",
"$",
"message",
"=",
"$",
"messages",
"[",
"$",
"requestIndex",
"]",
";",
"$",
"body",
"=",
"$",
"this",
"->",
"twig",
"->",
"render",
"(",
"'@Contentful/Collector/details.html.twig'",
",",
"[",
"'requestIndex'",
"=>",
"$",
"requestIndex",
",",
"'message'",
"=>",
"$",
"message",
",",
"]",
")",
";",
"return",
"new",
"Response",
"(",
"$",
"body",
")",
";",
"}"
] | @param string $token
@param int $requestIndex
@return Response | [
"@param",
"string",
"$token",
"@param",
"int",
"$requestIndex"
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/Controller/Delivery/ProfilerController.php#L49-L66 |
contentful/ContentfulBundle | src/DependencyInjection/ContentfulExtension.php | ContentfulExtension.load | public function load(array $configs, ContainerBuilder $container)
{
$configs = $this->processConfiguration(
new Configuration($container->getParameter('kernel.debug')),
$configs
);
$this->registerCache($container)
->registerCommand($container)
->registerDataCollector($container)
->registerDeliveryClient($container, $configs['delivery'] ?? [])
;
} | php | public function load(array $configs, ContainerBuilder $container)
{
$configs = $this->processConfiguration(
new Configuration($container->getParameter('kernel.debug')),
$configs
);
$this->registerCache($container)
->registerCommand($container)
->registerDataCollector($container)
->registerDeliveryClient($container, $configs['delivery'] ?? [])
;
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"configs",
"=",
"$",
"this",
"->",
"processConfiguration",
"(",
"new",
"Configuration",
"(",
"$",
"container",
"->",
"getParameter",
"(",
"'kernel.debug'",
")",
")",
",",
"$",
"configs",
")",
";",
"$",
"this",
"->",
"registerCache",
"(",
"$",
"container",
")",
"->",
"registerCommand",
"(",
"$",
"container",
")",
"->",
"registerDataCollector",
"(",
"$",
"container",
")",
"->",
"registerDeliveryClient",
"(",
"$",
"container",
",",
"$",
"configs",
"[",
"'delivery'",
"]",
"??",
"[",
"]",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/DependencyInjection/ContentfulExtension.php#L36-L48 |
contentful/ContentfulBundle | src/DependencyInjection/ContentfulExtension.php | ContentfulExtension.registerCache | private function registerCache(ContainerBuilder $container): self
{
$container->register('contentful.delivery.cache_clearer', CacheClearer::class)
->setAbstract(\true)
;
$container->register('contentful.delivery.cache_warmer', CacheWarmer::class)
->setAbstract(\true)
;
return $this;
} | php | private function registerCache(ContainerBuilder $container): self
{
$container->register('contentful.delivery.cache_clearer', CacheClearer::class)
->setAbstract(\true)
;
$container->register('contentful.delivery.cache_warmer', CacheWarmer::class)
->setAbstract(\true)
;
return $this;
} | [
"private",
"function",
"registerCache",
"(",
"ContainerBuilder",
"$",
"container",
")",
":",
"self",
"{",
"$",
"container",
"->",
"register",
"(",
"'contentful.delivery.cache_clearer'",
",",
"CacheClearer",
"::",
"class",
")",
"->",
"setAbstract",
"(",
"\\",
"true",
")",
";",
"$",
"container",
"->",
"register",
"(",
"'contentful.delivery.cache_warmer'",
",",
"CacheWarmer",
"::",
"class",
")",
"->",
"setAbstract",
"(",
"\\",
"true",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Registers two base cache handlers, one for warming up and one for clearing.
They are defined as abstract as a "concrete" implementation will be defined
for every configured client.
@param ContainerBuilder $container
@return ContentfulExtension | [
"Registers",
"two",
"base",
"cache",
"handlers",
"one",
"for",
"warming",
"up",
"and",
"one",
"for",
"clearing",
".",
"They",
"are",
"defined",
"as",
"abstract",
"as",
"a",
"concrete",
"implementation",
"will",
"be",
"defined",
"for",
"every",
"configured",
"client",
"."
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/DependencyInjection/ContentfulExtension.php#L59-L70 |
contentful/ContentfulBundle | src/DependencyInjection/ContentfulExtension.php | ContentfulExtension.registerCommand | private function registerCommand(ContainerBuilder $container): self
{
$container->register('contentful.delivery.command.info', InfoCommand::class)
->addArgument(new Parameter('contentful.delivery.clients.info'))
->addTag('console.command', [
'command' => 'contentful:delivery:info',
])
;
$container->register('contentful.delivery.command.debug', DebugCommand::class)
->addArgument(new TaggedIteratorArgument('contentful.delivery.client'))
->addArgument(new Parameter('contentful.delivery.clients.info'))
->addTag('console.command', [
'command' => 'contentful:delivery:debug',
])
;
return $this;
} | php | private function registerCommand(ContainerBuilder $container): self
{
$container->register('contentful.delivery.command.info', InfoCommand::class)
->addArgument(new Parameter('contentful.delivery.clients.info'))
->addTag('console.command', [
'command' => 'contentful:delivery:info',
])
;
$container->register('contentful.delivery.command.debug', DebugCommand::class)
->addArgument(new TaggedIteratorArgument('contentful.delivery.client'))
->addArgument(new Parameter('contentful.delivery.clients.info'))
->addTag('console.command', [
'command' => 'contentful:delivery:debug',
])
;
return $this;
} | [
"private",
"function",
"registerCommand",
"(",
"ContainerBuilder",
"$",
"container",
")",
":",
"self",
"{",
"$",
"container",
"->",
"register",
"(",
"'contentful.delivery.command.info'",
",",
"InfoCommand",
"::",
"class",
")",
"->",
"addArgument",
"(",
"new",
"Parameter",
"(",
"'contentful.delivery.clients.info'",
")",
")",
"->",
"addTag",
"(",
"'console.command'",
",",
"[",
"'command'",
"=>",
"'contentful:delivery:info'",
",",
"]",
")",
";",
"$",
"container",
"->",
"register",
"(",
"'contentful.delivery.command.debug'",
",",
"DebugCommand",
"::",
"class",
")",
"->",
"addArgument",
"(",
"new",
"TaggedIteratorArgument",
"(",
"'contentful.delivery.client'",
")",
")",
"->",
"addArgument",
"(",
"new",
"Parameter",
"(",
"'contentful.delivery.clients.info'",
")",
")",
"->",
"addTag",
"(",
"'console.command'",
",",
"[",
"'command'",
"=>",
"'contentful:delivery:debug'",
",",
"]",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Registers the CLI command which is in charge of extracting the configuration info,
and displaying it for debugging purposes.
@param ContainerBuilder $container
@return ContentfulExtension | [
"Registers",
"the",
"CLI",
"command",
"which",
"is",
"in",
"charge",
"of",
"extracting",
"the",
"configuration",
"info",
"and",
"displaying",
"it",
"for",
"debugging",
"purposes",
"."
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/DependencyInjection/ContentfulExtension.php#L80-L98 |
contentful/ContentfulBundle | src/DependencyInjection/ContentfulExtension.php | ContentfulExtension.registerDataCollector | private function registerDataCollector(ContainerBuilder $container): self
{
$container->register('contentful.delivery.data_collector', ClientDataCollector::class)
->addArgument(new TaggedIteratorArgument('contentful.delivery.client'))
->addArgument(new Parameter('contentful.delivery.clients.info'))
->addTag('data_collector', [
'id' => 'contentful.delivery',
'template' => '@Contentful/Collector/contentful.html.twig',
'priority' => '250',
])
;
return $this;
} | php | private function registerDataCollector(ContainerBuilder $container): self
{
$container->register('contentful.delivery.data_collector', ClientDataCollector::class)
->addArgument(new TaggedIteratorArgument('contentful.delivery.client'))
->addArgument(new Parameter('contentful.delivery.clients.info'))
->addTag('data_collector', [
'id' => 'contentful.delivery',
'template' => '@Contentful/Collector/contentful.html.twig',
'priority' => '250',
])
;
return $this;
} | [
"private",
"function",
"registerDataCollector",
"(",
"ContainerBuilder",
"$",
"container",
")",
":",
"self",
"{",
"$",
"container",
"->",
"register",
"(",
"'contentful.delivery.data_collector'",
",",
"ClientDataCollector",
"::",
"class",
")",
"->",
"addArgument",
"(",
"new",
"TaggedIteratorArgument",
"(",
"'contentful.delivery.client'",
")",
")",
"->",
"addArgument",
"(",
"new",
"Parameter",
"(",
"'contentful.delivery.clients.info'",
")",
")",
"->",
"addTag",
"(",
"'data_collector'",
",",
"[",
"'id'",
"=>",
"'contentful.delivery'",
",",
"'template'",
"=>",
"'@Contentful/Collector/contentful.html.twig'",
",",
"'priority'",
"=>",
"'250'",
",",
"]",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Registers the data collector, which will display info about the configured clients
and the queries being made to the API.
@param ContainerBuilder $container
@return ContentfulExtension | [
"Registers",
"the",
"data",
"collector",
"which",
"will",
"display",
"info",
"about",
"the",
"configured",
"clients",
"and",
"the",
"queries",
"being",
"made",
"to",
"the",
"API",
"."
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/DependencyInjection/ContentfulExtension.php#L108-L121 |
contentful/ContentfulBundle | src/DependencyInjection/ContentfulExtension.php | ContentfulExtension.configureDeliveryOptions | private function configureDeliveryOptions(array $options): array
{
$logger = $options['options']['logger'];
if (\null !== $logger) {
$options['options']['logger'] = \true === $logger
? new Reference(LoggerInterface::class)
: new Reference($options['options']['logger']);
}
if (\null !== $options['options']['client']) {
$options['options']['client'] = new Reference($options['options']['client']);
}
$pool = $options['options']['cache']['pool'];
if (\null !== $pool) {
$options['options']['cache']['pool'] = \true === $pool
? new Reference(CacheItemPoolInterface::class)
: new Reference($pool);
}
return $options;
} | php | private function configureDeliveryOptions(array $options): array
{
$logger = $options['options']['logger'];
if (\null !== $logger) {
$options['options']['logger'] = \true === $logger
? new Reference(LoggerInterface::class)
: new Reference($options['options']['logger']);
}
if (\null !== $options['options']['client']) {
$options['options']['client'] = new Reference($options['options']['client']);
}
$pool = $options['options']['cache']['pool'];
if (\null !== $pool) {
$options['options']['cache']['pool'] = \true === $pool
? new Reference(CacheItemPoolInterface::class)
: new Reference($pool);
}
return $options;
} | [
"private",
"function",
"configureDeliveryOptions",
"(",
"array",
"$",
"options",
")",
":",
"array",
"{",
"$",
"logger",
"=",
"$",
"options",
"[",
"'options'",
"]",
"[",
"'logger'",
"]",
";",
"if",
"(",
"\\",
"null",
"!==",
"$",
"logger",
")",
"{",
"$",
"options",
"[",
"'options'",
"]",
"[",
"'logger'",
"]",
"=",
"\\",
"true",
"===",
"$",
"logger",
"?",
"new",
"Reference",
"(",
"LoggerInterface",
"::",
"class",
")",
":",
"new",
"Reference",
"(",
"$",
"options",
"[",
"'options'",
"]",
"[",
"'logger'",
"]",
")",
";",
"}",
"if",
"(",
"\\",
"null",
"!==",
"$",
"options",
"[",
"'options'",
"]",
"[",
"'client'",
"]",
")",
"{",
"$",
"options",
"[",
"'options'",
"]",
"[",
"'client'",
"]",
"=",
"new",
"Reference",
"(",
"$",
"options",
"[",
"'options'",
"]",
"[",
"'client'",
"]",
")",
";",
"}",
"$",
"pool",
"=",
"$",
"options",
"[",
"'options'",
"]",
"[",
"'cache'",
"]",
"[",
"'pool'",
"]",
";",
"if",
"(",
"\\",
"null",
"!==",
"$",
"pool",
")",
"{",
"$",
"options",
"[",
"'options'",
"]",
"[",
"'cache'",
"]",
"[",
"'pool'",
"]",
"=",
"\\",
"true",
"===",
"$",
"pool",
"?",
"new",
"Reference",
"(",
"CacheItemPoolInterface",
"::",
"class",
")",
":",
"new",
"Reference",
"(",
"$",
"pool",
")",
";",
"}",
"return",
"$",
"options",
";",
"}"
] | Converts the references in the configuration into actual Reference objects.
@param array $options
@return array | [
"Converts",
"the",
"references",
"in",
"the",
"configuration",
"into",
"actual",
"Reference",
"objects",
"."
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/DependencyInjection/ContentfulExtension.php#L188-L209 |
contentful/ContentfulBundle | src/DataCollector/Delivery/ClientDataCollector.php | ClientDataCollector.collect | public function collect(Request $request, Response $response, \Exception $exception = \null)
{
$messages = [];
foreach ($this->clients as $client) {
$messages = \array_merge($messages, $client->getMessages());
}
$this->data['messages'] = $messages;
} | php | public function collect(Request $request, Response $response, \Exception $exception = \null)
{
$messages = [];
foreach ($this->clients as $client) {
$messages = \array_merge($messages, $client->getMessages());
}
$this->data['messages'] = $messages;
} | [
"public",
"function",
"collect",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"\\",
"Exception",
"$",
"exception",
"=",
"\\",
"null",
")",
"{",
"$",
"messages",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"clients",
"as",
"$",
"client",
")",
"{",
"$",
"messages",
"=",
"\\",
"array_merge",
"(",
"$",
"messages",
",",
"$",
"client",
"->",
"getMessages",
"(",
")",
")",
";",
"}",
"$",
"this",
"->",
"data",
"[",
"'messages'",
"]",
"=",
"$",
"messages",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/DataCollector/Delivery/ClientDataCollector.php#L52-L60 |
contentful/ContentfulBundle | src/Command/Delivery/DebugCommand.php | DebugCommand.execute | public function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$name = $input->getArgument('client-name');
if (!$name && 1 === \count($this->clients)) {
$name = \array_keys($this->clients)[0];
}
if (!isset($this->clients[$name])) {
throw new InvalidArgumentException(\sprintf(
'Could not find the requested client "%s", use "contentful:delivery:info" to check the configured clients.',
$name
));
}
$client = $this->clients[$name];
try {
$space = $client->getSpace();
$environment = $client->getEnvironment();
$query = (new Query())
->setLimit(1000)
;
/** @var ContentType[]|ResourceArray $contentTypes */
$contentTypes = $client->getContentTypes($query);
$entries = [];
foreach ($contentTypes as $contentType) {
$query = (new Query())
->setLimit(1)
->setContentType($contentType->getId())
;
$entries[$contentType->getId()] = $client->getEntries($query)->getTotal();
}
} catch (\Exception $exception) {
throw new RuntimeException(
'Requested service was found, but data could not be loaded. Try checking client credentials.',
0,
$exception
);
}
$io->title('Debug client');
$io->text('Full service ID: contentful.delivery.'.$name.'_client');
$io->section('Space');
$io->text($space->getName());
$io->comment('https://app.contentful.com/spaces/'.$space->getId().'/environments/'.$environment->getId());
$io->section(\sprintf(
'Locales (%d)',
\count($environment->getLocales())
));
$data = \array_map(function (Locale $locale) {
return [
$locale->getId(),
$locale->getName(),
$locale->getCode(),
$locale->getFallbackCode(),
];
}, $environment->getLocales());
$io->table(
['ID', 'Name', 'Code', 'Fallback Code'],
$data
);
$io->comment('https://app.contentful.com/spaces/'.$space->getId().'/environments/'.$environment->getId().'/locales');
$io->section(\sprintf(
'Content types (%d)',
\count($contentTypes)
));
$data = \array_map(function (ContentType $contentType) use ($entries) {
return [
$contentType->getId(),
$contentType->getName(),
\count($contentType->getFields()),
$entries[$contentType->getId()],
$contentType->getDescription(),
];
}, $contentTypes->getItems());
$io->table(
['ID', 'Name', 'Fields', 'Entries', 'Description'],
$data
);
$io->comment('https://app.contentful.com/spaces/'.$space->getId().'/environments/'.$environment->getId().'/content_types');
} | php | public function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$name = $input->getArgument('client-name');
if (!$name && 1 === \count($this->clients)) {
$name = \array_keys($this->clients)[0];
}
if (!isset($this->clients[$name])) {
throw new InvalidArgumentException(\sprintf(
'Could not find the requested client "%s", use "contentful:delivery:info" to check the configured clients.',
$name
));
}
$client = $this->clients[$name];
try {
$space = $client->getSpace();
$environment = $client->getEnvironment();
$query = (new Query())
->setLimit(1000)
;
/** @var ContentType[]|ResourceArray $contentTypes */
$contentTypes = $client->getContentTypes($query);
$entries = [];
foreach ($contentTypes as $contentType) {
$query = (new Query())
->setLimit(1)
->setContentType($contentType->getId())
;
$entries[$contentType->getId()] = $client->getEntries($query)->getTotal();
}
} catch (\Exception $exception) {
throw new RuntimeException(
'Requested service was found, but data could not be loaded. Try checking client credentials.',
0,
$exception
);
}
$io->title('Debug client');
$io->text('Full service ID: contentful.delivery.'.$name.'_client');
$io->section('Space');
$io->text($space->getName());
$io->comment('https://app.contentful.com/spaces/'.$space->getId().'/environments/'.$environment->getId());
$io->section(\sprintf(
'Locales (%d)',
\count($environment->getLocales())
));
$data = \array_map(function (Locale $locale) {
return [
$locale->getId(),
$locale->getName(),
$locale->getCode(),
$locale->getFallbackCode(),
];
}, $environment->getLocales());
$io->table(
['ID', 'Name', 'Code', 'Fallback Code'],
$data
);
$io->comment('https://app.contentful.com/spaces/'.$space->getId().'/environments/'.$environment->getId().'/locales');
$io->section(\sprintf(
'Content types (%d)',
\count($contentTypes)
));
$data = \array_map(function (ContentType $contentType) use ($entries) {
return [
$contentType->getId(),
$contentType->getName(),
\count($contentType->getFields()),
$entries[$contentType->getId()],
$contentType->getDescription(),
];
}, $contentTypes->getItems());
$io->table(
['ID', 'Name', 'Fields', 'Entries', 'Description'],
$data
);
$io->comment('https://app.contentful.com/spaces/'.$space->getId().'/environments/'.$environment->getId().'/content_types');
} | [
"public",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"io",
"=",
"new",
"SymfonyStyle",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"$",
"name",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'client-name'",
")",
";",
"if",
"(",
"!",
"$",
"name",
"&&",
"1",
"===",
"\\",
"count",
"(",
"$",
"this",
"->",
"clients",
")",
")",
"{",
"$",
"name",
"=",
"\\",
"array_keys",
"(",
"$",
"this",
"->",
"clients",
")",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"clients",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\\",
"sprintf",
"(",
"'Could not find the requested client \"%s\", use \"contentful:delivery:info\" to check the configured clients.'",
",",
"$",
"name",
")",
")",
";",
"}",
"$",
"client",
"=",
"$",
"this",
"->",
"clients",
"[",
"$",
"name",
"]",
";",
"try",
"{",
"$",
"space",
"=",
"$",
"client",
"->",
"getSpace",
"(",
")",
";",
"$",
"environment",
"=",
"$",
"client",
"->",
"getEnvironment",
"(",
")",
";",
"$",
"query",
"=",
"(",
"new",
"Query",
"(",
")",
")",
"->",
"setLimit",
"(",
"1000",
")",
";",
"/** @var ContentType[]|ResourceArray $contentTypes */",
"$",
"contentTypes",
"=",
"$",
"client",
"->",
"getContentTypes",
"(",
"$",
"query",
")",
";",
"$",
"entries",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"contentTypes",
"as",
"$",
"contentType",
")",
"{",
"$",
"query",
"=",
"(",
"new",
"Query",
"(",
")",
")",
"->",
"setLimit",
"(",
"1",
")",
"->",
"setContentType",
"(",
"$",
"contentType",
"->",
"getId",
"(",
")",
")",
";",
"$",
"entries",
"[",
"$",
"contentType",
"->",
"getId",
"(",
")",
"]",
"=",
"$",
"client",
"->",
"getEntries",
"(",
"$",
"query",
")",
"->",
"getTotal",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"exception",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Requested service was found, but data could not be loaded. Try checking client credentials.'",
",",
"0",
",",
"$",
"exception",
")",
";",
"}",
"$",
"io",
"->",
"title",
"(",
"'Debug client'",
")",
";",
"$",
"io",
"->",
"text",
"(",
"'Full service ID: contentful.delivery.'",
".",
"$",
"name",
".",
"'_client'",
")",
";",
"$",
"io",
"->",
"section",
"(",
"'Space'",
")",
";",
"$",
"io",
"->",
"text",
"(",
"$",
"space",
"->",
"getName",
"(",
")",
")",
";",
"$",
"io",
"->",
"comment",
"(",
"'https://app.contentful.com/spaces/'",
".",
"$",
"space",
"->",
"getId",
"(",
")",
".",
"'/environments/'",
".",
"$",
"environment",
"->",
"getId",
"(",
")",
")",
";",
"$",
"io",
"->",
"section",
"(",
"\\",
"sprintf",
"(",
"'Locales (%d)'",
",",
"\\",
"count",
"(",
"$",
"environment",
"->",
"getLocales",
"(",
")",
")",
")",
")",
";",
"$",
"data",
"=",
"\\",
"array_map",
"(",
"function",
"(",
"Locale",
"$",
"locale",
")",
"{",
"return",
"[",
"$",
"locale",
"->",
"getId",
"(",
")",
",",
"$",
"locale",
"->",
"getName",
"(",
")",
",",
"$",
"locale",
"->",
"getCode",
"(",
")",
",",
"$",
"locale",
"->",
"getFallbackCode",
"(",
")",
",",
"]",
";",
"}",
",",
"$",
"environment",
"->",
"getLocales",
"(",
")",
")",
";",
"$",
"io",
"->",
"table",
"(",
"[",
"'ID'",
",",
"'Name'",
",",
"'Code'",
",",
"'Fallback Code'",
"]",
",",
"$",
"data",
")",
";",
"$",
"io",
"->",
"comment",
"(",
"'https://app.contentful.com/spaces/'",
".",
"$",
"space",
"->",
"getId",
"(",
")",
".",
"'/environments/'",
".",
"$",
"environment",
"->",
"getId",
"(",
")",
".",
"'/locales'",
")",
";",
"$",
"io",
"->",
"section",
"(",
"\\",
"sprintf",
"(",
"'Content types (%d)'",
",",
"\\",
"count",
"(",
"$",
"contentTypes",
")",
")",
")",
";",
"$",
"data",
"=",
"\\",
"array_map",
"(",
"function",
"(",
"ContentType",
"$",
"contentType",
")",
"use",
"(",
"$",
"entries",
")",
"{",
"return",
"[",
"$",
"contentType",
"->",
"getId",
"(",
")",
",",
"$",
"contentType",
"->",
"getName",
"(",
")",
",",
"\\",
"count",
"(",
"$",
"contentType",
"->",
"getFields",
"(",
")",
")",
",",
"$",
"entries",
"[",
"$",
"contentType",
"->",
"getId",
"(",
")",
"]",
",",
"$",
"contentType",
"->",
"getDescription",
"(",
")",
",",
"]",
";",
"}",
",",
"$",
"contentTypes",
"->",
"getItems",
"(",
")",
")",
";",
"$",
"io",
"->",
"table",
"(",
"[",
"'ID'",
",",
"'Name'",
",",
"'Fields'",
",",
"'Entries'",
",",
"'Description'",
"]",
",",
"$",
"data",
")",
";",
"$",
"io",
"->",
"comment",
"(",
"'https://app.contentful.com/spaces/'",
".",
"$",
"space",
"->",
"getId",
"(",
")",
".",
"'/environments/'",
".",
"$",
"environment",
"->",
"getId",
"(",
")",
".",
"'/content_types'",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/Command/Delivery/DebugCommand.php#L63-L148 |
contentful/ContentfulBundle | src/DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root('contentful', 'array', $this->builder);
$root
->addDefaultsIfNotSet()
->children()
->arrayNode('delivery')
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->append($this->createDefaultNode())
->append($this->createTokenNode())
->append($this->createSpaceNode())
->append($this->createEnvironmentNode())
->append($this->createApiNode())
->append($this->createOptionsNode())
;
return $treeBuilder;
} | php | public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root('contentful', 'array', $this->builder);
$root
->addDefaultsIfNotSet()
->children()
->arrayNode('delivery')
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->append($this->createDefaultNode())
->append($this->createTokenNode())
->append($this->createSpaceNode())
->append($this->createEnvironmentNode())
->append($this->createApiNode())
->append($this->createOptionsNode())
;
return $treeBuilder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
":",
"TreeBuilder",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
")",
";",
"$",
"root",
"=",
"$",
"treeBuilder",
"->",
"root",
"(",
"'contentful'",
",",
"'array'",
",",
"$",
"this",
"->",
"builder",
")",
";",
"$",
"root",
"->",
"addDefaultsIfNotSet",
"(",
")",
"->",
"children",
"(",
")",
"->",
"arrayNode",
"(",
"'delivery'",
")",
"->",
"requiresAtLeastOneElement",
"(",
")",
"->",
"useAttributeAsKey",
"(",
"'name'",
")",
"->",
"arrayPrototype",
"(",
")",
"->",
"children",
"(",
")",
"->",
"append",
"(",
"$",
"this",
"->",
"createDefaultNode",
"(",
")",
")",
"->",
"append",
"(",
"$",
"this",
"->",
"createTokenNode",
"(",
")",
")",
"->",
"append",
"(",
"$",
"this",
"->",
"createSpaceNode",
"(",
")",
")",
"->",
"append",
"(",
"$",
"this",
"->",
"createEnvironmentNode",
"(",
")",
")",
"->",
"append",
"(",
"$",
"this",
"->",
"createApiNode",
"(",
")",
")",
"->",
"append",
"(",
"$",
"this",
"->",
"createOptionsNode",
"(",
")",
")",
";",
"return",
"$",
"treeBuilder",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/DependencyInjection/Configuration.php#L42-L64 |
contentful/ContentfulBundle | src/DependencyInjection/Compiler/ProfilerControllerPass.php | ProfilerControllerPass.process | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('profiler') || !$container->hasDefinition('twig')) {
return;
}
$container->register('contentful.delivery.profiler_controller', ProfilerController::class)
->setArguments([
new Reference('profiler'),
new Reference('twig'),
])
->setPublic(\true)
->addTag('controller.service_arguments')
;
} | php | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('profiler') || !$container->hasDefinition('twig')) {
return;
}
$container->register('contentful.delivery.profiler_controller', ProfilerController::class)
->setArguments([
new Reference('profiler'),
new Reference('twig'),
])
->setPublic(\true)
->addTag('controller.service_arguments')
;
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"if",
"(",
"!",
"$",
"container",
"->",
"hasDefinition",
"(",
"'profiler'",
")",
"||",
"!",
"$",
"container",
"->",
"hasDefinition",
"(",
"'twig'",
")",
")",
"{",
"return",
";",
"}",
"$",
"container",
"->",
"register",
"(",
"'contentful.delivery.profiler_controller'",
",",
"ProfilerController",
"::",
"class",
")",
"->",
"setArguments",
"(",
"[",
"new",
"Reference",
"(",
"'profiler'",
")",
",",
"new",
"Reference",
"(",
"'twig'",
")",
",",
"]",
")",
"->",
"setPublic",
"(",
"\\",
"true",
")",
"->",
"addTag",
"(",
"'controller.service_arguments'",
")",
";",
"}"
] | Loads the definition for the ProfilerController when the profiler and twig are present.
@param ContainerBuilder $container | [
"Loads",
"the",
"definition",
"for",
"the",
"ProfilerController",
"when",
"the",
"profiler",
"and",
"twig",
"are",
"present",
"."
] | train | https://github.com/contentful/ContentfulBundle/blob/f77d946eb1f784250ea5f302349be6e3e1dd4165/src/DependencyInjection/Compiler/ProfilerControllerPass.php#L26-L40 |
ezsystems/ezplatform-http-cache | src/EventSubscriber/UserContextSubscriber.php | UserContextSubscriber.tagUserContext | public function tagUserContext(FilterResponseEvent $event)
{
$response = $event->getResponse();
if (!$response->isCacheable()) {
return;
}
if ($response->headers->get('Content-Type') !== 'application/vnd.fos.user-context-hash') {
return;
}
if (!$response->getTtl()) {
return;
}
// We need to set tag directly on repsonse here to make sure this does not also get applied to the main request
// when using Symfony Proxy, as tag handler does not clear tags between requests.
$response->headers->set($this->tagHeader, $this->repoPrefix . 'ez-user-context-hash');
} | php | public function tagUserContext(FilterResponseEvent $event)
{
$response = $event->getResponse();
if (!$response->isCacheable()) {
return;
}
if ($response->headers->get('Content-Type') !== 'application/vnd.fos.user-context-hash') {
return;
}
if (!$response->getTtl()) {
return;
}
// We need to set tag directly on repsonse here to make sure this does not also get applied to the main request
// when using Symfony Proxy, as tag handler does not clear tags between requests.
$response->headers->set($this->tagHeader, $this->repoPrefix . 'ez-user-context-hash');
} | [
"public",
"function",
"tagUserContext",
"(",
"FilterResponseEvent",
"$",
"event",
")",
"{",
"$",
"response",
"=",
"$",
"event",
"->",
"getResponse",
"(",
")",
";",
"if",
"(",
"!",
"$",
"response",
"->",
"isCacheable",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"response",
"->",
"headers",
"->",
"get",
"(",
"'Content-Type'",
")",
"!==",
"'application/vnd.fos.user-context-hash'",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"$",
"response",
"->",
"getTtl",
"(",
")",
")",
"{",
"return",
";",
"}",
"// We need to set tag directly on repsonse here to make sure this does not also get applied to the main request",
"// when using Symfony Proxy, as tag handler does not clear tags between requests.",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"$",
"this",
"->",
"tagHeader",
",",
"$",
"this",
"->",
"repoPrefix",
".",
"'ez-user-context-hash'",
")",
";",
"}"
] | Tag vnd.fos.user-context-hash responses if they are set to cached.
@param FilterResponseEvent $event | [
"Tag",
"vnd",
".",
"fos",
".",
"user",
"-",
"context",
"-",
"hash",
"responses",
"if",
"they",
"are",
"set",
"to",
"cached",
"."
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/EventSubscriber/UserContextSubscriber.php#L43-L61 |
ezsystems/ezplatform-http-cache | src/EventSubscriber/RestKernelViewSubscriber.php | RestKernelViewSubscriber.getTags | protected function getTags($value)
{
$tags = [];
switch ($value) {
case $value instanceof VersionList && !empty($value->versions):
$tags[] = 'content-' . $value->versions[0]->contentInfo->id;
$tags[] = 'content-versions-' . $value->versions[0]->contentInfo->id;
break;
case $value instanceof Section:
$tags[] = 'section-' . $value->id;
break;
case $value instanceof ContentTypeGroupRefList:
if ($value->contentType->status !== ContentType::STATUS_DEFINED) {
return [];
}
$tags[] = 'type-' . $value->contentType->id;
case $value instanceof ContentTypeGroupList:
foreach ($value->contentTypeGroups as $contentTypeGroup) {
$tags[] = 'type-group-' . $contentTypeGroup->id;
}
break;
case $value instanceof RestContentType:
$value = $value->contentType;
case $value instanceof ContentType:
if ($value->status !== ContentType::STATUS_DEFINED) {
return [];
}
$tags[] = 'type-' . $value->id;
break;
case $value instanceof Root:
$tags[] = 'ez-all';
break;
// @deprecated The following logic is 1.x specific, and should be removed before a 1.0 version
case $value instanceof PermissionReport:
// We requrie v0.1.5 with added location property to be able to add tags
if (!isset($value->parentLocation)) {
return [];
}
// In case of for instance location swap where content type might change affecting allowed content types
$tags[] = 'content-' . $value->parentLocation->contentId;
$tags[] = 'content-type-' . $value->parentLocation->contentInfo->contentTypeId;
$tags[] = 'location-' . $value->parentLocation->id;
// In case of permissions assigned by subtree, so if path changes affecting this (move subtree operation)
foreach ($value->parentLocation->path as $pathItem) {
$tags[] = 'path-' . $pathItem;
}
break;
}
return $tags;
} | php | protected function getTags($value)
{
$tags = [];
switch ($value) {
case $value instanceof VersionList && !empty($value->versions):
$tags[] = 'content-' . $value->versions[0]->contentInfo->id;
$tags[] = 'content-versions-' . $value->versions[0]->contentInfo->id;
break;
case $value instanceof Section:
$tags[] = 'section-' . $value->id;
break;
case $value instanceof ContentTypeGroupRefList:
if ($value->contentType->status !== ContentType::STATUS_DEFINED) {
return [];
}
$tags[] = 'type-' . $value->contentType->id;
case $value instanceof ContentTypeGroupList:
foreach ($value->contentTypeGroups as $contentTypeGroup) {
$tags[] = 'type-group-' . $contentTypeGroup->id;
}
break;
case $value instanceof RestContentType:
$value = $value->contentType;
case $value instanceof ContentType:
if ($value->status !== ContentType::STATUS_DEFINED) {
return [];
}
$tags[] = 'type-' . $value->id;
break;
case $value instanceof Root:
$tags[] = 'ez-all';
break;
// @deprecated The following logic is 1.x specific, and should be removed before a 1.0 version
case $value instanceof PermissionReport:
// We requrie v0.1.5 with added location property to be able to add tags
if (!isset($value->parentLocation)) {
return [];
}
// In case of for instance location swap where content type might change affecting allowed content types
$tags[] = 'content-' . $value->parentLocation->contentId;
$tags[] = 'content-type-' . $value->parentLocation->contentInfo->contentTypeId;
$tags[] = 'location-' . $value->parentLocation->id;
// In case of permissions assigned by subtree, so if path changes affecting this (move subtree operation)
foreach ($value->parentLocation->path as $pathItem) {
$tags[] = 'path-' . $pathItem;
}
break;
}
return $tags;
} | [
"protected",
"function",
"getTags",
"(",
"$",
"value",
")",
"{",
"$",
"tags",
"=",
"[",
"]",
";",
"switch",
"(",
"$",
"value",
")",
"{",
"case",
"$",
"value",
"instanceof",
"VersionList",
"&&",
"!",
"empty",
"(",
"$",
"value",
"->",
"versions",
")",
":",
"$",
"tags",
"[",
"]",
"=",
"'content-'",
".",
"$",
"value",
"->",
"versions",
"[",
"0",
"]",
"->",
"contentInfo",
"->",
"id",
";",
"$",
"tags",
"[",
"]",
"=",
"'content-versions-'",
".",
"$",
"value",
"->",
"versions",
"[",
"0",
"]",
"->",
"contentInfo",
"->",
"id",
";",
"break",
";",
"case",
"$",
"value",
"instanceof",
"Section",
":",
"$",
"tags",
"[",
"]",
"=",
"'section-'",
".",
"$",
"value",
"->",
"id",
";",
"break",
";",
"case",
"$",
"value",
"instanceof",
"ContentTypeGroupRefList",
":",
"if",
"(",
"$",
"value",
"->",
"contentType",
"->",
"status",
"!==",
"ContentType",
"::",
"STATUS_DEFINED",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"tags",
"[",
"]",
"=",
"'type-'",
".",
"$",
"value",
"->",
"contentType",
"->",
"id",
";",
"case",
"$",
"value",
"instanceof",
"ContentTypeGroupList",
":",
"foreach",
"(",
"$",
"value",
"->",
"contentTypeGroups",
"as",
"$",
"contentTypeGroup",
")",
"{",
"$",
"tags",
"[",
"]",
"=",
"'type-group-'",
".",
"$",
"contentTypeGroup",
"->",
"id",
";",
"}",
"break",
";",
"case",
"$",
"value",
"instanceof",
"RestContentType",
":",
"$",
"value",
"=",
"$",
"value",
"->",
"contentType",
";",
"case",
"$",
"value",
"instanceof",
"ContentType",
":",
"if",
"(",
"$",
"value",
"->",
"status",
"!==",
"ContentType",
"::",
"STATUS_DEFINED",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"tags",
"[",
"]",
"=",
"'type-'",
".",
"$",
"value",
"->",
"id",
";",
"break",
";",
"case",
"$",
"value",
"instanceof",
"Root",
":",
"$",
"tags",
"[",
"]",
"=",
"'ez-all'",
";",
"break",
";",
"// @deprecated The following logic is 1.x specific, and should be removed before a 1.0 version",
"case",
"$",
"value",
"instanceof",
"PermissionReport",
":",
"// We requrie v0.1.5 with added location property to be able to add tags",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
"->",
"parentLocation",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"// In case of for instance location swap where content type might change affecting allowed content types",
"$",
"tags",
"[",
"]",
"=",
"'content-'",
".",
"$",
"value",
"->",
"parentLocation",
"->",
"contentId",
";",
"$",
"tags",
"[",
"]",
"=",
"'content-type-'",
".",
"$",
"value",
"->",
"parentLocation",
"->",
"contentInfo",
"->",
"contentTypeId",
";",
"$",
"tags",
"[",
"]",
"=",
"'location-'",
".",
"$",
"value",
"->",
"parentLocation",
"->",
"id",
";",
"// In case of permissions assigned by subtree, so if path changes affecting this (move subtree operation)",
"foreach",
"(",
"$",
"value",
"->",
"parentLocation",
"->",
"path",
"as",
"$",
"pathItem",
")",
"{",
"$",
"tags",
"[",
"]",
"=",
"'path-'",
".",
"$",
"pathItem",
";",
"}",
"break",
";",
"}",
"return",
"$",
"tags",
";",
"}"
] | @param object $value
@return array | [
"@param",
"object",
"$value"
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/EventSubscriber/RestKernelViewSubscriber.php#L68-L126 |
ezsystems/ezplatform-http-cache | src/AppCache.php | AppCache.handle | public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
$response = parent::handle($request, $type, $catch);
if (!$this->getKernel()->isDebug()) {
$this->cleanupHeadersForProd($response);
}
return $response;
} | php | public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
$response = parent::handle($request, $type, $catch);
if (!$this->getKernel()->isDebug()) {
$this->cleanupHeadersForProd($response);
}
return $response;
} | [
"public",
"function",
"handle",
"(",
"Request",
"$",
"request",
",",
"$",
"type",
"=",
"HttpKernelInterface",
"::",
"MASTER_REQUEST",
",",
"$",
"catch",
"=",
"true",
")",
"{",
"$",
"response",
"=",
"parent",
"::",
"handle",
"(",
"$",
"request",
",",
"$",
"type",
",",
"$",
"catch",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"getKernel",
"(",
")",
"->",
"isDebug",
"(",
")",
")",
"{",
"$",
"this",
"->",
"cleanupHeadersForProd",
"(",
"$",
"response",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/AppCache.php#L34-L43 |
ezsystems/ezplatform-http-cache | src/AppCache.php | AppCache.invalidate | protected function invalidate(Request $request, $catch = false)
{
if ($request->getMethod() !== 'PURGE' && $request->getMethod() !== 'BAN') {
return parent::invalidate($request, $catch);
}
// Reject all non-authorized clients
if (!in_array($request->getClientIp(), $this->getInternalAllowedIPs())) {
return new Response('', 405);
}
$response = new Response();
$store = $this->getStore();
if ($store instanceof RequestAwarePurger) {
$result = $store->purgeByRequest($request);
} else {
$result = $store->purge($request->getUri());
}
if ($result === true) {
$response->setStatusCode(200, 'Purged');
} else {
$response->setStatusCode(404, 'Not purged');
}
return $response;
} | php | protected function invalidate(Request $request, $catch = false)
{
if ($request->getMethod() !== 'PURGE' && $request->getMethod() !== 'BAN') {
return parent::invalidate($request, $catch);
}
// Reject all non-authorized clients
if (!in_array($request->getClientIp(), $this->getInternalAllowedIPs())) {
return new Response('', 405);
}
$response = new Response();
$store = $this->getStore();
if ($store instanceof RequestAwarePurger) {
$result = $store->purgeByRequest($request);
} else {
$result = $store->purge($request->getUri());
}
if ($result === true) {
$response->setStatusCode(200, 'Purged');
} else {
$response->setStatusCode(404, 'Not purged');
}
return $response;
} | [
"protected",
"function",
"invalidate",
"(",
"Request",
"$",
"request",
",",
"$",
"catch",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"request",
"->",
"getMethod",
"(",
")",
"!==",
"'PURGE'",
"&&",
"$",
"request",
"->",
"getMethod",
"(",
")",
"!==",
"'BAN'",
")",
"{",
"return",
"parent",
"::",
"invalidate",
"(",
"$",
"request",
",",
"$",
"catch",
")",
";",
"}",
"// Reject all non-authorized clients",
"if",
"(",
"!",
"in_array",
"(",
"$",
"request",
"->",
"getClientIp",
"(",
")",
",",
"$",
"this",
"->",
"getInternalAllowedIPs",
"(",
")",
")",
")",
"{",
"return",
"new",
"Response",
"(",
"''",
",",
"405",
")",
";",
"}",
"$",
"response",
"=",
"new",
"Response",
"(",
")",
";",
"$",
"store",
"=",
"$",
"this",
"->",
"getStore",
"(",
")",
";",
"if",
"(",
"$",
"store",
"instanceof",
"RequestAwarePurger",
")",
"{",
"$",
"result",
"=",
"$",
"store",
"->",
"purgeByRequest",
"(",
"$",
"request",
")",
";",
"}",
"else",
"{",
"$",
"result",
"=",
"$",
"store",
"->",
"purge",
"(",
"$",
"request",
"->",
"getUri",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"result",
"===",
"true",
")",
"{",
"$",
"response",
"->",
"setStatusCode",
"(",
"200",
",",
"'Purged'",
")",
";",
"}",
"else",
"{",
"$",
"response",
"->",
"setStatusCode",
"(",
"404",
",",
"'Not purged'",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/AppCache.php#L57-L83 |
ezsystems/ezplatform-http-cache | src/AppCache.php | AppCache.cleanupHeadersForProd | protected function cleanupHeadersForProd(Response $response)
{
// remove headers that identify the content or internal digest info
$response->headers->remove('xkey');
$response->headers->remove('x-content-digest');
// remove vary by X-User-Hash header
$varyValues = [];
$variesByUser = false;
foreach ($response->getVary() as $value) {
if ($value === 'X-User-Hash') {
$variesByUser = true;
} else {
$varyValues[] = $value;
}
}
// update resulting vary header in normalized form (comma separated)
if (empty($varyValues)) {
$response->headers->remove('Vary');
} else {
$response->setVary(implode(', ', $varyValues));
}
// If cache varies by user hash, then make sure other proxies don't cache this
if ($variesByUser) {
$response->setPrivate();
$response->headers->removeCacheControlDirective('s-maxage');
$response->headers->addCacheControlDirective('no-cache');
}
} | php | protected function cleanupHeadersForProd(Response $response)
{
// remove headers that identify the content or internal digest info
$response->headers->remove('xkey');
$response->headers->remove('x-content-digest');
// remove vary by X-User-Hash header
$varyValues = [];
$variesByUser = false;
foreach ($response->getVary() as $value) {
if ($value === 'X-User-Hash') {
$variesByUser = true;
} else {
$varyValues[] = $value;
}
}
// update resulting vary header in normalized form (comma separated)
if (empty($varyValues)) {
$response->headers->remove('Vary');
} else {
$response->setVary(implode(', ', $varyValues));
}
// If cache varies by user hash, then make sure other proxies don't cache this
if ($variesByUser) {
$response->setPrivate();
$response->headers->removeCacheControlDirective('s-maxage');
$response->headers->addCacheControlDirective('no-cache');
}
} | [
"protected",
"function",
"cleanupHeadersForProd",
"(",
"Response",
"$",
"response",
")",
"{",
"// remove headers that identify the content or internal digest info",
"$",
"response",
"->",
"headers",
"->",
"remove",
"(",
"'xkey'",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"remove",
"(",
"'x-content-digest'",
")",
";",
"// remove vary by X-User-Hash header",
"$",
"varyValues",
"=",
"[",
"]",
";",
"$",
"variesByUser",
"=",
"false",
";",
"foreach",
"(",
"$",
"response",
"->",
"getVary",
"(",
")",
"as",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"'X-User-Hash'",
")",
"{",
"$",
"variesByUser",
"=",
"true",
";",
"}",
"else",
"{",
"$",
"varyValues",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"// update resulting vary header in normalized form (comma separated)",
"if",
"(",
"empty",
"(",
"$",
"varyValues",
")",
")",
"{",
"$",
"response",
"->",
"headers",
"->",
"remove",
"(",
"'Vary'",
")",
";",
"}",
"else",
"{",
"$",
"response",
"->",
"setVary",
"(",
"implode",
"(",
"', '",
",",
"$",
"varyValues",
")",
")",
";",
"}",
"// If cache varies by user hash, then make sure other proxies don't cache this",
"if",
"(",
"$",
"variesByUser",
")",
"{",
"$",
"response",
"->",
"setPrivate",
"(",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"removeCacheControlDirective",
"(",
"'s-maxage'",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"addCacheControlDirective",
"(",
"'no-cache'",
")",
";",
"}",
"}"
] | Perform cleanup of reponse.
@param Response $response | [
"Perform",
"cleanup",
"of",
"reponse",
"."
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/AppCache.php#L100-L130 |
ezsystems/ezplatform-http-cache | src/Twig/ContentTaggingExtension.php | ContentTaggingExtension.tagHttpCacheForLocation | public function tagHttpCacheForLocation(Location $location)
{
$this->responseTagger->tag($location);
$this->responseTagger->tag($location->getContentInfo());
} | php | public function tagHttpCacheForLocation(Location $location)
{
$this->responseTagger->tag($location);
$this->responseTagger->tag($location->getContentInfo());
} | [
"public",
"function",
"tagHttpCacheForLocation",
"(",
"Location",
"$",
"location",
")",
"{",
"$",
"this",
"->",
"responseTagger",
"->",
"tag",
"(",
"$",
"location",
")",
";",
"$",
"this",
"->",
"responseTagger",
"->",
"tag",
"(",
"$",
"location",
"->",
"getContentInfo",
"(",
")",
")",
";",
"}"
] | Adds tags to current response.
@internal Function is only for use within this class (and implicit by Twig).
@param Location $location | [
"Adds",
"tags",
"to",
"current",
"response",
"."
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/Twig/ContentTaggingExtension.php#L50-L54 |
ezsystems/ezplatform-http-cache | src/Proxy/TagAwareStore.php | TagAwareStore.write | public function write(Request $request, Response $response)
{
$key = parent::write($request, $response);
// Get tags in order to save them
$digest = $response->headers->get('X-Content-Digest');
$tags = $response->headers->get('xkey', null, false);
if (count($tags) === 1) {
// Handle string based header (her gotten as single item array with space separated string)
$tags = explode(' ', $tags[0]);
}
foreach (array_unique($tags) as $tag) {
if (false === $this->saveTag($tag, $digest)) {
throw new \RuntimeException('Unable to store the cache tag meta information.');
}
}
return $key;
} | php | public function write(Request $request, Response $response)
{
$key = parent::write($request, $response);
// Get tags in order to save them
$digest = $response->headers->get('X-Content-Digest');
$tags = $response->headers->get('xkey', null, false);
if (count($tags) === 1) {
// Handle string based header (her gotten as single item array with space separated string)
$tags = explode(' ', $tags[0]);
}
foreach (array_unique($tags) as $tag) {
if (false === $this->saveTag($tag, $digest)) {
throw new \RuntimeException('Unable to store the cache tag meta information.');
}
}
return $key;
} | [
"public",
"function",
"write",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"key",
"=",
"parent",
"::",
"write",
"(",
"$",
"request",
",",
"$",
"response",
")",
";",
"// Get tags in order to save them",
"$",
"digest",
"=",
"$",
"response",
"->",
"headers",
"->",
"get",
"(",
"'X-Content-Digest'",
")",
";",
"$",
"tags",
"=",
"$",
"response",
"->",
"headers",
"->",
"get",
"(",
"'xkey'",
",",
"null",
",",
"false",
")",
";",
"if",
"(",
"count",
"(",
"$",
"tags",
")",
"===",
"1",
")",
"{",
"// Handle string based header (her gotten as single item array with space separated string)",
"$",
"tags",
"=",
"explode",
"(",
"' '",
",",
"$",
"tags",
"[",
"0",
"]",
")",
";",
"}",
"foreach",
"(",
"array_unique",
"(",
"$",
"tags",
")",
"as",
"$",
"tag",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"saveTag",
"(",
"$",
"tag",
",",
"$",
"digest",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Unable to store the cache tag meta information.'",
")",
";",
"}",
"}",
"return",
"$",
"key",
";",
"}"
] | Writes a cache entry to the store for the given Request and Response.
Existing entries are read and any that match the response are removed. This
method calls write with the new list of cache entries.
@param Request $request A Request instance
@param Response $response A Response instance
@return string The key under which the response is stored
@throws \RuntimeException | [
"Writes",
"a",
"cache",
"entry",
"to",
"the",
"store",
"for",
"the",
"given",
"Request",
"and",
"Response",
"."
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/Proxy/TagAwareStore.php#L68-L88 |
ezsystems/ezplatform-http-cache | src/Proxy/TagAwareStore.php | TagAwareStore.saveTag | private function saveTag($tag, $digest)
{
$path = $this->getTagPath($tag) . DIRECTORY_SEPARATOR . $digest;
if (!is_dir(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) {
return false;
}
$tmpFile = tempnam(dirname($path), basename($path));
if (false === $fp = @fopen($tmpFile, 'wb')) {
return false;
}
@fwrite($fp, $digest);
@fclose($fp);
if ($digest != file_get_contents($tmpFile)) {
return false;
}
if (false === @rename($tmpFile, $path)) {
return false;
}
@chmod($path, 0666 & ~umask());
return true;
} | php | private function saveTag($tag, $digest)
{
$path = $this->getTagPath($tag) . DIRECTORY_SEPARATOR . $digest;
if (!is_dir(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) {
return false;
}
$tmpFile = tempnam(dirname($path), basename($path));
if (false === $fp = @fopen($tmpFile, 'wb')) {
return false;
}
@fwrite($fp, $digest);
@fclose($fp);
if ($digest != file_get_contents($tmpFile)) {
return false;
}
if (false === @rename($tmpFile, $path)) {
return false;
}
@chmod($path, 0666 & ~umask());
return true;
} | [
"private",
"function",
"saveTag",
"(",
"$",
"tag",
",",
"$",
"digest",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"getTagPath",
"(",
"$",
"tag",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"digest",
";",
"if",
"(",
"!",
"is_dir",
"(",
"dirname",
"(",
"$",
"path",
")",
")",
"&&",
"false",
"===",
"@",
"mkdir",
"(",
"dirname",
"(",
"$",
"path",
")",
",",
"0777",
",",
"true",
")",
"&&",
"!",
"is_dir",
"(",
"dirname",
"(",
"$",
"path",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"tmpFile",
"=",
"tempnam",
"(",
"dirname",
"(",
"$",
"path",
")",
",",
"basename",
"(",
"$",
"path",
")",
")",
";",
"if",
"(",
"false",
"===",
"$",
"fp",
"=",
"@",
"fopen",
"(",
"$",
"tmpFile",
",",
"'wb'",
")",
")",
"{",
"return",
"false",
";",
"}",
"@",
"fwrite",
"(",
"$",
"fp",
",",
"$",
"digest",
")",
";",
"@",
"fclose",
"(",
"$",
"fp",
")",
";",
"if",
"(",
"$",
"digest",
"!=",
"file_get_contents",
"(",
"$",
"tmpFile",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"false",
"===",
"@",
"rename",
"(",
"$",
"tmpFile",
",",
"$",
"path",
")",
")",
"{",
"return",
"false",
";",
"}",
"@",
"chmod",
"(",
"$",
"path",
",",
"0666",
"&",
"~",
"umask",
"(",
")",
")",
";",
"return",
"true",
";",
"}"
] | Save digest for the given tag.
@param string $tag The tag key
@param string $digest The digest hash to store representing the cache item.
@return bool | [
"Save",
"digest",
"for",
"the",
"given",
"tag",
"."
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/Proxy/TagAwareStore.php#L98-L123 |
ezsystems/ezplatform-http-cache | src/Proxy/TagAwareStore.php | TagAwareStore.purgeByRequest | public function purgeByRequest(Request $request)
{
if (!$request->headers->has('X-Location-Id') && !$request->headers->has('key')) {
return $this->purge($request->getUri());
}
// For BC with older purge code covering most use cases.
$locationId = $request->headers->get('X-Location-Id');
if ($locationId === '*' || $locationId === '.*') {
return $this->purgeAllContent();
}
if ($request->headers->has('key')) {
$tags = explode(' ', $request->headers->get('key'));
} elseif ($locationId[0] === '(' && substr($locationId, -1) === ')') {
// Deprecated: (123|456|789) => Purge for #123, #456 and #789 location IDs.
$tags = array_map(
function ($id) {return 'location-' . $id;},
explode('|', substr($locationId, 1, -1))
);
} else {
$tags = array('location-' . $locationId);
}
if (empty($tags)) {
return false;
}
foreach ($tags as $tag) {
$this->purgeByCacheTag($tag);
}
return true;
} | php | public function purgeByRequest(Request $request)
{
if (!$request->headers->has('X-Location-Id') && !$request->headers->has('key')) {
return $this->purge($request->getUri());
}
// For BC with older purge code covering most use cases.
$locationId = $request->headers->get('X-Location-Id');
if ($locationId === '*' || $locationId === '.*') {
return $this->purgeAllContent();
}
if ($request->headers->has('key')) {
$tags = explode(' ', $request->headers->get('key'));
} elseif ($locationId[0] === '(' && substr($locationId, -1) === ')') {
// Deprecated: (123|456|789) => Purge for #123, #456 and #789 location IDs.
$tags = array_map(
function ($id) {return 'location-' . $id;},
explode('|', substr($locationId, 1, -1))
);
} else {
$tags = array('location-' . $locationId);
}
if (empty($tags)) {
return false;
}
foreach ($tags as $tag) {
$this->purgeByCacheTag($tag);
}
return true;
} | [
"public",
"function",
"purgeByRequest",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"headers",
"->",
"has",
"(",
"'X-Location-Id'",
")",
"&&",
"!",
"$",
"request",
"->",
"headers",
"->",
"has",
"(",
"'key'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"purge",
"(",
"$",
"request",
"->",
"getUri",
"(",
")",
")",
";",
"}",
"// For BC with older purge code covering most use cases.",
"$",
"locationId",
"=",
"$",
"request",
"->",
"headers",
"->",
"get",
"(",
"'X-Location-Id'",
")",
";",
"if",
"(",
"$",
"locationId",
"===",
"'*'",
"||",
"$",
"locationId",
"===",
"'.*'",
")",
"{",
"return",
"$",
"this",
"->",
"purgeAllContent",
"(",
")",
";",
"}",
"if",
"(",
"$",
"request",
"->",
"headers",
"->",
"has",
"(",
"'key'",
")",
")",
"{",
"$",
"tags",
"=",
"explode",
"(",
"' '",
",",
"$",
"request",
"->",
"headers",
"->",
"get",
"(",
"'key'",
")",
")",
";",
"}",
"elseif",
"(",
"$",
"locationId",
"[",
"0",
"]",
"===",
"'('",
"&&",
"substr",
"(",
"$",
"locationId",
",",
"-",
"1",
")",
"===",
"')'",
")",
"{",
"// Deprecated: (123|456|789) => Purge for #123, #456 and #789 location IDs.",
"$",
"tags",
"=",
"array_map",
"(",
"function",
"(",
"$",
"id",
")",
"{",
"return",
"'location-'",
".",
"$",
"id",
";",
"}",
",",
"explode",
"(",
"'|'",
",",
"substr",
"(",
"$",
"locationId",
",",
"1",
",",
"-",
"1",
")",
")",
")",
";",
"}",
"else",
"{",
"$",
"tags",
"=",
"array",
"(",
"'location-'",
".",
"$",
"locationId",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"tags",
")",
")",
"{",
"return",
"false",
";",
"}",
"foreach",
"(",
"$",
"tags",
"as",
"$",
"tag",
")",
"{",
"$",
"this",
"->",
"purgeByCacheTag",
"(",
"$",
"tag",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Purges data from $request.
If key or X-Location-Id (deprecated) header is present, the store will purge cache for given locationId or group of locationIds.
If not, regular purge by URI will occur.
@param \Symfony\Component\HttpFoundation\Request $request
@return bool True if purge was successful. False otherwise | [
"Purges",
"data",
"from",
"$request",
".",
"If",
"key",
"or",
"X",
"-",
"Location",
"-",
"Id",
"(",
"deprecated",
")",
"header",
"is",
"present",
"the",
"store",
"will",
"purge",
"cache",
"for",
"given",
"locationId",
"or",
"group",
"of",
"locationIds",
".",
"If",
"not",
"regular",
"purge",
"by",
"URI",
"will",
"occur",
"."
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/Proxy/TagAwareStore.php#L134-L167 |
ezsystems/ezplatform-http-cache | src/Proxy/TagAwareStore.php | TagAwareStore.purgeByCacheTag | private function purgeByCacheTag($tag)
{
$cacheTagsCacheDir = $this->getTagPath($tag);
if (!file_exists($cacheTagsCacheDir) || !is_dir($cacheTagsCacheDir)) {
return;
}
$files = (new Finder())->files()->in($cacheTagsCacheDir);
foreach ($files as $file) {
// @todo Change to be able to reuse parent::invalidate() or parent::purge() ?
if ($digest = file_get_contents($file->getRealPath())) {
@unlink($this->getPath($digest));
}
@unlink($file);
}
// We let folder stay in case another process have just written new cache tags.
} | php | private function purgeByCacheTag($tag)
{
$cacheTagsCacheDir = $this->getTagPath($tag);
if (!file_exists($cacheTagsCacheDir) || !is_dir($cacheTagsCacheDir)) {
return;
}
$files = (new Finder())->files()->in($cacheTagsCacheDir);
foreach ($files as $file) {
// @todo Change to be able to reuse parent::invalidate() or parent::purge() ?
if ($digest = file_get_contents($file->getRealPath())) {
@unlink($this->getPath($digest));
}
@unlink($file);
}
// We let folder stay in case another process have just written new cache tags.
} | [
"private",
"function",
"purgeByCacheTag",
"(",
"$",
"tag",
")",
"{",
"$",
"cacheTagsCacheDir",
"=",
"$",
"this",
"->",
"getTagPath",
"(",
"$",
"tag",
")",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"cacheTagsCacheDir",
")",
"||",
"!",
"is_dir",
"(",
"$",
"cacheTagsCacheDir",
")",
")",
"{",
"return",
";",
"}",
"$",
"files",
"=",
"(",
"new",
"Finder",
"(",
")",
")",
"->",
"files",
"(",
")",
"->",
"in",
"(",
"$",
"cacheTagsCacheDir",
")",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
"file",
")",
"{",
"// @todo Change to be able to reuse parent::invalidate() or parent::purge() ?",
"if",
"(",
"$",
"digest",
"=",
"file_get_contents",
"(",
"$",
"file",
"->",
"getRealPath",
"(",
")",
")",
")",
"{",
"@",
"unlink",
"(",
"$",
"this",
"->",
"getPath",
"(",
"$",
"digest",
")",
")",
";",
"}",
"@",
"unlink",
"(",
"$",
"file",
")",
";",
"}",
"// We let folder stay in case another process have just written new cache tags.",
"}"
] | Purges cache for tag.
@param string $tag | [
"Purges",
"cache",
"for",
"tag",
"."
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/Proxy/TagAwareStore.php#L182-L198 |
ezsystems/ezplatform-http-cache | src/Proxy/TagAwareStore.php | TagAwareStore.getTagPath | public function getTagPath($tag = null)
{
$path = $this->root . DIRECTORY_SEPARATOR . static::TAG_CACHE_DIR;
if ($tag) {
// Flip the tag so we put id first so it gets sliced into folders.
// (otherwise we would easily reach inode limits on file system)
$tag = strrev($tag);
$path .= DIRECTORY_SEPARATOR . substr($tag, 0, 2) . DIRECTORY_SEPARATOR . substr($tag, 2, 2) . DIRECTORY_SEPARATOR . substr($tag, 4);
}
return $path;
} | php | public function getTagPath($tag = null)
{
$path = $this->root . DIRECTORY_SEPARATOR . static::TAG_CACHE_DIR;
if ($tag) {
// Flip the tag so we put id first so it gets sliced into folders.
// (otherwise we would easily reach inode limits on file system)
$tag = strrev($tag);
$path .= DIRECTORY_SEPARATOR . substr($tag, 0, 2) . DIRECTORY_SEPARATOR . substr($tag, 2, 2) . DIRECTORY_SEPARATOR . substr($tag, 4);
}
return $path;
} | [
"public",
"function",
"getTagPath",
"(",
"$",
"tag",
"=",
"null",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"root",
".",
"DIRECTORY_SEPARATOR",
".",
"static",
"::",
"TAG_CACHE_DIR",
";",
"if",
"(",
"$",
"tag",
")",
"{",
"// Flip the tag so we put id first so it gets sliced into folders.",
"// (otherwise we would easily reach inode limits on file system)",
"$",
"tag",
"=",
"strrev",
"(",
"$",
"tag",
")",
";",
"$",
"path",
".=",
"DIRECTORY_SEPARATOR",
".",
"substr",
"(",
"$",
"tag",
",",
"0",
",",
"2",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"substr",
"(",
"$",
"tag",
",",
"2",
",",
"2",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"substr",
"(",
"$",
"tag",
",",
"4",
")",
";",
"}",
"return",
"$",
"path",
";",
"}"
] | Returns cache dir for $tag.
This method is public only for unit tests.
Use it only if you know what you are doing.
@internal
@param int $tag
@return string | [
"Returns",
"cache",
"dir",
"for",
"$tag",
"."
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/Proxy/TagAwareStore.php#L212-L223 |
ezsystems/ezplatform-http-cache | spec/EventSubscriber/RestKernelViewSubscriberSpec.php | RestKernelViewSubscriberSpec.it_does_nothing_on_content_type_draft | public function it_does_nothing_on_content_type_draft(
GetResponseForControllerResultEvent $event,
Request $request,
ParameterBag $attributes,
ContentType $restValue,
TagHandler $tagHandler
) {
$request->isMethodCacheable()->willReturn(true);
$attributes->get('is_rest_request')->willReturn(true);
$restValue->beConstructedWith([['status' => ContentType::STATUS_DRAFT]]);
$event->getControllerResult()->willReturn($restValue);
$tagHandler->addTags(new AnyValueToken())->shouldNotBecalled();
$event->setControllerResult()->shouldNotBecalled();
$this->tagUIRestResult($event);
} | php | public function it_does_nothing_on_content_type_draft(
GetResponseForControllerResultEvent $event,
Request $request,
ParameterBag $attributes,
ContentType $restValue,
TagHandler $tagHandler
) {
$request->isMethodCacheable()->willReturn(true);
$attributes->get('is_rest_request')->willReturn(true);
$restValue->beConstructedWith([['status' => ContentType::STATUS_DRAFT]]);
$event->getControllerResult()->willReturn($restValue);
$tagHandler->addTags(new AnyValueToken())->shouldNotBecalled();
$event->setControllerResult()->shouldNotBecalled();
$this->tagUIRestResult($event);
} | [
"public",
"function",
"it_does_nothing_on_content_type_draft",
"(",
"GetResponseForControllerResultEvent",
"$",
"event",
",",
"Request",
"$",
"request",
",",
"ParameterBag",
"$",
"attributes",
",",
"ContentType",
"$",
"restValue",
",",
"TagHandler",
"$",
"tagHandler",
")",
"{",
"$",
"request",
"->",
"isMethodCacheable",
"(",
")",
"->",
"willReturn",
"(",
"true",
")",
";",
"$",
"attributes",
"->",
"get",
"(",
"'is_rest_request'",
")",
"->",
"willReturn",
"(",
"true",
")",
";",
"$",
"restValue",
"->",
"beConstructedWith",
"(",
"[",
"[",
"'status'",
"=>",
"ContentType",
"::",
"STATUS_DRAFT",
"]",
"]",
")",
";",
"$",
"event",
"->",
"getControllerResult",
"(",
")",
"->",
"willReturn",
"(",
"$",
"restValue",
")",
";",
"$",
"tagHandler",
"->",
"addTags",
"(",
"new",
"AnyValueToken",
"(",
")",
")",
"->",
"shouldNotBecalled",
"(",
")",
";",
"$",
"event",
"->",
"setControllerResult",
"(",
")",
"->",
"shouldNotBecalled",
"(",
")",
";",
"$",
"this",
"->",
"tagUIRestResult",
"(",
"$",
"event",
")",
";",
"}"
] | ContentType | [
"ContentType"
] | train | https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/spec/EventSubscriber/RestKernelViewSubscriberSpec.php#L95-L112 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.