_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6200 | Httpclient.post | train | public function post($url, $params = array(), $options = array())
{
return $this->request($url, self::POST, $params, $options);
} | php | {
"resource": ""
} |
q6201 | Httpclient.put | train | public function put($url, $params = array(), $options = array())
{
return $this->request($url, self::PUT, $params, $options);
} | php | {
"resource": ""
} |
q6202 | Httpclient.patch | train | public function patch($url, $params = array(), $options = array())
{
return $this->request($url, self::PATCH, $params, $options);
} | php | {
"resource": ""
} |
q6203 | Httpclient.delete | train | public function delete($url, $params = array(), $options = array())
{
return $this->request($url, self::DELETE, $params, $options);
} | php | {
"resource": ""
} |
q6204 | Httpclient.splitHeaders | train | protected function splitHeaders($rawHeaders)
{
$headers = array();
$lines = explode("\n", trim($rawHeaders));
$headers['HTTP'] = array_shift($lines);
foreach ($lines as $h) {
$h = explode(':', $h, 2);
if (isset($h[1])) {
$headers[$h[0]] = trim($h[1]);
}
}
return (object)$headers;
} | php | {
"resource": ""
} |
q6205 | Httpclient.doCurl | train | protected function doCurl()
{
$response = curl_exec($this->curl);
if (curl_errno($this->curl)) {
throw new \Exception(curl_error($this->curl), 1);
}
$curlInfo = curl_getinfo($this->curl);
$results = array(
'curl_info' => $curlInfo,
'response' => $response,
);
return $results;
} | php | {
"resource": ""
} |
q6206 | T3Salutation.translate | train | public function translate( $value )
{
switch( $value )
{
case \Aimeos\MShop\Common\Item\Address\Base::SALUTATION_MR:
return 0;
case \Aimeos\MShop\Common\Item\Address\Base::SALUTATION_MRS:
return 1;
case \Aimeos\MShop\Common\Item\Address\Base::SALUTATION_MISS:
return 2;
case \Aimeos\MShop\Common\Item\Address\Base::SALUTATION_COMPANY:
return 10;
}
return 99;
} | php | {
"resource": ""
} |
q6207 | T3Salutation.reverse | train | public function reverse( $value )
{
switch( $value )
{
case 0:
return \Aimeos\MShop\Common\Item\Address\Base::SALUTATION_MR;
case 1:
return \Aimeos\MShop\Common\Item\Address\Base::SALUTATION_MRS;
case 2:
return \Aimeos\MShop\Common\Item\Address\Base::SALUTATION_MISS;
case 10:
return \Aimeos\MShop\Common\Item\Address\Base::SALUTATION_COMPANY;
}
return \Aimeos\MShop\Common\Item\Address\Base::SALUTATION_UNKNOWN;
} | php | {
"resource": ""
} |
q6208 | JsonApiExtension.createJsonApi | train | protected function createJsonApi($source, DocumentHydrator $hydrator): JsonApiObject
{
$jsonApi = isset($source->version)
? new JsonApiObject($source->version)
: new JsonApiObject();
$hydrator->hydrateObject($jsonApi, $source);
return $jsonApi;
} | php | {
"resource": ""
} |
q6209 | AttachmentsController.preview | train | public function preview($attachmentId = null)
{
// FIXME cache previews
$attachment = $this->Attachments->get($attachmentId);
$this->_checkAuthorization($attachment);
switch ($attachment->filetype) {
case 'image/png':
case 'image/jpg':
case 'image/jpeg':
case 'image/gif':
$image = new \Imagick($attachment->getAbsolutePath());
if (Configure::read('Attachments.autorotate')) {
$this->_autorotate($image);
}
break;
case 'application/pdf':
// Will render a preview of the first page of this PDF
$image = new \Imagick($attachment->getAbsolutePath() . '[0]');
break;
default:
$image = new \Imagick(Plugin::path('Attachments') . '/webroot/img/file.png');
break;
}
$image->setImageFormat('png');
$image->thumbnailImage(80, 80, true, false);
$image->setImageCompression(\Imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality(75);
$image->stripImage();
header('Content-Type: image/' . $image->getImageFormat());
echo $image;
$image->destroy();
exit;
} | php | {
"resource": ""
} |
q6210 | AttachmentsController.view | train | public function view($attachmentId = null)
{
// FIXME cache previews
$attachment = $this->Attachments->get($attachmentId);
$this->_checkAuthorization($attachment);
switch ($attachment->filetype) {
case 'image/png':
case 'image/jpg':
case 'image/jpeg':
case 'image/gif':
$image = new \Imagick($attachment->getAbsolutePath());
if (Configure::read('Attachments.autorotate')) {
$this->_autorotate($image);
}
break;
case 'application/pdf':
header('Content-Type: ' . $attachment->filetype);
$file = new File($attachment->getAbsolutePath());
echo $file->read();
exit;
break;
default:
$image = new \Imagick(Plugin::path('Attachments') . '/webroot/img/file.png');
break;
}
$image->setImageFormat('png');
$image->setImageCompression(\Imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality(75);
$image->stripImage();
header('Content-Type: image/' . $image->getImageFormat());
echo $image;
$image->destroy();
exit;
} | php | {
"resource": ""
} |
q6211 | AttachmentsController.download | train | public function download($attachmentId = null)
{
$attachment = $this->Attachments->get($attachmentId);
$this->_checkAuthorization($attachment);
$this->response->file($attachment->getAbsolutePath(), [
'download' => true,
'name' => $attachment->filename
]);
return $this->response;
} | php | {
"resource": ""
} |
q6212 | AttachmentsController._checkAuthorization | train | protected function _checkAuthorization(Attachment $attachment)
{
if ($attachmentsBehavior = $attachment->getRelatedTable()->behaviors()->get('Attachments')) {
$behaviorConfig = $attachmentsBehavior->config();
if (is_callable($behaviorConfig['downloadAuthorizeCallback'])) {
$relatedEntity = $attachment->getRelatedEntity();
$authorized = $behaviorConfig['downloadAuthorizeCallback']($attachment, $relatedEntity, $this->request);
if ($authorized !== true) {
throw new UnauthorizedException(__d('attachments', 'attachments.unauthorized_for_attachment'));
}
}
}
} | php | {
"resource": ""
} |
q6213 | AttachmentsController._autorotate | train | protected function _autorotate(\Imagick $image)
{
switch ($image->getImageOrientation()) {
case \Imagick::ORIENTATION_TOPRIGHT:
$image->flopImage();
break;
case \Imagick::ORIENTATION_BOTTOMRIGHT:
$image->rotateImage('#000', 180);
break;
case \Imagick::ORIENTATION_BOTTOMLEFT:
$image->flopImage();
$image->rotateImage('#000', 180);
break;
case \Imagick::ORIENTATION_LEFTTOP:
$image->flopImage();
$image->rotateImage('#000', -90);
break;
case \Imagick::ORIENTATION_RIGHTTOP:
$image->rotateImage('#000', 90);
break;
case \Imagick::ORIENTATION_RIGHTBOTTOM:
$image->flopImage();
$image->rotateImage('#000', 90);
break;
case \Imagick::ORIENTATION_LEFTBOTTOM:
$image->rotateImage('#000', -90);
break;
}
$image->setImageOrientation(\Imagick::ORIENTATION_TOPLEFT);
} | php | {
"resource": ""
} |
q6214 | AttachmentsController.saveTags | train | public function saveTags($attachmentId = null)
{
$this->request->allowMethod('post');
$attachment = $this->Attachments->get($attachmentId);
$this->_checkAuthorization($attachment);
if (!TableRegistry::get($attachment->model)) {
throw new \Cake\ORM\Exception\MissingTableClassException('Could not find Table ' . $attachment->model);
}
$inputArray = explode('&', $this->request->input('urldecode'));
$tags = explode('$', explode('=', $inputArray[0])[1]);
unset($inputArray[0]);
// parse the attachments area options from the post data (comes in as a string)
$options = [];
foreach ($inputArray as $option) {
$option = substr($option, 8);
$optionParts = explode(']=', $option);
$options[$optionParts[0]] = $optionParts[1];
}
// set so the first div of the attachments area element is skipped in the view, as it
// serves as target for the Json Action
$options['isAjax'] = true;
$Model = TableRegistry::get($attachment->model);
$Model->saveTags($attachment, $tags);
$entity = $Model->get($attachment->foreign_key, ['contain' => 'Attachments']);
$this->set(compact('entity', 'options'));
} | php | {
"resource": ""
} |
q6215 | Autoload.autoload | train | public function autoload($class)
{
/* On explose la classe par '\' */
$parts = preg_split('#\\\#', $class);
/* On extrait le dernier element. */
$className = array_pop($parts);
/* On créé le chemin vers la classe */
$path = implode('\\', $parts);
$file = $className . '.php';
/*
* Si la classe recherchée est à la racine du namespace le chemin sera
* égale à la clé. Cette condition peut éviter la boucle.
*/
if (isset($this->prefix[ $path ])) {
$filepath = $this->relplaceSlash($this->prefix[ $path ] . self::DS . $file);
if ($this->requireFile($filepath)) {
return $filepath;
}
}
/*
* Recherche une correspondance entre le namespace fournit en librairie
* et la classe instanciée.
*/
foreach ($this->lib as $nameSpace => $src) {
$filepath = $this->relplaceSlash(str_replace($nameSpace, $src, $class) . '.php');
if ($this->requireFile($filepath)) {
return $filepath;
}
}
/*
* Si le namespace n'est pas précisé en librairie, on parcoure les répertoires
* pour chercher une correspondance avec l'arborescence.
*/
foreach ($this->map as $map) {
$filepath = $this->relplaceSlash($map . self::DS . $path . self::DS . $file);
if ($this->requireFile($filepath)) {
return $filepath;
}
}
return false;
} | php | {
"resource": ""
} |
q6216 | Min.sizeMin | train | protected function sizeMin($key, $lengthValue, $min, $not = true)
{
if ($lengthValue < $min && $not) {
$this->addReturn($key, 'must', [ ':min' => $min ]);
} elseif (!($lengthValue < $min) && !$not) {
$this->addReturn($key, 'not', [ ':min' => $min ]);
}
} | php | {
"resource": ""
} |
q6217 | DataStoreController.listAction | train | public function listAction()
{
/** @var FeatureTypeService $featureService */
$featureService = $this->container->get("features");
$featureTypes = $featureService->getFeatureTypeDeclarations();
return new JsonResponse(array(
'list' => $featureTypes,
));
} | php | {
"resource": ""
} |
q6218 | Signature.verify | train | final public function verify(string $header, string $body, int $threshold = 3600): bool
{
$signature = new Verify($this->key, 'sha256', $threshold);
return $signature($body, $header);
} | php | {
"resource": ""
} |
q6219 | Signature.verifyFrom | train | final public function verifyFrom(ResponseInterface $message, int $threshold = 3600): bool
{
$response = new Response($message);
return $this->verify(
$response->getHeader('HTTP_X_SIGNATURE')[0],
$response->getBody(),
$threshold
);
} | php | {
"resource": ""
} |
q6220 | AttributeProcessor.processMethod | train | protected function processMethod(\ReflectionMethod $method, Definition $definition)
{
$annotations = $this->reader->getMethodAnnotations($method);
foreach ($annotations as $annotation)
{
if ($annotation instanceof AttributeAnnotation) {
$this->validateMethodAttribute($annotation, $method);
$attribute = $this->createAttributeByMethod($annotation, $method);
$definition->addAttribute($attribute);
}
}
} | php | {
"resource": ""
} |
q6221 | AttributeProcessor.validateMethodAttribute | train | protected function validateMethodAttribute(AttributeAnnotation $annotation, \ReflectionMethod $method)
{
if (! $method->isPublic()) {
throw new \LogicException(sprintf(
'Attribute annotation can be applied only to non public method "%s".',
$method->getName()
));
}
if ($annotation->getter !== null) {
throw new \LogicException(sprintf(
'The "getter" property of Attribute annotation applied to method "%s" is useless.',
$method->getName()
));
}
} | php | {
"resource": ""
} |
q6222 | AttributeProcessor.createAttributeByProperty | train | protected function createAttributeByProperty(AttributeAnnotation $annotation, \ReflectionProperty $property): Attribute
{
$name = ($annotation->name === null)
? $property->getName()
: $annotation->name;
$getter = ($annotation->getter === null)
? $this->resolveGetter($property)
: $annotation->getter;
$setter = ($annotation->setter === null)
? $this->resolveSetter($property)
: $annotation->setter;
$attribute = new Attribute($name, $getter);
$attribute->setPropertyName($property->getName());
if ($setter !== null) {
$attribute->setSetter($setter);
}
$this->processAttributeOptions($annotation, $attribute);
return $attribute;
} | php | {
"resource": ""
} |
q6223 | AttributeProcessor.createAttributeByMethod | train | protected function createAttributeByMethod(AttributeAnnotation $annotation, \ReflectionMethod $method): Attribute
{
$name = ($annotation->name === null)
? $this->resolveNameByMethod($method)
: $annotation->name;
$attribute = new Attribute($name, $method->getName());
if ($annotation->setter !== null) {
$attribute->setSetter($annotation->setter);
}
if ($annotation->type !== null) {
$this->processDataType($annotation->type, $attribute);
}
return $attribute;
} | php | {
"resource": ""
} |
q6224 | AttributeProcessor.resolveNameByMethod | train | protected function resolveNameByMethod(\ReflectionMethod $method): string
{
$name = $method->getName();
if (preg_match('~^(?:get|is)(?<name>[a-z0-9_]+)~i', $name, $matches)) {
return lcfirst($matches['name']);
}
return $name;
} | php | {
"resource": ""
} |
q6225 | PaymentProcessor.executeQuery | train | public function executeQuery($queryName, PaymentTransaction $paymentTransaction)
{
$query = $this->getQuery($queryName);
$response = null;
try
{
$request = $query->createRequest($paymentTransaction);
$response = $this->makeRequest($request);
$query->processResponse($paymentTransaction, $response);
}
catch (Exception $e)
{
$this->handleException($e, $paymentTransaction, $response);
return;
}
$this->handleQueryResult($paymentTransaction, $response);
return $response;
} | php | {
"resource": ""
} |
q6226 | PaymentProcessor.processCustomerReturn | train | public function processCustomerReturn(CallbackResponse $callbackResponse, PaymentTransaction $paymentTransaction)
{
$callbackResponse->setType('customer_return');
return $this->processPaynetEasyCallback($callbackResponse, $paymentTransaction);
} | php | {
"resource": ""
} |
q6227 | PaymentProcessor.processPaynetEasyCallback | train | public function processPaynetEasyCallback(CallbackResponse $callbackResponse, PaymentTransaction $paymentTransaction)
{
try
{
$this->getCallback($callbackResponse->getType())
->processCallback($paymentTransaction, $callbackResponse);
}
catch (Exception $e)
{
$this->handleException($e, $paymentTransaction, $callbackResponse);
return;
}
$this->handleQueryResult($paymentTransaction, $callbackResponse);
return $callbackResponse;
} | php | {
"resource": ""
} |
q6228 | PaymentProcessor.setHandler | train | public function setHandler($handlerName, $handlerCallback)
{
$this->checkHandlerName($handlerName);
if (!is_callable($handlerCallback))
{
throw new RuntimeException("Handler callback must be callable");
}
$this->handlers[$handlerName] = $handlerCallback;
return $this;
} | php | {
"resource": ""
} |
q6229 | PaymentProcessor.callHandler | train | protected function callHandler($handlerName)
{
$this->checkHandlerName($handlerName);
$arguments = func_get_args();
array_shift($arguments);
if ($this->hasHandler($handlerName))
{
call_user_func_array($this->handlers[$handlerName], $arguments);
}
return $this;
} | php | {
"resource": ""
} |
q6230 | Link.merge | train | public function merge(self $link)
{
$this->parameters = array_replace(
$link->getParameters(),
$this->parameters
);
$this->metadata = array_replace(
$link->getMetadata(),
$this->metadata
);
} | php | {
"resource": ""
} |
q6231 | PasswordGrant.authenticate | train | public function authenticate(string $username, string $password, ?string $scope = '*'): Response
{
$body = $this->mergeApiBody(
\array_filter(\compact('username', 'password', 'scope'))
);
return $this->send('POST', 'oauth/token', $this->getApiHeaders(), $body)
->validateWith(function ($statusCode, $response) {
if ($statusCode !== 200) {
throw new RuntimeException('Unable to generate access token!');
}
$this->client->setAccessToken($response->toArray()['access_token']);
});
} | php | {
"resource": ""
} |
q6232 | PasswordGrant.getApiBody | train | protected function getApiBody(): array
{
$clientId = $this->client->getClientId();
$clientSecret = $this->client->getClientSecret();
if (empty($clientId) || empty($clientSecret)) {
throw new InvalidArgumentException('Missing client_id and client_secret information!');
}
return [
'scope' => '*',
'grant_type' => 'password',
'client_id' => $clientId,
'client_secret' => $clientSecret,
];
} | php | {
"resource": ""
} |
q6233 | Validator.isValid | train | public function isValid()
{
$this->key = [];
$this->errors = [];
$this->correctInputs();
foreach ($this->rules as $key => $test) {
/* Si la valeur est requise uniquement avec la présence de certains champs. */
if ($this->isRequiredWhith($key) && $this->isOneVoidValue($key)) {
continue;
}
/* Si la valeur est requise uniquement en l'absence de certains champs. */
if ($this->isRequiredWhithout($key) && !$this->isAllVoidValue($key)) {
continue;
}
/* Si la valeur n'est pas requise et vide. */
if ($this->isNotRequired($key) && $this->isVoidValue($key)) {
continue;
}
/* Pour chaque règle cherche les fonctions séparées par un pipe. */
foreach (explode('|', $test) as $rule) {
$this->parseRules($key, $rule);
}
}
return empty($this->errors);
} | php | {
"resource": ""
} |
q6234 | Validator.isNotRequired | train | protected function isNotRequired($key)
{
return strstr($this->rules[ $key ], '!required') && !strstr($this->rules[ $key ], '!required_');
} | php | {
"resource": ""
} |
q6235 | Validator.isVoidValue | train | protected function isVoidValue($key)
{
$require = new Rules\Required;
$require->execute('required', $key, $this->inputs[ $key ], false, true);
return $require->hasErrors();
} | php | {
"resource": ""
} |
q6236 | StatusQuery.setNeededAction | train | protected function setNeededAction(Response $response) {
if ($response->hasHtml())
{
$response->setNeededAction(Response::NEEDED_SHOW_HTML);
}
elseif ($response->isProcessing())
{
$response->setNeededAction(Response::NEEDED_STATUS_UPDATE);
}
} | php | {
"resource": ""
} |
q6237 | StatusQuery.setFieldsFromResponse | train | protected function setFieldsFromResponse(PaymentTransaction $paymentTransaction, Response $response) {
$payment = $paymentTransaction->getPayment();
$card = $payment->getRecurrentCardFrom();
if ($response->offsetExists('card-ref-id'))
{
$card->setPaynetId($response['card-ref-id']);
}
if ($response->offsetExists('last-four-digits'))
{
$card->setLastFourDigits($response['last-four-digits']);
}
if ($response->offsetExists('bin'))
{
$card->setBin($response['bin']);
}
if ($response->offsetExists('cardholder-name'))
{
$card->setCardPrintedName($response['cardholder-name']);
}
if ($response->offsetExists('card-exp-month'))
{
$card->setExpireMonth($response['card-exp-month']);
}
if ($response->offsetExists('card-exp-year'))
{
$card->setExpireYear($response['card-exp-year']);
}
if ($response->offsetExists('card-hash-id'))
{
$card->setCardHashId($response['card-hash-id']);
}
if ($response->offsetExists('card-type'))
{
$card->setCardType($response['card-type']);
}
} | php | {
"resource": ""
} |
q6238 | Colors.colorize | train | public static function colorize($text, $fgcolor = null, $bgcolor = null)
{
$colors = '';
if ($bgcolor) {
$colors .= self::getBgColorString(self::getColorCode($bgcolor));
}
if ($fgcolor) {
$colors .= self::getFgColorString(self::getColorCode($fgcolor));
}
if ($colors) {
$text = $colors . $text . self::RESET;
}
return $text;
} | php | {
"resource": ""
} |
q6239 | Colors.colorizeLines | train | public static function colorizeLines($text, $fgcolor = null, $bgcolor = null)
{
$lines = explode("\n", $text);
foreach ($lines as &$line) {
$line = self::colorize($line, $fgcolor, $bgcolor);
}
return implode("\n", $lines);
} | php | {
"resource": ""
} |
q6240 | Colors.getColorCode | train | public static function getColorCode($color, $options = array())
{
$code = (int) $color;
if (is_string($color)) {
$options = array_merge(explode('+', strtolower($color)), $options);
$color = array_shift($options);
if (!isset(self::$colors[$color])) {
throw new ConsoleException("Unknown color '$color'");
}
$code = self::$colors[$color];
}
foreach ($options as $opt) {
$opt = strtolower($opt);
if (!isset(self::$options[$opt])) {
throw new ConsoleException("Unknown option '$color'");
}
$code = $code | self::$options[$opt];
}
return $code;
} | php | {
"resource": ""
} |
q6241 | Colors.getFgColorString | train | public static function getFgColorString($colorCode)
{
list($color, $options) = self::extractColorAndOptions($colorCode);
$codes = array_filter(array_merge($options, array("3{$color}")));
return sprintf("\033[%sm", implode(';', $codes));
} | php | {
"resource": ""
} |
q6242 | Colors.extractColorAndOptions | train | private static function extractColorAndOptions($colorCode)
{
$options = array();
foreach (self::$options as $name => $bit) {
if (($colorCode & $bit) === $bit) {
$options[] = self::$codes[$bit];
$colorCode = $colorCode & ~$bit;
}
}
if (!isset(self::$codes[$colorCode])) {
throw new ConsoleException("Cannot parse color code");
}
return array(self::$codes[$colorCode], $options);
} | php | {
"resource": ""
} |
q6243 | CookieSwoole.setSecret | train | public function setSecret($name, $value, $expire = 604800, $path = '/', $domain = '')
{
$value = \ePHP\Hash\Encrypt::encryptG($value, md5($_SERVER['HTTP_HOST'].APP_PATH.SERVER_MODE));
$this->set($name, $value, $expire, $path, $domain);
} | php | {
"resource": ""
} |
q6244 | CookieSwoole.getSecret | train | public function getSecret($name)
{
$value = $this->get($name);
if (empty($value)) {
return false;
} else {
return \ePHP\Hash\Encrypt::decryptG($value, md5($_SERVER['HTTP_HOST'].APP_PATH.SERVER_MODE));
}
} | php | {
"resource": ""
} |
q6245 | Vehicles.get | train | public function get(int $vehicleId, ?Query $query = null): Response
{
$this->requiresAccessToken();
return $this->send(
'GET', "vehicles/{$vehicleId}", $this->getApiHeaders(), $this->buildHttpQuery($query)
);
} | php | {
"resource": ""
} |
q6246 | Vehicles.update | train | public function update(int $vehicleId, array $payload): Response
{
$this->requiresAccessToken();
return $this->sendJson(
'PATCH', "vehicles/{$vehicleId}", $this->getApiHeaders(), $payload
);
} | php | {
"resource": ""
} |
q6247 | DataTypeManager.registerDataTypeHandler | train | public function registerDataTypeHandler(DataTypeHandlerInterface $handler)
{
foreach ($handler->supports() as $name) {
$this->handlers[$name] = $handler;
}
} | php | {
"resource": ""
} |
q6248 | DataTypeManager.processHandlerToResource | train | protected function processHandlerToResource(Attribute $definition, $value)
{
$type = $definition->getType();
$handler = $this->handlers[$type];
$parameters = $definition->getTypeParameters();
if (! $definition->isMany()) {
return $handler->toResource($value, $type, $parameters);
}
if (! $value instanceof \Traversable && ! is_array($value)) {
throw new NotIterableAttribute($definition, $value);
}
$collection = [];
foreach ($value as $item) {
$collection[] = $handler->toResource($item, $type, $parameters);
}
return $collection;
} | php | {
"resource": ""
} |
q6249 | DataTypeManager.processHandlerFromResource | train | protected function processHandlerFromResource(Attribute $definition, $value)
{
$type = $definition->getType();
$handler = $this->handlers[$type];
$parameters = $definition->getTypeParameters();
if (! $definition->isMany()) {
return $handler->fromResource($value, $type, $parameters);
}
if (! $value instanceof \Traversable && ! is_array($value)) {
throw new NotIterableAttribute($definition, $value);
}
$collection = new \ArrayObject();
foreach ($value as $item) {
$collection[] = $handler->fromResource($item, $type, $parameters);
}
return $collection;
} | php | {
"resource": ""
} |
q6250 | FieldsManagerTrait.filterFieldList | train | public static function filterFieldList($fieldsList, $filters = array())
{
$result = array();
foreach ($fieldsList as $field) {
if (in_array($field->id, $filters, true)) {
$result[] = $field;
}
}
return $result;
} | php | {
"resource": ""
} |
q6251 | FieldsManagerTrait.filterFieldListByTag | train | public static function filterFieldListByTag($fieldsList, $itemType, $itemProp)
{
$result = array();
$tag = md5($itemProp.IDSPLIT.$itemType);
foreach ($fieldsList as $field) {
if ($field->tag !== $tag) {
continue;
}
if (($field->itemtype !== $itemType) || ($field->itemprop !== $itemProp)) {
continue;
}
$result[] = $field;
}
return $result;
} | php | {
"resource": ""
} |
q6252 | FieldsManagerTrait.reduceFieldList | train | public static function reduceFieldList($fieldsList, $isRead = false, $isWrite = false)
{
$result = array();
foreach ($fieldsList as $field) {
//==============================================================================
// Filter Non-Readable Fields
if ($isRead && !$field->read) {
continue;
}
//==============================================================================
// Filter Non-Writable Fields
if ($isWrite && !$field->write) {
continue;
}
$result[] = $field->id;
}
return $result;
} | php | {
"resource": ""
} |
q6253 | FieldsManagerTrait.isListField | train | public static function isListField($fieldType)
{
//====================================================================//
// Safety Check
if (empty($fieldType)) {
return false;
}
//====================================================================//
// Detects Lists
$list = explode(LISTSPLIT, $fieldType);
if (is_array($list) && (2 == count($list))) {
//====================================================================//
// If List Detected, Prepare Field List Information Array
return array('fieldname' => $list[0], 'listname' => $list[1]);
}
return false;
} | php | {
"resource": ""
} |
q6254 | FieldsManagerTrait.fieldName | train | public static function fieldName($listFieldName)
{
//====================================================================//
// Decode
$result = self::isListField($listFieldName);
if (empty($result)) {
return false;
}
//====================================================================//
// Return Field Identifier
return $result['fieldname'];
} | php | {
"resource": ""
} |
q6255 | FieldsManagerTrait.listName | train | public static function listName($listFieldName)
{
//====================================================================//
// Decode
$result = self::isListField($listFieldName);
if (empty($result)) {
return false;
}
//====================================================================//
// Return List Name
return $result['listname'];
} | php | {
"resource": ""
} |
q6256 | FieldsManagerTrait.baseType | train | public static function baseType($fieldId)
{
//====================================================================//
// Detect List Id Fields
if (self::isListField($fieldId)) {
$fieldId = self::fieldName($fieldId);
}
//====================================================================//
// Detect Objects Id Fields
if (self::isIdField((string) $fieldId)) {
$fieldId = self::objectType((string) $fieldId);
}
return $fieldId;
} | php | {
"resource": ""
} |
q6257 | FieldsManagerTrait.isIdField | train | public static function isIdField($fieldId)
{
//====================================================================//
// Safety Check
if (empty($fieldId)) {
return false;
}
//====================================================================//
// Detects ObjectId
$list = explode(IDSPLIT, $fieldId);
if (is_array($list) && (2 == count($list))) {
//====================================================================//
// If List Detected, Prepare Field List Information Array
$result['ObjectId'] = $list[0];
$result['ObjectType'] = $list[1];
return $result;
}
return false;
} | php | {
"resource": ""
} |
q6258 | FieldsManagerTrait.objectId | train | public static function objectId($fieldId)
{
//====================================================================//
// decode
$result = self::isIdField($fieldId);
if (empty($result)) {
return false;
}
//====================================================================//
// Return List Name
return $result['ObjectId'];
} | php | {
"resource": ""
} |
q6259 | FieldsManagerTrait.objectType | train | public static function objectType($fieldId)
{
//====================================================================//
// decode
$result = self::isIdField($fieldId);
if (empty($result)) {
return false;
}
//====================================================================//
// Return Field Identifier
return $result['ObjectType'];
} | php | {
"resource": ""
} |
q6260 | FieldsManagerTrait.extractRawData | train | public static function extractRawData($objectData, $filter)
{
$filteredData = self::filterData($objectData, array($filter));
//====================================================================//
// Explode List Field Id
$isList = self::isListField($filter);
//====================================================================//
// Simple Single Field
if (!$isList) {
if (isset($filteredData[$filter])) {
return $filteredData[$filter];
}
//====================================================================//
// List Field
} else {
//====================================================================//
// Check List Exists
if (!isset($filteredData[self::listName($filter)])) {
return null;
}
//====================================================================//
// Parse Raw List Data
$result = array();
foreach ($filteredData[self::listName($filter)] as $key => $item) {
$result[$key] = $item[self::fieldName($filter)];
}
return $result;
}
//====================================================================//
// Field Not Received or is Empty
return null;
} | php | {
"resource": ""
} |
q6261 | FieldsManagerTrait.filterData | train | public static function filterData($objectData, $filters = array())
{
$result = array();
$listFilters = array();
//====================================================================//
// Process All Single Fields Ids & Store Sorted List Fields Ids
foreach ($filters as $fieldId) {
//====================================================================//
// Explode List Field Id
$isList = self::isListField($fieldId);
//====================================================================//
// Single Field Data Type
if ((!$isList) && (array_key_exists($fieldId, $objectData))) {
$result[$fieldId] = $objectData[$fieldId];
} elseif (!$isList) {
continue;
}
//====================================================================//
// List Field Data Type
$listName = $isList['listname'];
$fieldName = $isList['fieldname'];
//====================================================================//
// Check List Data are Present in Block
if (!array_key_exists($listName, $objectData)) {
continue;
}
//====================================================================//
// Create List
if (!array_key_exists($listName, $listFilters)) {
$listFilters[$listName] = array();
}
$listFilters[$listName][] = $fieldName;
}
//====================================================================//
// Process All List Fields Ids Filters
foreach ($listFilters as $listName => $listFilters) {
$result[$listName] = self::filterListData($objectData[$listName], $listFilters);
}
return $result;
} | php | {
"resource": ""
} |
q6262 | FieldsManagerTrait.filterListData | train | public static function filterListData($objectData, $filters = array())
{
$result = array();
foreach ($objectData as $fieldData) {
$filteredItems = array();
//====================================================================//
// Ensure Item is An Array of Fields
if (!is_array($fieldData) && !($fieldData instanceof ArrayObject)) {
continue;
}
//====================================================================//
// Convert ArrayObjects to Array
if ($fieldData instanceof ArrayObject) {
$fieldData = $fieldData->getArrayCopy();
}
//====================================================================//
// Search for Field in Item Block
foreach ($filters as $fieldId) {
if (array_key_exists($fieldId, $fieldData)) {
$filteredItems[$fieldId] = $fieldData[$fieldId];
}
}
$result[] = $filteredItems;
}
return $result;
} | php | {
"resource": ""
} |
q6263 | Response.setNeededAction | train | public function setNeededAction($neededAction)
{
if (!in_array($neededAction, static::$allowedNeededActions))
{
throw new RuntimeException("Unknown needed action: '{$neededAction}'");
}
$this->neededAction = $neededAction;
return $this;
} | php | {
"resource": ""
} |
q6264 | Response.getError | train | public function getError()
{
if($this->isError() || $this->isDeclined())
{
return new PaynetException($this->getErrorMessage(), $this->getErrorCode());
}
else
{
throw new RuntimeException('Response has no error');
}
} | php | {
"resource": ""
} |
q6265 | Response.getAnyKey | train | protected function getAnyKey(array $keys)
{
foreach($keys as $key)
{
$value = $this->getValue($key);
if(!is_null($value))
{
return $value;
}
}
} | php | {
"resource": ""
} |
q6266 | Jwt.loadToken | train | public function loadToken($token, $validate = true, $verify = true)
{
$token = $this->getParser()->parse((string) $token);
if ($validate && !$this->validateToken($token)) {
return null;
}
if ($verify && !$this->verifyToken($token)) {
return null;
}
return $token;
} | php | {
"resource": ""
} |
q6267 | Xml._toArray | train | private static function _toArray($data, $recursion = false)
{
$tmp = array();
$data = (array) $data;
foreach ($data as $k => $v) {
$v = (array) $v;
if (isset($v[0]) && is_string($v[0])) {
$tmp[$k] = $v[0];
} else {
$tmp[$k] = self::_toArray($v, true);
}
}
return $tmp;
} | php | {
"resource": ""
} |
q6268 | Utils.find | train | public static function find($filename, $dirs = array())
{
if (empty($dirs)) {
if ($filename = realpath($filename)) {
return $filename;
}
} else {
foreach ((array) $dirs as $dir) {
$pathname = self::join($dir, $filename);
if ($pathname = realpath($pathname)) {
return $pathname;
}
}
}
return false;
} | php | {
"resource": ""
} |
q6269 | Utils.filterFiles | train | public static function filterFiles($args, $allowWildcards = true)
{
$files = array();
foreach ($args as $arg) {
if (file_exists($arg)) {
$files[] = $arg;
} else if ($allowWildcards && strpos($arg, '*') !== false) {
$files = array_merge($files, glob($arg));
}
}
return $files;
} | php | {
"resource": ""
} |
q6270 | Utils.join | train | public static function join($path1, $path2) {
$ds = DIRECTORY_SEPARATOR;
return str_replace("$ds$ds", $ds, implode($ds, array_filter(func_get_args())));
} | php | {
"resource": ""
} |
q6271 | Utils.touch | train | public static function touch($filename, $content = '')
{
self::mkdir(dirname($filename));
file_put_contents($filename, $content);
} | php | {
"resource": ""
} |
q6272 | Utils.computeFuncParams | train | public static function computeFuncParams(ReflectionFunctionAbstract $reflection, array $args, array $options, $needTagInDocComment = true)
{
if ($needTagInDocComment && !preg_match('/@compute-params/', $reflection->getDocComment())) {
return array($args, $options);
}
$nbRequiredParams = $reflection->getNumberOfRequiredParameters();
if (count($args) < $nbRequiredParams) {
throw new ConsoleException("Not enough parameters in '" . $reflection->getName() . "'");
}
$params = $args;
if (count($args) > $nbRequiredParams) {
$params = array_slice($args, 0, $nbRequiredParams);
$args = array_slice($args, $nbRequiredParams);
}
foreach ($reflection->getParameters() as $param) {
if ($param->isOptional() && substr($param->getName(), 0, 1) !== '_') {
if (array_key_exists($param->getName(), $options)) {
$params[] = $options[$param->getName()];
unset($options[$param->getName()]);
} else {
$params[] = $param->getDefaultValue();
}
}
}
$params[] = $args;
$params[] = $options;
return $params;
} | php | {
"resource": ""
} |
q6273 | ControllerManager.initialize | train | private function initialize(AbstractController $controller)
{
foreach ($this->initializers as $initializer) {
if ($initializer instanceof InitializerInterface) {
$initializer->initialize($controller, $this);
} else {
call_user_func($initializer, $controller, $this);
}
}
} | php | {
"resource": ""
} |
q6274 | Stream.tell | train | public function tell() : int
{
if (! \is_resource($this->resource))
{
throw new Exception\UntellableStreamException('Stream is not resourceable');
}
$result = \ftell($this->resource);
if (false === $result)
{
throw new Exception\UntellableStreamException('Unable to get the stream pointer position');
}
return $result;
} | php | {
"resource": ""
} |
q6275 | Stream.isSeekable | train | public function isSeekable() : bool
{
if (! \is_resource($this->resource))
{
return false;
}
$metadata = \stream_get_meta_data($this->resource);
return $metadata['seekable'];
} | php | {
"resource": ""
} |
q6276 | Stream.rewind | train | public function rewind() : void
{
if (! \is_resource($this->resource))
{
throw new Exception\UnseekableStreamException('Stream is not resourceable');
}
if (! $this->isSeekable())
{
throw new Exception\UnseekableStreamException('Stream is not seekable');
}
$result = \fseek($this->resource, 0, \SEEK_SET);
if (! (0 === $result))
{
throw new Exception\UnseekableStreamException('Unable to move the stream pointer to beginning');
}
} | php | {
"resource": ""
} |
q6277 | Stream.seek | train | public function seek($offset, $whence = \SEEK_SET) : void
{
if (! \is_resource($this->resource))
{
throw new Exception\UnseekableStreamException('Stream is not resourceable');
}
if (! $this->isSeekable())
{
throw new Exception\UnseekableStreamException('Stream is not seekable');
}
$result = \fseek($this->resource, $offset, $whence);
if (! (0 === $result))
{
throw new Exception\UnseekableStreamException('Unable to move the stream pointer to the given position');
}
} | php | {
"resource": ""
} |
q6278 | Stream.isWritable | train | public function isWritable() : bool
{
if (! \is_resource($this->resource))
{
return false;
}
$metadata = \stream_get_meta_data($this->resource);
return ! (false === \strpbrk($metadata['mode'], '+acwx'));
} | php | {
"resource": ""
} |
q6279 | Stream.write | train | public function write($string) : int
{
if (! \is_resource($this->resource))
{
throw new Exception\UnwritableStreamException('Stream is not resourceable');
}
if (! $this->isWritable())
{
throw new Exception\UnwritableStreamException('Stream is not writable');
}
$result = \fwrite($this->resource, $string);
if (false === $result)
{
throw new Exception\UnwritableStreamException('Unable to write to the stream');
}
return $result;
} | php | {
"resource": ""
} |
q6280 | Stream.read | train | public function read($length) : string
{
if (! \is_resource($this->resource))
{
throw new Exception\UnreadableStreamException('Stream is not resourceable');
}
if (! $this->isReadable())
{
throw new Exception\UnreadableStreamException('Stream is not readable');
}
$result = \fread($this->resource, $length);
if (false === $result)
{
throw new Exception\UnreadableStreamException('Unable to read from the stream');
}
return $result;
} | php | {
"resource": ""
} |
q6281 | Stream.getContents | train | public function getContents() : string
{
if (! \is_resource($this->resource))
{
throw new Exception\UnreadableStreamException('Stream is not resourceable');
}
if (! $this->isReadable())
{
throw new Exception\UnreadableStreamException('Stream is not readable');
}
$result = \stream_get_contents($this->resource);
if (false === $result)
{
throw new Exception\UnreadableStreamException('Unable to read remainder of the stream');
}
return $result;
} | php | {
"resource": ""
} |
q6282 | Stream.getMetadata | train | public function getMetadata($key = null)
{
if (! \is_resource($this->resource))
{
return null;
}
$metadata = \stream_get_meta_data($this->resource);
if (! (null === $key))
{
return $metadata[$key] ?? null;
}
return $metadata;
} | php | {
"resource": ""
} |
q6283 | Stream.getSize | train | public function getSize() : ?int
{
if (! \is_resource($this->resource))
{
return null;
}
$stats = \fstat($this->resource);
if (false === $stats)
{
return null;
}
return $stats['size'];
} | php | {
"resource": ""
} |
q6284 | SayCommand.executeHello | train | public function executeHello(array $args, array $options = array())
{
$name = 'unknown';
if (empty($args)) {
$dialog = new Dialog($this->console);
$name = $dialog->ask('What is your name?', $name);
} else {
$name = $args[0];
}
$this->writeln(sprintf('hello %s!', $name));
} | php | {
"resource": ""
} |
q6285 | Uri.filterPort | train | protected function filterPort($port)
{
if (empty($port)) {
return null;
}
if (!self::validePort($port)) {
throw new \InvalidArgumentException('The port is not in the TCP/UDP port.');
}
return $this->scheme !== '' && !$this->validPortStandard($port)
? (int) $port
: null;
} | php | {
"resource": ""
} |
q6286 | Uri.filterFragment | train | protected function filterFragment($fragment)
{
$fragmentStr = $this->filterString($fragment);
$fragmentDecode = rawurldecode($fragmentStr);
return rawurlencode(ltrim($fragmentDecode, '#'));
} | php | {
"resource": ""
} |
q6287 | Uri.filterPath | train | protected function filterPath($path)
{
$pathStr = $this->filterString($path);
$pathDecode = rawurldecode($pathStr);
$dataPath = array_map(
function ($value) {
return rawurlencode($value);
},
explode('/', $pathDecode)
);
return implode('/', $dataPath);
} | php | {
"resource": ""
} |
q6288 | Uri.validPortStandard | train | protected function validPortStandard($port)
{
return in_array($port, $this->ports) &&
$this->scheme === array_keys($this->ports, $port)[ 0 ];
} | php | {
"resource": ""
} |
q6289 | FEUsersAddSiteIdTypo3.migrate | train | public function migrate()
{
$table = 'fe_users';
$column = 'siteid';
$this->msg( sprintf( 'Adding "%1$s" column to "%2$s" table', $column, $table ), 0 );
$schema = $this->getSchema( 'db-customer' );
if( isset( $this->migrate[$schema->getName()] )
&& $schema->tableExists( $table ) === true
&& $schema->columnExists( $table, $column ) === false )
{
foreach ( $this->migrate[$schema->getName()] as $stmt )
{
$this->execute( $stmt );
}
$this->status( 'done' );
}
else
{
$this->status( 'OK' );
}
} | php | {
"resource": ""
} |
q6290 | DIContainerFactory.getDefinitionsFilePath | train | private function getDefinitionsFilePath(array $config)
{
$filePath = __DIR__ . '/../../../../../../../config/php-di.config.php';
if (isset($config['definitionsFile'])) {
$filePath = $config['definitionsFile'];
}
if (!file_exists($filePath)) {
throw new \Exception('DI definitions file missing.');
}
return $filePath;
} | php | {
"resource": ""
} |
q6291 | ConsoleController.clearCacheAction | train | public function clearCacheAction()
{
/* @var $cache FlushableCache */
$cache = $this->serviceLocator->get('DiCache');
if ($cache instanceof FlushableCache) {
$cache->flushAll();
}
echo "PHP DI definitions cache was cleared." . PHP_EOL . PHP_EOL;
} | php | {
"resource": ""
} |
q6292 | ErrorsContainer.errorsToArray | train | protected function errorsToArray(): array
{
$errors = [];
foreach ($this->errors as $error)
{
$errors[] = $error->toArray();
}
return $errors;
} | php | {
"resource": ""
} |
q6293 | AttachmentsTable.addUploads | train | public function addUploads(EntityInterface $entity, array $uploads)
{
$attachments = [];
foreach ($uploads as $path => $tags) {
if (!(array_keys($uploads) !== range(0, count($uploads) - 1))) {
// if only paths and no tags
$path = $tags;
$tags = [];
}
$file = Configure::read('Attachments.tmpUploadsPath') . $path;
$attachment = $this->createAttachmentEntity($entity, $file, $tags);
$this->save($attachment);
$attachments[] = $attachment;
}
$entity->attachments = $attachments;
} | php | {
"resource": ""
} |
q6294 | AttachmentsTable.addUpload | train | public function addUpload(EntityInterface $entity, $upload)
{
$tags = [];
$path = $upload;
if (is_array($upload)) {
$tags = reset($upload);
$path = reset(array_flip($upload));
}
$file = Configure::read('Attachments.tmpUploadsPath') . $path;
$attachment = $this->createAttachmentEntity($entity, $file, $tags);
$save = $this->save($attachment);
if ($save) {
return $attachment;
}
return $save;
} | php | {
"resource": ""
} |
q6295 | AttachmentsTable.afterSave | train | public function afterSave(Event $event, Attachment $attachment, \ArrayObject $options)
{
if ($attachment->tmpPath) {
// Make sure the folder is created
$folder = new Folder();
$targetDir = Configure::read('Attachments.path') . dirname($attachment->filepath);
if (!$folder->create($targetDir)) {
throw new \Exception("Folder {$targetDir} could not be created.");
}
$targetPath = Configure::read('Attachments.path') . $attachment->filepath;
if (!rename($attachment->tmpPath, $targetPath)) {
throw new \Exception("Temporary file {$attachment->tmpPath} could not be moved to {$attachment->filepath}");
}
$attachment->tmpPath = null;
}
} | php | {
"resource": ""
} |
q6296 | AttachmentsTable.createAttachmentEntity | train | public function createAttachmentEntity(EntityInterface $entity, $filePath, array $tags = [])
{
if (!file_exists($filePath)) {
throw new \Exception("File {$filePath} does not exist.");
}
if (!is_readable($filePath)) {
throw new \Exception("File {$filePath} cannot be read.");
}
$file = new File($filePath);
$info = $file->info();
// in filepath, we store the path relative to the Attachment.path configuration
// to make it easy to switch storage
$info = $this->__getFileName($info, $entity);
$targetPath = $entity->source() . '/' . $entity->id . '/' . $info['basename'];
$attachment = $this->newEntity([
'model' => $entity->source(),
'foreign_key' => $entity->id,
'filename' => $info['basename'],
'filesize' => $info['filesize'],
'filetype' => $info['mime'],
'filepath' => $targetPath,
'tmpPath' => $filePath,
'tags' => $tags
]);
return $attachment;
} | php | {
"resource": ""
} |
q6297 | AttachmentsTable.__getFileName | train | private function __getFileName($fileInfo, EntityInterface $entity, $id = 0)
{
if (!file_exists(Configure::read('Attachments.path') . $entity->source() . '/' . $entity->id . '/' . $fileInfo['basename'])) {
return $fileInfo;
}
$fileInfo['basename'] = $fileInfo['filename'] . ' (' . ++$id . ').' . $fileInfo['extension'];
return $this->__getFileName($fileInfo, $entity, $id);
} | php | {
"resource": ""
} |
q6298 | DocumentHydrator.hydrate | train | public function hydrate($source): AbstractDocument
{
if (! isset($source->data)) {
return $this->processNoDataDocument($source);
}
if (is_object($source->data)) {
return $this->processSingleResourceDocument($source);
}
if (is_array($source->data)) {
return $this->processResourceCollectionDocument($source);
}
throw new InvalidDocumentException('If data is present and is not null it must be an object or an array');
} | php | {
"resource": ""
} |
q6299 | DocumentHydrator.processNoDataDocument | train | protected function processNoDataDocument($source): NoDataDocument
{
$document = new NoDataDocument();
$this->hydrateObject($document, $source);
return $document;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.