_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q261200 | Mondator.generateContainers | test | public function generateContainers()
{
$containers = array();
$containers['_global'] = new Container();
// global extensions
$globalExtensions = $this->getExtensions();
// configClasses
$configClasses = new \ArrayObject();
foreach ($this->getConfigClasses() as $class => $configClass) {
$configClasses[$class] = new \ArrayObject($configClass);
}
// classes extensions
$classesExtensions = new \ArrayObject();
$this->generateContainersClassesExtensions($globalExtensions, $classesExtensions, $configClasses);
// config class process
foreach ($classesExtensions as $class => $classExtensions) {
foreach ($classExtensions as $classExtension) {
$classExtension->configClassProcess($class, $configClasses);
}
}
// pre global process
foreach ($globalExtensions as $globalExtension) {
$globalExtension->preGlobalProcess($configClasses, $containers['_global']);
}
// class process
foreach ($classesExtensions as $class => $classExtensions) {
$containers[$class] = $container = new Container();
foreach ($classExtensions as $classExtension) {
$classExtension->classProcess($class, $configClasses, $container);
}
}
// post global process
foreach ($globalExtensions as $globalExtension) {
$globalExtension->postGlobalProcess($configClasses, $containers['_global']);
}
return $containers;
} | php | {
"resource": ""
} |
q261201 | Mondator.dumpContainers | test | public function dumpContainers(array $containers)
{
// directories
foreach ($containers as $container) {
foreach ($container->getDefinitions() as $name => $definition) {
$output = $definition->getOutput();
$dir = $output->getDir();
if (!file_exists($dir) && false === @mkdir($dir, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the %s directory (%s).', $name, $dir));
}
if (!is_writable($dir)) {
throw new \RuntimeException(sprintf('Unable to write in the %s directory (%s).', $name, $dir));
}
}
}
// output
foreach ($containers as $container) {
foreach ($container->getDefinitions() as $name => $definition) {
$output = $definition->getOutput($name);
$dir = $output->getDir();
$file = $dir.DIRECTORY_SEPARATOR.$definition->getClassName().'.php';
if (!file_exists($file) || $output->getOverride()) {
$dumper = new Dumper($definition);
$content = $dumper->dump();
$tmpFile = tempnam(dirname($file), basename($file));
if (false === @file_put_contents($tmpFile, $content) || !@rename($tmpFile, $file)) {
throw new \RuntimeException(sprintf('Failed to write the file "%s".', $file));
}
chmod($file, 0644);
}
}
}
} | php | {
"resource": ""
} |
q261202 | BoolSpec.it_should_return_inner_value | test | function it_should_return_inner_value()
{
$this->value()->shouldBeBool();
$this->value()->shouldBeEqualTo($this->init);
$this->get()->shouldBeBool();
$this->get()->shouldBeEqualTo($this->init);
} | php | {
"resource": ""
} |
q261203 | Client.setAddress | test | public function setAddress($address)
{
$this->address = \is_string($address) ? \explode(',', $address) : $address;
return $this;
} | php | {
"resource": ""
} |
q261204 | Client.notice | test | public function notice($method, array $params = [], array $headers = [])
{
$request = new JsonRequest($method, $params);
$request->headers()->add($headers);
try {
$this->execute($request);
} catch (\Exception $e) {
// Nothing
}
} | php | {
"resource": ""
} |
q261205 | Client.call | test | public function call($method, array $params = [], array $headers = [])
{
$request = new JsonRequest($method, $params, \uniqid(\gethostname().'.', true));
$request->headers()->add($headers);
try {
return $this->execute($request);
} catch (\Exception $e) {
return $this->createResponseFromException($e, $request);
}
} | php | {
"resource": ""
} |
q261206 | Client.createResponseFromException | test | protected function createResponseFromException(\Exception $e, JsonRequest $request)
{
$response = new JsonResponse();
$response->setId($request->getId());
$response->setErrorMessage($e->getMessage());
$response->setErrorCode($e->getCode());
return $response;
} | php | {
"resource": ""
} |
q261207 | Client.parserHttp | test | protected function parserHttp($http)
{
$response = [];
$json = \json_decode($http, true);
if (JSON_ERROR_NONE !== \json_last_error() || empty($http)) {
throw new Exceptions\InvalidResponseException('Invalid response from RPC server, must be valid json.');
}
/**
* Create new JsonResponse.
*
* @param mixed $json
*
* @return JsonResponse
*/
$createJsonResponse = function ($json) {
$id = null;
$result = null;
$error = [
'code' => null,
'message' => null,
'data' => null,
];
if (
\is_array($json)
& \array_key_exists('id', $json)
& (
\array_key_exists('result', $json)
|| \array_key_exists('error', $json)
)
) {
$id = $json['id'];
$result = \array_key_exists('result', $json) ? $json['result'] : null;
if (\array_key_exists('error', $json)) {
$error['code'] = \array_key_exists('code', $json['error']) ? $json['error']['code'] : null;
$error['message'] = \array_key_exists('message', $json['error']) ? $json['error']['message'] : null;
$error['data'] = \array_key_exists('data', $json['error']) ? $json['error']['data'] : null;
}
$response = new JsonResponse();
$response->setId($id);
$response->setResult($result);
$response->setErrorCode($error['code']);
$response->setErrorMessage($error['message']);
$response->setErrorData($error['data']);
return $response;
}
throw new Exceptions\InvalidResponseException('Invalid response format from RPC server.');
};
if (\array_keys($json) === \range(0, \count($json) - 1)) {
foreach ($json as $part) {
$response[] = $createJsonResponse($part);
}
} else {
$response = $createJsonResponse($json);
}
return $response;
} | php | {
"resource": ""
} |
q261208 | Performer.requestForActionPermission | test | public function requestForActionPermission($dontWait = null)
{
$sendSuccess = null;
if (!$this->requestSocket) {
$this->requestSocket = $this->context->getSocket(\ZMQ::SOCKET_REQ);
$this->requestSocket->connect($this->getSocketsParams()->getRequestPulsarRsSocketAddress());
}
$requestDto = new PreparingRequestDto();
if ($dontWait) {
try {
$this->requestSocket->send(serialize($requestDto));
$sendSuccess = true;
} catch (\Exception $e) {
$this->logger->debug("Possibly work PerformerImitator.");
}
$this->becomeTheSubscriberReplyDto = unserialize($this->requestSocket->recv(\ZMQ::MODE_DONTWAIT));
} else {
$this->requestSocket->send(serialize($requestDto));
$this->logger->debug("Performer send preparing request. Wait receive");
//->recv() block execution until data will received
$this->becomeTheSubscriberReplyDto = unserialize($this->requestSocket->recv());
if (!$this->becomeTheSubscriberReplyDto->isAllowToStartSubscription()) {
throw new PublisherPulsarException(PublisherPulsarExceptionsConstants::SUBSCRIPTION_IS_NOT_ALLOWED);
}
$this->logger->debug("Performer got allowing becomeTheSubscriberReply.");
}
return $sendSuccess;
} | php | {
"resource": ""
} |
q261209 | Performer.waitAllowingSubscriptionMessage | test | public function waitAllowingSubscriptionMessage()
{
if (!$this->subscriberSocket) {
$this->subscriberSocket = $this->context->getSocket(\ZMQ::SOCKET_SUB);
$this->subscriberSocket->connect($this->getSocketsParams()->getPublisherPulsarSocketAddress());
}
$this->subscriberSocket->setSockOpt(\ZMQ::SOCKOPT_SUBSCRIBE, "");
$this->logger->debug("Performer become subscriber.");
//use in Pulsar to divide termination of current subscribers and potential subscribers, if early termination occurred
$this->performerEarlyTerminated->setStandOnSubscription(true);
$this->pushReadyToGetSubscriptionMsg();
//->recv() block execution until data will received; all subscribers will continue execution synchronously
$this->logger->debug("Performer wait subscription msg.");
$this->publisherToSubscribersDto = unserialize($this->subscriberSocket->recv());
$this->logger->debug("Performer got subscription msg.");
if (!$this->publisherToSubscribersDto->isAllowAction()) {
throw new PublisherPulsarException(PublisherPulsarExceptionsConstants::ACTION_IS_NOT_ALLOWED);
}
return null;
} | php | {
"resource": ""
} |
q261210 | Performer.pushActionResultInfo | test | public function pushActionResultInfo(ActionResultingPushDto $resultingPushDto)
{
$this->subscriberSocket->setSockOpt(\ZMQ::SOCKOPT_UNSUBSCRIBE, "");
$this->performerEarlyTerminated->setStandOnSubscription(false);
$this->logger->debug("Performer was unsubscribed.");
$this->initOrCheckPushConnection();
$this->pushSocket->send(serialize($resultingPushDto));
$this->logger->debug("Performer send actionResulting msg.");
return null;
} | php | {
"resource": ""
} |
q261211 | BaseSecurePresenter.formatLayoutTemplateFiles | test | public function formatLayoutTemplateFiles()
{
$list = parent::formatLayoutTemplateFiles();
$layout = $this->layout ? $this->layout : 'layout';
$dir = $this->administrationTemplatesDir;
$list[] = "$dir/@$layout.latte";
return $list;
} | php | {
"resource": ""
} |
q261212 | ComplexType.toFile | test | public function toFile($file, $jsonOptions = 0)
{
if (is_dir(pathinfo($file, PATHINFO_DIRNAME)))
{
return (bool) file_put_contents($file, $this->toJson($this->getIntegerable($jsonOptions)));
}
return false;
} | php | {
"resource": ""
} |
q261213 | Str.dashed | test | public static function dashed($value)
{
if (isset(static::$dashedCache[$value]))
{
return static::$dashedCache[$value];
}
return static::$dashedCache[$value] = StaticStringy::dasherize($value);
} | php | {
"resource": ""
} |
q261214 | SliceableTrait.getSlice | test | protected function getSlice($start, $stop, $step)
{
$length = $this->length();
$step = (isset($step)) ? $step : 1;
if ($step === 0)
{
throw new InvalidArgumentException('Slice step cannot be 0');
}
if (isset($start))
{
$start = $this->adjustBoundary($length, $start, $step);
}
else
{
$start = ($step > 0) ? 0 : $length - 1;
}
if (isset($stop))
{
$stop = $this->adjustBoundary($length, $stop, $step);
}
else
{
$stop = ($step > 0) ? $length : -1;
}
// Return an empty string if the set of indices would be empty
if (($step > 0 && $start >= $stop) || ($step < 0 && $start <= $stop))
{
return new static('');
}
// Return the substring if step is 1
if ($step === 1)
{
return $this->cut($start, $stop - $start);
}
// Otherwise iterate over the slice indices
$str = '';
foreach ($this->getIndices($start, $stop, $step) as $index)
{
$str .= (isset($this[$index])) ? $this[$index] : '';
}
return new static($str);
} | php | {
"resource": ""
} |
q261215 | SliceableTrait.getIndices | test | protected function getIndices($start, $stop, $step)
{
$indices = [];
if ($step > 0)
{
for ($i = $start; $i < $stop; $i += $step)
{
$indices[] = $i;
}
}
else
{
for ($i = $start; $i > $stop; $i += $step)
{
$indices[] = $i;
}
}
return $indices;
} | php | {
"resource": ""
} |
q261216 | Channel.getOption | test | public function getOption($value)
{
if(is_array($value))
{
return $this->_getOptionFromArray($value);
}
elseif(preg_match($this->shortHandRegex, strtoupper($value)))
{
return '-channel ' . $value . ' ';
}
else
{
$msg = 'Invalid argument $value "' . $value . '", allowed values are ' . implode(', ',
$this->allowedOptions)
. ' as array (e.g.: ["Green", "Blue"]) or some of the characters R G B A O C M Y K without whitespaces and unique';
return $this->_optionValueException($msg);
}
} | php | {
"resource": ""
} |
q261217 | Channel._validateValuesArrayArgument | test | private function _validateValuesArrayArgument(array $values)
{
foreach($values as $value)
{
if(!in_array($value, $this->allowedOptions))
{
$msg = 'Invalid element in $value array: "' . $value . '", allowed values: ' . implode(', ',
$this->allowedOptions);
$this->_optionValueException($msg);
}
}
} | php | {
"resource": ""
} |
q261218 | Command._createOption | test | protected function _createOption($option, $value)
{
if(!class_exists($option))
{
throw new InvalidOptionValueException('Option class "' . $option . '" not found.');
}
$class = new $option();
return $this->_validateOptionInterface($class)->_validateOption($class)->getOption($value);
} | php | {
"resource": ""
} |
q261219 | Pulsar.declareReplyToReplyStackMessaging | test | protected function declareReplyToReplyStackMessaging()
{
$this->replyToReplyStack->on(EventsConstants::MESSAGE, function ($requestDto) {
if ($this->getRequestForStartFromReplyStack === false) {
$this->getRequestForStartFromReplyStack = true;
$startReplyToReplyStack = new PulsarToReplyStackReplyDto();
$startReplyToReplyStack->setSubscribersNumber($this->shouldBeSubscribersNumber);
$startReplyToReplyStack->setDtoToTransfer(new BecomeTheSubscriberReplyDto());
$this->replyToReplyStack->send(serialize($startReplyToReplyStack));
} else {
if ($this->replyStackReturnResult === false) {
$this->replyStackReturnResult = true;
/**
* @var ReplyStackToPulsarReturnResultRequestDto $requestDto
*/
$requestDto = unserialize($requestDto);
if (!($requestDto instanceof ReplyStackToPulsarReturnResultRequestDto)) {
throw new PublisherPulsarException("Unexpected result from ReplyStack.");
}
$this->considerMeAsSubscriber = $requestDto->getConsiderMeAsSubscriber();
$this->logger->debug("PULSAR RECEIVE REPLY STACK RESULT INFO.");
} else {
throw new PublisherPulsarException("Get replyStack result (info about subscribers) twice.");
}
}
});
$this->replyToReplyStack->on(EventsConstants::ERROR, function ($error) {
$this->logger->debug(LoggingExceptions::getExceptionString($error));
});
return null;
} | php | {
"resource": ""
} |
q261220 | Object.get | test | public function get($property, $default = null)
{
$property = $this->getStringable($property);
if ($this->has($property))
{
return $this->retrieveValue($property);
}
return $default;
} | php | {
"resource": ""
} |
q261221 | ContainerSpec.getMatchers | test | public function getMatchers()
{
return array(
'beInRange' => function($key, $match)
{
return in_array($key, $match);
},
'beArrayAndExactLengthOf' => function($array, $count)
{
return is_array($array) && $count === count($array);
}
);
} | php | {
"resource": ""
} |
q261222 | ImageMagick.compareImages | test | public function compareImages($expectedImage, $compareImage, $resultImageName, $resultImageDirectory)
{
$time = date('Ymd-His');
$diffResult = $this->createDiffGifOnDifferences($expectedImage, $compareImage,
$resultImageName . 'Diff' . $time, $resultImageDirectory);
$compareResult = $this->createComparisonImageOnDifferences($expectedImage, $compareImage,
$resultImageName . 'Compared' . $time,
$resultImageDirectory);
if($diffResult || $compareResult)
{
$gif = $resultImageName . 'Diff' . $time . '.gif';
$png = $resultImageName . 'Compared' . $time . '.gif';
return [$gif, $png];
}
return [];
} | php | {
"resource": ""
} |
q261223 | ImageMagick.createDiffGifOnDifferences | test | public function createDiffGifOnDifferences($expectedImage,
$compareImage,
$resultImageName,
$resultImageDirectory = '.')
{
if(!$this->compare->same($expectedImage, $compareImage))
{
$this->convert->createGifCommand([$expectedImage, $compareImage], $resultImageName, $resultImageDirectory);
return true;
}
return false;
} | php | {
"resource": ""
} |
q261224 | ImageMagick.createComparisonImageOnDifferences | test | public function createComparisonImageOnDifferences($actualImage,
$compareImage,
$resultImageName,
$resultImageDirectory = '.')
{
if(!$this->compare->same($compareImage, $actualImage))
{
$this->compare->createComparisonImage($compareImage, $actualImage, $resultImageName, $resultImageDirectory);
return true;
}
return false;
} | php | {
"resource": ""
} |
q261225 | Compare.same | test | public function same($expectedImage, $compareImage)
{
$metric = $this->_createOption(Metric::class, 'AE');
$cmd = 'compare ' . $metric . $expectedImage . ' ' . $compareImage . $this->redirectDefaultErrorResponse;
return (int)`$cmd` === 0;
}
/**
* Creates a comparison image.
*
* @param string $compareImage Expected image.
* @param string $actualImage Current image to compare.
* @param string $resultImageName Name of the resulting comparison image.
* @param string $resultImageDir (Optional) Path to directory of result images.
*
* @return mixed
* @throws \ImageMagick\Exceptions\InvalidOptionValueException
*/
public function createComparisonImage($compareImage,
$actualImage,
$resultImageName,
$resultImageDir = '.')
{
$compose = $this->_createOption(Compose::class, 'src');
$resultDirectory = rtrim($resultImageDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$cmd = 'compare ' . $compareImage . ' ' . $actualImage . ' ' . $compose . $resultDirectory
. $resultImageName . '.png';
return `$cmd`;
} | php | {
"resource": ""
} |
q261226 | Router.post | test | public function post($route, $callback)
{
$this->route(new Route($route, $callback), self::METHOD_POST);
} | php | {
"resource": ""
} |
q261227 | Router.route | test | public function route(Route $route, $http_method = self::METHOD_GET)
{
// Is this a valid HTTP method?
if (!in_array($http_method, array(
self::METHOD_HEAD,
self::METHOD_GET,
self::METHOD_POST,
self::METHOD_PUT,
self::METHOD_PATCH,
self::METHOD_DELETE
))) {
throw new \InvalidArgumentException("The method {$http_method} is invalid");
}
// Does this URL already exist in the routing table?
if (isset($this->routes[$http_method][$route->pattern()])) {
// Trigger a new error and exception if errors are on
throw new \LogicException("The URI {$route->url()} already exists in the routing table");
}
// Add the route to the routing table
$this->routes[$http_method][$route->pattern()] = $route;
} | php | {
"resource": ""
} |
q261228 | Router.match | test | public function match($url, $http_method = self::METHOD_GET)
{
// Make sure there is a trailing slash
$url = rtrim($url, '/') . '/';
foreach ($this->routes[$http_method] as $route) {
if (preg_match($route->pattern(), $url)) {
return $route;
}
}
return null;
} | php | {
"resource": ""
} |
q261229 | Router.run | test | public function run()
{
// If no routes have been added, then throw an exception
try {
if (empty($this->routes)) {
throw new \RuntimeException('No routes exist in the routing table. Add some');
}
}
catch (\Exception $e) {
$this->error($e);
return FALSE;
}
// Try and get a matching route for the current URL
$route = $this->match(
$this->request->getPathInfo(),
$this->request->getMethod()
);
// Call not found handler if no match was found
if ($route === null) {
$this->not_found();
return FALSE;
}
// Set current route
$this->current_route = $route;
// Get parameters from request
$params = $this->parse_parameters($route);
// Try to execute callback for route, if it fails, catch the exception and generate a HTTP 500 error
try {
$this->current_http_status = \Symfony\Component\HttpFoundation\Response::HTTP_OK;
// Set response content
$this->response->setContent($route->execute($params));
// Send response
$this->response->send();
return TRUE;
}
catch (\Exception $e) {
$this->error($e);
return FALSE;
}
} | php | {
"resource": ""
} |
q261230 | Router.redirect | test | public function redirect($url)
{
// If no URL is given, throw exception
try {
if (empty($url)) {
throw new \InvalidArgumentException('No URL given');
}
}
catch (\Exception $e) {
$this->error($e);
return FALSE;
}
// Set redirect status codes and location
$this->current_http_status = \Symfony\Component\HttpFoundation\Response::HTTP_FOUND;
$this->response->setStatusCode($this->current_http_status);
$this->response->headers->set('Location', $url);
return TRUE;
} | php | {
"resource": ""
} |
q261231 | Router.parse_parameters | test | protected function parse_parameters(Route $route)
{
// Get all parameter matches from URL for this route
$request_url = rtrim($this->request->getPathInfo(), '/') . '/';
preg_match($route->pattern(), "{$request_url}", $matches);
$params = array();
// Retrieve any matches
foreach ($matches as $key => $value) {
if (is_string($key)) {
$params[] = $value;
}
}
return $params;
} | php | {
"resource": ""
} |
q261232 | ListRoute.date | test | protected function date($file)
{
$file_contents = $this->sonic->app['filesystem']->parse($file['path']);
if (isset($file_contents['meta']['date']) === FALSE) {
return NULL;
}
return new \DateTime($file_contents['meta']['date']);
} | php | {
"resource": ""
} |
q261233 | MagicPresenter.handleSaveImage | test | public function handleSaveImage()
{
if ($this->mainManager instanceof MagicManager
&& $this->mainManager->isGallery()
) {
$folder = $this->mainManager->getGalleryFolder();
} else {
$this->error();
}
if ($folder == '') {
$folder = 'misc';
}
$file = $this->httpRequest->getFile('Filedata');
if ($file && $file->isOk() && $this->detailObject) {
// Save ...
$year = date('Y');
$month = date('m');
$namespace = "{$folder}/{$year}/{$month}";
$this->imageStorage->setNamespace($namespace);
$image = $this->imageStorage->save($file->getContents(), $file->getName());
$filename = pathinfo($image->getFile(), PATHINFO_BASENAME);
$size = $image->getSize();
// Prepare thumbnail
$this->imgPipe->setNamespace($namespace);
$this->imgPipe->request($filename, '100x100', 'exact');
// Save to database
$this->mainManager->addGalleryImage($filename, $namespace, $size->getWidth(), $size->getHeight(),
$file->getContentType(), $this->detailObject->id);
$response = [
'status' => '1',
'height' => $size->getHeight(),
'width' => $size->getWidth(),
'mime' => $file->getContentType(),
];
} else {
$response = [
'status' => '0',
'error' => 'Error while uploading file',
'code' => 500,
];
}
$this->sendJson($response);
} | php | {
"resource": ""
} |
q261234 | HttpRequest.get | test | public function get($strPath, array $arrOptions = [])
{
$request = wp_remote_get($this->build_uri($strPath), array_merge(
self::DEFAULT_OPTIONS,
$arrOptions, [
'headers' => $this->arrHeaders
])
);
return new HttpResponse($request);
} | php | {
"resource": ""
} |
q261235 | HttpRequest.post | test | public function post($strPath, array $arrOptions = [])
{
$request = wp_remote_post($this->build_uri($strPath), array_merge(
self::DEFAULT_OPTIONS,
$arrOptions, [
'headers' => $this->arrHeaders
])
);
return new HttpResponse($request);
} | php | {
"resource": ""
} |
q261236 | HttpRequest.set_auth | test | public function set_auth()
{
$date = date("Y-m-d\TH:i:s.000O");
$this->arrHeaders['X-cXense-Authentication'] = sprintf(
'username=%s date=%s hmac-sha256-hex=%s',
WpCxense::instance()->settings->getApiUser(),
$date,
hash_hmac("sha256", $date, WpCxense::instance()->settings->getApiKey())
);
return $this;
} | php | {
"resource": ""
} |
q261237 | Helper.config | test | public function config($option)
{
return isset($this->app['settings'][$option]) === TRUE
? $this->app['settings'][$option]
: NULL;
} | php | {
"resource": ""
} |
q261238 | Helper.validate_config | test | public function validate_config($config)
{
$message = '';
while ($message === '') {
if (!is_dir($this->app['ROOT_DIR'] . $config['sonic.content_dir'])) {
$message = 'Content directory does not exist';
break;
}
if (!is_dir($this->app['ROOT_DIR'] . $config['sonic.plugins_dir'])) {
$message = 'Plugins directory does not exist';
break;
}
if (!is_dir($this->app['ROOT_DIR'] . $config['sonic.templates_dir'])) {
$message = 'Templates directory does not exist';
break;
}
if (
!is_file("{$config['sonic.templates_dir']}/{$config['sonic.default_template']}")
) {
$message = 'No default template exists';
break;
}
if ($config['sonic.environment'] !== 'dev') {
preg_match('#^(https?://)?([\da-z\.-]+)\.([a-z\.]{2,6})([/\w \.-]*)*/+$#', $config['site.site_root']) === 0
? $message = 'Site root is invalid. Should be like http://www.example.com/'
: $message = '';
}
break;
}
if ($message === '') {
return TRUE;
}
else {
throw new \InvalidArgumentException($message);
}
} | php | {
"resource": ""
} |
q261239 | Helper.get_excerpt | test | public static function get_excerpt($text, $br_limit = 3)
{
if (substr_count($text, PHP_EOL) > $br_limit) {
$excerpt = explode(PHP_EOL, $text, ++$br_limit);
array_pop($excerpt);
return implode(' ', $excerpt);
}
return $text;
} | php | {
"resource": ""
} |
q261240 | Helper.handle_errors | test | public static function handle_errors($err_no, $err_str = '', $err_file = '', $err_line = '')
{
if (!($err_no & error_reporting())) {
return;
}
throw new \ErrorException($err_str, $err_no, 0, $err_file, $err_line);
} | php | {
"resource": ""
} |
q261241 | Helper.dot_extensions | test | private function dot_extensions()
{
$extensions = $this->app['settings']['sonic.content_ext'];
foreach ($extensions as $extension) {
$dotted_extensions[] = '.' . $extension;
}
return $dotted_extensions;
} | php | {
"resource": ""
} |
q261242 | WidgetDocumentQuery.validateWidgetId | test | private function validateWidgetId(?string $widgetId)
{
if (!isset($widgetId) && current_user_can('administrator')) {
throw new WidgetMissingId('Missing request "widgetId" key!');
}
$this->arrPayload['widgetId'] = $widgetId;
} | php | {
"resource": ""
} |
q261243 | WidgetDocumentQuery.setCxenseUserId | test | public function setCxenseUserId()
{
if (!isset($_COOKIE['cX_P'])) {
$this->cxenseUserId = '';
return;
}
$this->cxenseUserId = $_COOKIE['cX_P'];
$this->arrPayload['user']= ['ids' => ['usi' => $this->cxenseUserId]];
} | php | {
"resource": ""
} |
q261244 | WidgetDocumentQuery.get | test | public function get()
{
$result = $this->getDocuments();
$objDocuments = isset($result->items) ? $result->items : [];
return [
'totalCount' => count($objDocuments),
'matches' => $this->parseDocuments($objDocuments)
];
} | php | {
"resource": ""
} |
q261245 | String.append | test | public function append($string, $delimiter = '')
{
if ($this->isValidStringAndDelimiter($string, $delimiter))
{
return new static($this->string.$this->retrieveValue($delimiter).$this->retrieveValue($string));
}
return $this;
} | php | {
"resource": ""
} |
q261246 | String.prepend | test | public function prepend($string, $delimiter = '')
{
if ($this->isValidStringAndDelimiter($string, $delimiter))
{
return new static($this->retrieveValue($string).$this->retrieveValue($delimiter).$this->string);
}
return $this;
} | php | {
"resource": ""
} |
q261247 | String.is | test | public function is($pattern)
{
return (bool) Str::matches($this->retrieveValue($pattern), $this->string);
} | php | {
"resource": ""
} |
q261248 | String.limitWords | test | public function limitWords($limit, $end = '...')
{
return new static(Str::words($this->string, $this->getIntegerable($limit), $this->retrieveValue($end)));
} | php | {
"resource": ""
} |
q261249 | String.uuid | test | public function uuid()
{
return new static(sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
));
} | php | {
"resource": ""
} |
q261250 | String.join | test | public function join($glue, $array)
{
if ($this->isArrayable($array))
{
$this->string = implode($this->retrieveValue($glue), $this->getArrayable($array));
return $this;
}
throw new InvalidArgumentException('Argument 2 should be array, Container or instance of Arrayable');
} | php | {
"resource": ""
} |
q261251 | String.toEntities | test | public function toEntities($flags = ENT_QUOTES, $encoding = 'UTF-8')
{
return new static(htmlentities($this->string, $flags, $this->retrieveValue($encoding)));
} | php | {
"resource": ""
} |
q261252 | String.cut | test | public function cut($offset, $length = null, $encoding = 'UTF-8')
{
return new static(
mb_substr(
$this->string,
$this->getIntegerable($offset),
$this->getIntegerable($length),
$this->retrieveValue($encoding)
)
);
} | php | {
"resource": ""
} |
q261253 | String.limit | test | public function limit($limit = 100, $end = '...')
{
return new static(
Str::limit($this->string, $this->getIntegerable($limit), $this->retrieveValue($end))
);
} | php | {
"resource": ""
} |
q261254 | String.limitSafe | test | public function limitSafe($limit = 100, $end = '...')
{
return new static(
StaticStringy::safeTruncate($this->string, $this->getIntegerable($limit)).$this->retrieveValue($end)
);
} | php | {
"resource": ""
} |
q261255 | String.toVars | test | public function toVars()
{
$vars = [];
return mb_parse_str($this->string, $vars) && ! is_null($vars) ? new Container($vars) : new Container;
} | php | {
"resource": ""
} |
q261256 | String.encrypt | test | public function encrypt($key, $expires)
{
$payload = [
'exp' => $this->getIntegerable($expires),
'string' => $this->string
];
return JWT::encode($payload, $this->getStringable($key));
} | php | {
"resource": ""
} |
q261257 | String.fromEncrypted | test | public function fromEncrypted($encrypted, $key)
{
$encrypted = $this->retrieveValue($encrypted);
$key = $this->retrieveValue($key);
if ($this->isEncryptedString($encrypted, $key))
{
$data = JWT::decode($encrypted, $key);
return $this->initialize($data->string);
}
throw new BadMethodCallException('Expected encrypted String, got: ' . $encrypted);
} | php | {
"resource": ""
} |
q261258 | String.toContainer | test | public function toContainer()
{
$value = $this->value();
if ( ! $this->isFile() || ! $this->isJson() || ! $this->isSerialized())
{
$value = [$value];
}
return new Container($value);
} | php | {
"resource": ""
} |
q261259 | Api.generateParserFromGrammar | test | static function generateParserFromGrammar(
string $grammarFilePath,
string $parserName="MyParser",
string $namespace="",
Output $output=null,
string $pathToHeaderComment="")
{
$parser = new MetaGrammarParser();
$ast = !empty($grammarFilePath) ?
$parser->parseFile($grammarFilePath) :
$parser->parseStdin();
if ($ast !== false) {
$generator = new CodeGenerator($parserName, $namespace);
$generator->setHeaderCommentFile($pathToHeaderComment);
$generator->generate($ast, $output);
return [true, ""];
} else {
return [false, $parser->error()];
}
} | php | {
"resource": ""
} |
q261260 | DocumentSearch.set_settings | test | public function set_settings()
{
if ($strPrefix = WpCxense::instance()->settings->getOrganisationPrefix()) {
$this->arrFields['organisation'] = array_map(function ($strValue) use ($strPrefix) {
return $strPrefix . '-' . $strValue;
}, $this->arrFields['organisation']);
}
return $this;
} | php | {
"resource": ""
} |
q261261 | DocumentSearch.get_documents | test | public function get_documents()
{
$this->validate_query_key();
$objDocuments = $this
->set_per_page()
->set_page()
->set_facets()
->set_filter()
->set_exclude_filter()
->set_sorting()
->set_spellcheck()
->set_highlights()
->set_result_fields()
->get();
$objDocuments->matches = $this->parse_documents($objDocuments->matches);
return $objDocuments;
} | php | {
"resource": ""
} |
q261262 | DocumentSearch.set_per_page | test | private function set_per_page($intCount = 10)
{
$this->arrPayload['count'] = $intCount;
if (isset($this->arrSearch['count'])) {
$this->arrPayload['count'] = $this->arrSearch['count'];
}
return $this;
} | php | {
"resource": ""
} |
q261263 | DocumentSearch.set_page | test | private function set_page($intPage = 1)
{
if (!isset($this->arrPayload['count'])) {
throw new DocumentSearchMissingCount('\DocumentSearch::setPerPage() is required before \DocumentSearch::setPage()');
}
// get the page
if (isset($this->arrSearch['page'])) {
$intPage = $this->arrSearch['page'];
}
// set the starting point
$this->arrPayload['start'] = $this->arrPayload['count'] * ($intPage - 1);
return $this;
} | php | {
"resource": ""
} |
q261264 | RetrievableTrait.getNumberable | test | public function getNumberable($value, $default = null)
{
switch(true)
{
case is_int($value):
case is_float($value):
return $value;
case is_numeric($value) && strpos($value, '.'):
return (float) $value;
case is_numeric($value):
case is_bool($value):
return (int) $value;
case $value instanceof IntegerContract:
case $value instanceof FloatContract:
return $value->value();
case $value instanceof BooleanContract:
return $value->toInt()->value();
case $value instanceof StringContract:
return (int) $value->value();
default:
return value($default);
}
} | php | {
"resource": ""
} |
q261265 | RetrievableTrait.getSearchable | test | public function getSearchable($value, $default = [])
{
if ($this->isArrayable($value))
{
return $this->getArrayable($value, $default);
}
elseif ($this->isStringable($value))
{
return $this->getStringable($value, $default);
}
elseif ($value instanceof Closure)
{
return $value;
}
return value($default);
} | php | {
"resource": ""
} |
q261266 | RetrievableTrait.boolFromString | test | protected function boolFromString($value)
{
$grammar = $this->getGrammar();
$value = $this->getStringable($value);
if (isset($grammar[$value])) return $grammar[$value];
return false;
} | php | {
"resource": ""
} |
q261267 | RetrievableTrait.getGrammar | test | protected function getGrammar()
{
return [
'true' => true, 'false' => false,
'on' => true, 'off' => false,
'yes' => true, 'no' => false,
'y' => true, 'n' => false,
'+' => true, '-' => false
];
} | php | {
"resource": ""
} |
q261268 | Convert.createGifCommand | test | public function createGifCommand(array $sourcesImages, $resultImageName, $resultDirectory, $delay = 50, $loop = 0)
{
$cmd = $this->createGifCommandCmd($sourcesImages, $resultImageName, $resultDirectory, $delay, $loop);
return `$cmd`;
} | php | {
"resource": ""
} |
q261269 | Convert.createGifCommandCmd | test | public function createGifCommandCmd(array $sourcesImages,
$resultImageName,
$resultDirectory,
$delay = 50,
$loop = 0)
{
$delayOption = $this->_createOption(Delay::class, $delay);
$loopOption = $this->_createOption(Loop::class, $loop);
return 'convert ' . $delayOption . implode(' ', $sourcesImages) . ' ' . $loopOption . $resultDirectory
. DIRECTORY_SEPARATOR . $resultImageName . '.gif';
} | php | {
"resource": ""
} |
q261270 | TokenStream.lookupMany | test | public function lookupMany($n = 1)
{
if ($n > $this->bufSize) {
$this->bufSize = $n;
}
$this->fillBuffer();
$tokens = [];
$size = min($n, count($this->tokens));
for ($i=0; $i<$size; $i++) {
$tokens[] = $this->tokens[$i];
}
return $tokens;
} | php | {
"resource": ""
} |
q261271 | Number.format | test | public function format($decimals = 2, $decimalDelimiter = '.', $thousandDelimiter = ' ')
{
return new String(
number_format(
(float) $this->value,
$this->getIntegerable($decimals),
$this->getStringable($decimalDelimiter),
$this->getStringable($thousandDelimiter)
)
);
} | php | {
"resource": ""
} |
q261272 | Definition.hasPropertyByName | test | public function hasPropertyByName($name)
{
foreach ($this->properties as $property) {
if ($property->getName() == $name) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q261273 | Definition.getPropertyByName | test | public function getPropertyByName($name)
{
foreach ($this->properties as $property) {
if ($property->getName() == $name) {
return $property;
}
}
throw new \InvalidArgumentException(sprintf('The property "%s" does not exists.', $name));
} | php | {
"resource": ""
} |
q261274 | Definition.removePropertyByName | test | public function removePropertyByName($name)
{
foreach ($this->properties as $key => $property) {
if ($property->getName() == $name) {
unset($this->properties[$key]);
return;
}
}
throw new \InvalidArgumentException(sprintf('The property "%s" does not exists.', $name));
} | php | {
"resource": ""
} |
q261275 | Definition.hasMethodByName | test | public function hasMethodByName($name)
{
foreach ($this->methods as $method) {
if ($method->getName() == $name) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q261276 | Definition.getMethodByName | test | public function getMethodByName($name)
{
foreach ($this->methods as $method) {
if ($method->getName() == $name) {
return $method;
}
}
throw new \InvalidArgumentException(sprintf('The method "%s" does not exists.', $name));
} | php | {
"resource": ""
} |
q261277 | Definition.removeMethodByName | test | public function removeMethodByName($name)
{
foreach ($this->methods as $key => $method) {
if ($method->getName() == $name) {
unset($this->methods[$key]);
return;
}
}
throw new \InvalidArgumentException(sprintf('The method "%s" does not exists.', $name));
} | php | {
"resource": ""
} |
q261278 | Markdown.parse_meta | test | protected function parse_meta($file)
{
// Grab meta section between '/* ... */' in the content file
preg_match_all('#/\*(.*?)\*/#s', $file, $meta);
// Retrieve individual meta fields
preg_match_all('#^[\t]?(\w*):(.*)$#mi', $meta[1][0], $match);
for ($i=0; $i < count($match[1]); $i++) {
$result[strtolower($match[1][$i])] = trim(htmlentities($match[2][$i]));
}
return $result;
} | php | {
"resource": ""
} |
q261279 | Sonic.run_hooks | test | public function run_hooks($hook_id, $args = array())
{
// If plugins are disabled, do not run
if ($this->app['settings']['sonic.plugins_enabled'] === FALSE) {
return FALSE;
}
// Run hooks associated with that event
foreach ($this->app['plugins'] as $plugin_id => $plugin) {
if (is_callable(array($plugin, $hook_id))) {
call_user_func_array(array($plugin, $hook_id), $args);
}
}
return TRUE;
} | php | {
"resource": ""
} |
q261280 | Sonic.load_plugins | test | protected function load_plugins()
{
if ($this->app['settings']['sonic.plugins_enabled'] === TRUE) {
// Load plugins from 'plugins' folder
$file_list = $this->app['filesystem']->listContents($this->app['settings']['sonic.plugins_dir']);
$plugin_files = array_filter($file_list, function ($file) {
return preg_match('#^([A-Z]+\w+)Plugin.php$#', $file['basename']) === 1
? TRUE
: FALSE;
});
foreach ($plugin_files as $plugin_file) {
$plugin = $this->app['filesystem']->include($plugin_file['path']);
$plugin->set_app($this);
$plugins[$plugin_file['filename']] = $plugin;
}
$this->app['plugins'] = $plugins;
}
} | php | {
"resource": ""
} |
q261281 | Sonic.setup_router | test | protected function setup_router()
{
// Only because you can't use $this->app in the callback
$app = $this->app;
$file_list = $app['filesystem']->listContents($app['settings']['sonic.content_dir'], true);
$files = array_filter($file_list, function ($file) {
return isset($file['extension']) && $file['extension'] === 'md'
? TRUE
: FALSE;
});
// Add each as a route
foreach ($files as $file) {
// Get filename without extension
$file_path = str_replace(
$app['settings']['sonic.content_dir'],
'',
$file['dirname'] . '/' . $file['filename']
);
$route = '/' . trim(str_replace('/index', '/', $file_path), '/');
$this->app['router']->route(new Routes\DefaultRoute($route));
}
} | php | {
"resource": ""
} |
q261282 | Container.get | test | public function get($key, $default = null)
{
return Arr::get($this->items, $this->getKey($key), $default);
} | php | {
"resource": ""
} |
q261283 | Container.set | test | public function set($key, $value)
{
Arr::set($this->items, $this->getKey($key), $value);
return $this;
} | php | {
"resource": ""
} |
q261284 | Container.pushToKey | test | public function pushToKey($key, $value)
{
if ( ! $this->has($key))
{
$this->set($key, []);
}
$keyValue = $this->get($key);
if ($keyValue instanceof static)
{
$keyValue->push($value);
}
elseif (is_array($keyValue))
{
$keyValue[] = $value;
}
else
{
$this->set($key, [])->pushToKey($key, $keyValue);
return $this;
}
$this->set($key, $keyValue);
return $this;
} | php | {
"resource": ""
} |
q261285 | Container.search | test | public function search($value, $strict = false)
{
return Arr::search($this->items, $this->getSearchable($value, $value), $this->getBoolable($strict));
} | php | {
"resource": ""
} |
q261286 | Container.keysByField | test | public function keysByField($keyBy)
{
$byField = [];
$keyBy = $this->getStringable($keyBy);
foreach ($this->items as $item)
{
$key = _data_get($item, $keyBy);
$byField[$key] = $item;
}
return new static($byField);
} | php | {
"resource": ""
} |
q261287 | Container.unique | test | public function unique($recursive = false)
{
if ($this->getBoolable($recursive))
{
return new static($this->uniqueRecursive($this->items));
}
return new static(array_unique($this->items));
} | php | {
"resource": ""
} |
q261288 | Container.numericKeys | test | public function numericKeys()
{
$keys = new static;
foreach ($this->items as $key => $value)
{
if (is_numeric($key)) $keys->set($key, $value);
}
return $keys;
} | php | {
"resource": ""
} |
q261289 | Container.join | test | public function join($glue = '')
{
foreach ($copy = Arr::flatten($this->items) as $key => $object)
{
$copy[$key] = $this->getStringable($object);
}
return string(implode($this->getStringable($glue, ''), $copy));
} | php | {
"resource": ""
} |
q261290 | Container.joinByKey | test | public function joinByKey($key, $glue = null)
{
return string(implode($glue, $this->lists($this->getKey($key))->all()));
} | php | {
"resource": ""
} |
q261291 | Container.lists | test | public function lists($valueByKey, $key = null)
{
return new static(Arr::pluck($this->items, $this->getKey($valueByKey), $this->getKey($key)));
} | php | {
"resource": ""
} |
q261292 | Container.chunk | test | public function chunk($size = 2, $preserveKeys = false)
{
$size = $this->getIntegerable($size);
if ( ! is_integer($size) || $size > $this->length())
{
throw new BadLengthException('Chunk size is larger than container length');
}
$chunks = new static;
foreach (array_chunk($this->items, $size, $this->getBoolable($preserveKeys)) as $value)
{
$chunks->push(new static($value));
}
return $chunks;
} | php | {
"resource": ""
} |
q261293 | Container.filter | test | public function filter(callable $function, $recursive = false)
{
if ( ! $this->getBoolable($recursive))
{
return new static(array_filter($this->items, $function));
}
return new static($this->filterRecursive($function, $this->items));
} | php | {
"resource": ""
} |
q261294 | Container.walk | test | public function walk(callable $callback, $recursive = false, $userdata = null)
{
$function = $this->getBoolable($recursive) ? 'array_walk_recursive' : 'array_walk';
$function($this->items, $callback, $userdata);
return $this;
} | php | {
"resource": ""
} |
q261295 | Container.merge | test | public function merge($items)
{
if ( ! $this->isArrayable($items))
{
throw new BadMethodCallException('Argument 1 must be array, Container or implement Arrayable interface');
}
return new static(array_merge($this->items, $this->retrieveValue($items)));
} | php | {
"resource": ""
} |
q261296 | Container.mergeWithKey | test | public function mergeWithKey($items, $key, $default = null)
{
$key = $this->getKey($key);
if ( ! $this->has($key)) throw new InvalidArgumentException('Key: '.$key.' not exists');
$get = $this->get($key, $default);
$value = array_merge($get, $this->retrieveValue($items));
return $this->copy()->set($key, $value);
} | php | {
"resource": ""
} |
q261297 | Container.increase | test | public function increase($increaseSize = 1, $value = null)
{
$this->items = array_pad($this->items, $this->length() + $this->getIntegerable($increaseSize), $value);
return $this;
} | php | {
"resource": ""
} |
q261298 | Container.randomKey | test | public function randomKey($quantity = 1)
{
$quantity = $this->getIntegerable($quantity);
if ($this->isNotEmpty() && $this->length() >= $quantity && $quantity > 0)
{
$random = array_rand($this->items, $quantity);
return is_array($random) ? new static($random) : $random;
}
throw new BadMethodCallException("1 Argument should be between 1 and the number of elements in the Container, got: {$quantity}");
} | php | {
"resource": ""
} |
q261299 | Container.random | test | public function random($quantity = 1)
{
$quantity = $this->getIntegerable($quantity);
$result = new static;
while($quantity--)
{
$result->push($this->items[$this->randomKey()]);
}
return $result->length() === 1 ? $result->first() : $result;
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.