_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q262200 | FormattedResponder.formatter | test | protected function formatter(ServerRequestInterface $request)
{
$accept = $request->getHeaderLine('Accept');
$priorities = $this->priorities();
if (!empty($accept)) {
$preferred = $this->negotiator->getBest($accept, array_keys($priorities));
}
if (!empty($preferred)) {
$formatter = $priorities[$preferred->getValue()];
} else {
$formatter = array_shift($priorities);
}
return $this->resolve($formatter);
} | php | {
"resource": ""
} |
q262201 | FormattedResponder.format | test | protected function format(
ServerRequestInterface $request,
ResponseInterface $response,
PayloadInterface $payload
) {
$formatter = $this->formatter($request);
$response = $response->withHeader('Content-Type', $formatter->type());
// Overwrite the body instead of making a copy and dealing with the stream.
$response->getBody()->write($formatter->body($payload));
return $response;
} | php | {
"resource": ""
} |
q262202 | EnvConfiguration.detectEnvFile | test | private function detectEnvFile()
{
$env = DIRECTORY_SEPARATOR . '.env';
$dir = dirname(dirname(__DIR__));
do {
if (is_file($dir . $env)) {
return $dir . $env;
}
$dir = dirname($dir);
} while (is_readable($dir) && dirname($dir) !== $dir);
throw EnvException::detectionFailed();
} | php | {
"resource": ""
} |
q262203 | ExceptionHandler.type | test | private function type(ServerRequestInterface $request)
{
$accept = $request->getHeaderLine('Accept');
$priorities = $this->preferences->toArray();
if (!empty($accept)) {
$preferred = $this->negotiator->getBest($accept, array_keys($priorities));
}
if (!empty($preferred)) {
return $preferred->getValue();
}
return key($priorities);
} | php | {
"resource": ""
} |
q262204 | Application.build | test | public static function build(
Injector $injector = null,
ConfigurationSet $configuration = null,
MiddlewareSet $middleware = null
) {
return new static($injector, $configuration, $middleware);
} | php | {
"resource": ""
} |
q262205 | Application.run | test | public function run($runner = Relay::class)
{
$this->configuration->apply($this->injector);
return $this->injector
->share($this->middleware)
->prepare(Directory::class, $this->routing)
->execute($runner);
} | php | {
"resource": ""
} |
q262206 | ActionHandler.handle | test | private function handle(
Action $action,
ServerRequestInterface $request,
ResponseInterface $response
) {
$domain = $this->resolve($action->getDomain());
$input = $this->resolve($action->getInput());
$responder = $this->resolve($action->getResponder());
$payload = $this->payload($domain, $input, $request);
$response = $this->response($responder, $request, $response, $payload);
return $response;
} | php | {
"resource": ""
} |
q262207 | ActionHandler.payload | test | private function payload(
DomainInterface $domain,
InputInterface $input,
ServerRequestInterface $request
) {
return $domain($input($request));
} | php | {
"resource": ""
} |
q262208 | ActionHandler.response | test | private function response(
ResponderInterface $responder,
ServerRequestInterface $request,
ResponseInterface $response,
PayloadInterface $payload
) {
return $responder($request, $response, $payload);
} | php | {
"resource": ""
} |
q262209 | StatusResponder.status | test | private function status(
ResponseInterface $response,
PayloadInterface $payload
) {
$status = $payload->getStatus();
$code = $this->http_status->getStatusCode($status);
return $response->withStatus($code);
} | php | {
"resource": ""
} |
q262210 | TranslatorService.getCommandFromResource | test | public function getCommandFromResource($resource, $action, $relation = null)
{
$namespace = Config::get('api.app_namespace');
$mapping = Config::get('api.mapping');
// If the mapping does not exist, we consider this as a 404 error
if (!isset($mapping[$resource])) {
throw new NotFoundHttpException('The resource [' . $resource . '] is not mapped to any Model.');
}
$allowedActions = ['index', 'store', 'show', 'update', 'destroy'];
if (!in_array($action, $allowedActions)) {
throw new InvalidArgumentException('[' . $action . '] is not a valid action.');
}
// If we have a $relation parameter, then we generate a command based on it
if ($relation) {
if (!isset($mapping[$relation])) {
throw new NotFoundHttpException('The resource [' . $resource . '] is not mapped to any Model.');
}
$command = implode('\\', [
$namespace,
'Commands',
$mapping[$resource] . 'Command',
ucfirst($mapping[$relation]) . ucfirst($action) . 'Command'
]);
} else {
$command = implode('\\', [
$namespace,
'Commands',
$mapping[$resource] . 'Command',
ucfirst($action) . 'Command'
]);
}
// If no custom command is found, then we use one of the default ones
if (!class_exists($command)) {
if ($relation) {
$command = implode('\\', [
'Osedea',
'LaravelRest',
'Commands',
'DefaultCommand',
'Relation' . ucfirst($action) . 'Command'
]);
} else {
$command = implode('\\', [
'Osedea',
'LaravelRest',
'Commands',
'DefaultCommand',
ucfirst($action) . 'Command'
]);
}
}
if (!class_exists($command)) {
throw new NotFoundHttpException('There is no default command for this action and resource.');
}
return $command;
} | php | {
"resource": ""
} |
q262211 | Controller.runBeforeCommands | test | protected function runBeforeCommands($command)
{
$beforeCommands = $command::beforeCommands();
if (!is_array($beforeCommands) && strlen(trim($beforeCommands)) > 0) {
$beforeCommands = [$beforeCommands];
}
$this->dispatcher->pipeThrough($beforeCommands);
} | php | {
"resource": ""
} |
q262212 | Command.getPerPageFromModelClass | test | protected function getPerPageFromModelClass($modelClass) {
// We need this empty model to grab perPage and perPageMax parameters
$model = new $modelClass;
// If Model::$perPage equals 0, then pagination is disabled
if ($model->getPerPage() == 0) {
return $modelClass::all();
}
// The number of items per page can be overriden as a query parameter
$perPage = Request::input('perPage', $model->getPerPage());
// We make sure the $perPage parameter is not higher than the maximum for this model
if ($perPage > $model->getPerPageMax()) {
$perPage = $model->getPerPageMax();
}
return $perPage;
} | php | {
"resource": ""
} |
q262213 | Command.addWhereStatements | test | protected function addWhereStatements($query, $class)
{
$params = Request::all();
foreach ($params as $key => $value) {
if (!in_array($key, $this->keywordParams) && !in_array($key, $class::$filterable)) {
throw new InvalidFilterException;
}
if (!in_array($key, $this->keywordParams)) {
$query->where($key, '=', $value);
}
}
return $query;
} | php | {
"resource": ""
} |
q262214 | LaravelRestServiceProvider.boot | test | public function boot()
{
$this->publishes([
implode(DIRECTORY_SEPARATOR, [__DIR__, 'config', 'api.php']) => config_path('api.php')
]);
$this->setupRoutes($this->app->router);
} | php | {
"resource": ""
} |
q262215 | Route.allow | test | public function allow($methods = [])
{
$methods = $methods ? (array) $methods : [];
$methods = array_map('strtoupper', $methods);
$this->_methods = array_fill_keys($methods, true) + $this->_methods;
return $this;
} | php | {
"resource": ""
} |
q262216 | Route.pattern | test | public function pattern($pattern = null)
{
if (!func_num_args()) {
return $this->_pattern;
}
$this->_token = null;
$this->_regex = null;
$this->_variables = null;
if (!$pattern || $pattern[0] !== '[') {
$pattern = '/' . trim($pattern, '/');
}
$this->_pattern = $this->_prefix . $pattern;
return $this;
} | php | {
"resource": ""
} |
q262217 | Route.token | test | public function token()
{
if ($this->_token === null) {
$parser = $this->_classes['parser'];
$this->_token = [];
$this->_regex = null;
$this->_variables = null;
$this->_token = $parser::tokenize($this->_pattern, '/');
}
return $this->_token;
} | php | {
"resource": ""
} |
q262218 | Route.regex | test | public function regex()
{
if ($this->_regex !== null) {
return $this->_regex;
}
$this->_compile();
return $this->_regex;
} | php | {
"resource": ""
} |
q262219 | Route.variables | test | public function variables()
{
if ($this->_variables !== null) {
return $this->_variables;
}
$this->_compile();
return $this->_variables;
} | php | {
"resource": ""
} |
q262220 | Route.match | test | public function match($request, &$variables = null, &$hostVariables = null)
{
$hostVariables = [];
if (($host = $this->host()) && !$host->match($request, $hostVariables)) {
return false;
}
$path = isset($request['path']) ? $request['path'] : '';
$method = isset($request['method']) ? $request['method'] : '*';
if (!isset($this->_methods['*']) && $method !== '*' && !isset($this->_methods[$method])) {
if ($method !== 'HEAD' && !isset($this->_methods['GET'])) {
return false;
}
}
$path = '/' . trim($path, '/');
if (!preg_match('~^' . $this->regex() . '$~', $path, $matches)) {
return false;
}
$variables = $this->_buildVariables($matches);
$this->params = $hostVariables + $variables;
return true;
} | php | {
"resource": ""
} |
q262221 | Route._buildVariables | test | protected function _buildVariables($values)
{
$variables = [];
$parser = $this->_classes['parser'];
$i = 1;
foreach ($this->variables() as $name => $pattern) {
if (!isset($values[$i])) {
$variables[$name] = !$pattern ? null : [];
continue;
}
if (!$pattern) {
$variables[$name] = $values[$i] ?: null;
} else {
$token = $parser::tokenize($pattern, '/');
$rule = $parser::compile($token);
if (preg_match_all('~' . $rule[0] . '~', $values[$i], $parts)) {
foreach ($parts[1] as $value) {
if (strpos($value, '/') !== false) {
$variables[$name][] = explode('/', $value);
} else {
$variables[$name][] = $value;
}
}
} else {
$variables[$name] = [];
}
}
$i++;
}
return $variables;
} | php | {
"resource": ""
} |
q262222 | Route.dispatch | test | public function dispatch($response = null)
{
if ($error = $this->error()) {
throw new RouterException($this->message(), $error);
}
$this->response = $response;
$request = $this->request;
$generator = $this->middleware();
$next = function() use ($request, $response, $generator, &$next) {
$handler = $generator->current();
$generator->next();
return $handler($request, $response, $next);
};
return $next();
} | php | {
"resource": ""
} |
q262223 | Route.link | test | public function link($params = [], $options = [])
{
$defaults = [
'absolute' => false,
'basePath' => '',
'query' => '',
'fragment' => ''
];
$options = array_filter($options, function($value) { return $value !== '*'; });
$options += $defaults;
$params = $params + $this->params;
$link = $this->_link($this->token(), $params);
$basePath = trim($options['basePath'], '/');
if ($basePath) {
$basePath = '/' . $basePath;
}
$link = isset($link) ? ltrim($link, '/') : '';
$link = $basePath . ($link ? '/' . $link : $link);
$query = $options['query'] ? '?' . $options['query'] : '';
$fragment = $options['fragment'] ? '#' . $options['fragment'] : '';
if ($options['absolute']) {
if ($host = $this->host()) {
$link = $host->link($params, $options) . "{$link}";
} else {
$scheme = !empty($options['scheme']) ? $options['scheme'] . '://' : '//';
$host = isset($options['host']) ? $options['host'] : 'localhost';
$link = "{$scheme}{$host}{$link}";
}
}
return $link . $query . $fragment;
} | php | {
"resource": ""
} |
q262224 | Host._compile | test | protected function _compile()
{
if ($this->pattern() === '*') {
return;
}
$parser = $this->_classes['parser'];
$rule = $parser::compile($this->token());
$this->_regex = $rule[0];
$this->_variables = $rule[1];
} | php | {
"resource": ""
} |
q262225 | Host.match | test | public function match($request, &$hostVariables = null)
{
$defaults = [
'host' => '*',
'scheme' => '*'
];
$request += $defaults;
$scheme = $request['scheme'];
$host = $request['host'];
$hostVariables = [];
$anyHost = $this->pattern() === '*' || $host === '*';
$anyScheme = $this->scheme() === '*' || $scheme === '*';
if ($anyHost) {
if ($this->variables()) {
$hostVariables = array_fill_keys(array_keys($this->variables()), null);
}
return $anyScheme || $this->scheme() === $scheme;
}
if (!$anyScheme && $this->scheme() !== $scheme) {
return false;
}
if (!preg_match('~^' . $this->regex() . '$~', $host, $matches)) {
$hostVariables = null;
return false;
}
$i = 0;
foreach ($this->variables() as $name => $pattern) {
$hostVariables[$name] = $matches[++$i];
}
return true;
} | php | {
"resource": ""
} |
q262226 | Host.link | test | public function link($params = [], $options = [])
{
$defaults = [
'scheme' => $this->scheme()
];
$options += $defaults;
if (!isset($options['host'])) {
$options['host'] = $this->_link($this->token(), $params);
}
$scheme = $options['scheme'] !== '*' ? $options['scheme'] . '://' : '//';
return $scheme . $options['host'];
} | php | {
"resource": ""
} |
q262227 | Parser.tokenize | test | public static function tokenize($pattern, $delimiter = '/')
{
// Checks if the pattern has some optional segments.
if (count(preg_split('~' . static::PLACEHOLDER_REGEX . '(*SKIP)(*F)|\[~x', $pattern)) > 1) {
$tokens = static::_tokenizePattern($pattern, $delimiter);
} else {
$tokens = static::_tokenizeSegment($pattern, $delimiter);
}
return [
'optional' => false,
'greedy' => '',
'repeat' => false,
'pattern' => $pattern,
'tokens' => $tokens
];
} | php | {
"resource": ""
} |
q262228 | Parser._tokenizePattern | test | protected static function _tokenizePattern($pattern, $delimiter, &$variable = null)
{
$tokens = [];
$index = 0;
$path = '';
$parts = static::split($pattern);
foreach ($parts as $part) {
if (is_string($part)) {
$tokens = array_merge($tokens, static::_tokenizeSegment($part, $delimiter, $variable));
continue;
}
$greedy = $part[1];
$repeat = $greedy === '+' || $greedy === '*';
$optional = $greedy === '?' || $greedy === '*';
$children = static::_tokenizePattern($part[0], $delimiter, $variable);
$tokens[] = [
'optional' => $optional,
'greedy' => $greedy ?: '?',
'repeat' => $repeat ? $variable : false,
'pattern' => $part[0],
'tokens' => $children
];
}
return $tokens;
} | php | {
"resource": ""
} |
q262229 | Parser._tokenizeSegment | test | protected static function _tokenizeSegment($pattern, $delimiter, &$variable = null)
{
$tokens = [];
$index = 0;
$path = '';
if (preg_match_all('~' . static::PLACEHOLDER_REGEX . '()~x', $pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach ($matches as $match) {
$offset = $match[0][1];
$path .= substr($pattern, $index, $offset - $index);
$index = $offset + strlen($match[0][0]);
if ($path) {
$tokens[] = $path;
$path = '';
}
$variable = $match[1][0];
$capture = $match[2][0] ?: '[^' . $delimiter . ']+';
$tokens[] = [
'name' => $variable,
'pattern' => $capture
];
}
}
if ($index < strlen($pattern)) {
$path .= substr($pattern, $index);
if ($path) {
$tokens[] = $path;
}
}
return $tokens;
} | php | {
"resource": ""
} |
q262230 | Parser.split | test | public static function split($pattern)
{
$segments = [];
$len = strlen($pattern);
$buffer = '';
$opened = 0;
for ($i = 0; $i < $len; $i++) {
if ($pattern[$i] === '{') {
do {
$buffer .= $pattern[$i++];
if ($pattern[$i] === '}') {
$buffer .= $pattern[$i];
break;
}
} while ($i < $len);
} elseif ($pattern[$i] === '[') {
$opened++;
if ($opened === 1) {
$segments[] = $buffer;
$buffer = '';
} else {
$buffer .= $pattern[$i];
}
} elseif ($pattern[$i] === ']') {
$opened--;
if ($opened === 0) {
$greedy = '?';
if ($i < $len -1) {
if ($pattern[$i + 1] === '*' || $pattern[$i + 1] === '+') {
$greedy = $pattern[$i + 1];
$i++;
}
}
$segments[] = [$buffer, $greedy];
$buffer = '';
} else {
$buffer .= $pattern[$i];
}
} else {
$buffer .= $pattern[$i];
}
}
if ($buffer) {
$segments[] = $buffer;
}
if ($opened) {
throw ParserException::squareBracketMismatch();
}
return $segments;
} | php | {
"resource": ""
} |
q262231 | Parser.compile | test | public static function compile($token)
{
$variables = [];
$regex = '';
foreach ($token['tokens'] as $child) {
if (is_string($child)) {
$regex .= preg_quote($child, '~');
} elseif (isset($child['tokens'])) {
$rule = static::compile($child);
if ($child['repeat']) {
if (count($rule[1]) > 1) {
throw ParserException::placeholderExceeded();
}
$regex .= '((?:' . $rule[0] . ')' . $child['greedy'] . ')';
} elseif ($child['optional']) {
$regex .= '(?:' . $rule[0] . ')?';
}
foreach ($rule[1] as $name => $pattern) {
if (isset($variables[$name])) {
throw ParserException::duplicatePlaceholder($name);
}
$variables[$name] = $pattern;
}
} else {
$name = $child['name'];
if (isset($variables[$name])) {
throw ParserException::duplicatePlaceholder($name);
}
if ($token['repeat']) {
$variables[$name] = $token['pattern'];
$regex .= $child['pattern'];
} else {
$variables[$name] = false;
$regex .= '(' . $child['pattern'] . ')';
}
}
}
return [$regex, $variables];
} | php | {
"resource": ""
} |
q262232 | Scope.scopify | test | public function scopify($options)
{
$scope = $this->_scope;
if (!empty($options['name'])) {
$options['name'] = $scope['name'] ? $scope['name'] . '.' . $options['name'] : $options['name'];
}
if (!empty($options['prefix'])) {
$options['prefix'] = $scope['prefix'] . trim($options['prefix'], '/');
$options['prefix'] = $options['prefix'] ? $options['prefix'] . '/' : '';
}
if (isset($options['persist'])) {
$options['persist'] = ((array) $options['persist']) + $scope['persist'];
}
if (isset($options['namespace'])) {
$options['namespace'] = $scope['namespace'] . trim($options['namespace'], '\\') . '\\';
}
return $options + $scope;
} | php | {
"resource": ""
} |
q262233 | Router.bind | test | public function bind($pattern, $options = [], $handler = null)
{
if (!is_array($options)) {
$handler = $options;
$options = [];
}
if (!$handler instanceof Closure && !method_exists($handler, '__invoke')) {
throw new RouterException("The handler needs to be an instance of `Closure` or implements the `__invoke()` magic method.");
}
if (isset($options['method'])) {
throw new RouterException("Use the `'methods'` option to limit HTTP verbs on a route binding definition.");
}
$scope = end($this->_scopes);
$options = $scope->scopify($options);
$options['pattern'] = $pattern;
$options['handler'] = $handler;
$options['scope'] = $scope;
$scheme = $options['scheme'];
$host = $options['host'];
if (isset($this->_hosts[$scheme][$host])) {
$options['host'] = $this->_hosts[$scheme][$host];
}
if (isset($this->_pattern[$scheme][$host][$pattern])) {
$instance = $this->_pattern[$scheme][$host][$pattern];
} else {
$route = $this->_classes['route'];
$instance = new $route($options);
$this->_hosts[$scheme][$host] = $instance->host();
}
if (!isset($this->_pattern[$scheme][$host][$pattern])) {
$this->_pattern[$scheme][$host][$pattern] = $instance;
}
$methods = $options['methods'] ? (array) $options['methods'] : [];
$instance->allow($methods);
foreach ($methods as $method) {
$this->_routes[$scheme][$host][strtoupper($method)][] = $instance;
}
if (isset($options['name'])) {
$this->_data[$options['name']] = $instance;
}
return $instance;
} | php | {
"resource": ""
} |
q262234 | Router.group | test | public function group($prefix, $options, $handler = null)
{
if (!is_array($options)) {
$handler = $options;
if (is_string($prefix)) {
$options = [];
} else {
$options = $prefix;
$prefix = '';
}
}
if (!$handler instanceof Closure && !method_exists($handler, '__invoke')) {
throw new RouterException("The handler needs to be an instance of `Closure` or implements the `__invoke()` magic method.");
}
$options['prefix'] = isset($options['prefix']) ? $options['prefix'] : $prefix;
$scope = $this->scope();
$this->pushScope($scope->seed($options));
$handler($this);
return $this->popScope();
} | php | {
"resource": ""
} |
q262235 | Router.route | test | public function route($request)
{
$defaults = [
'path' => '',
'method' => 'GET',
'host' => '*',
'scheme' => '*'
];
$this->_defaults = [];
if ($request instanceof RequestInterface) {
$uri = $request->getUri();
$r = [
'scheme' => $uri->getScheme(),
'host' => $uri->getHost(),
'method' => $request->getMethod(),
'path' => $uri->getPath()
];
if (method_exists($request, 'basePath')) {
$this->basePath($request->basePath());
}
} elseif (!is_array($request)) {
$r = array_combine(array_keys($defaults), func_get_args() + array_values($defaults));
} else {
$r = $request + $defaults;
}
$r = $this->_normalizeRequest($r);
if ($route = $this->_route($r)) {
$route->request = is_object($request) ? $request : $r;
foreach ($route->persist as $key) {
if (isset($route->params[$key])) {
$this->_defaults[$key] = $route->params[$key];
}
}
} else {
$route = $this->_classes['route'];
$error = $route::NOT_FOUND;
$message = "No route found for `{$r['scheme']}:{$r['host']}:{$r['method']}:/{$r['path']}`.";
$route = new $route(compact('error', 'message'));
}
return $route;
} | php | {
"resource": ""
} |
q262236 | Router._normalizeRequest | test | protected function _normalizeRequest($request)
{
if (preg_match('~^(?:[a-z]+:)?//~i', $request['path'])) {
$parsed = array_intersect_key(parse_url($request['path']), $request);
$request = $parsed + $request;
}
$request['path'] = (ltrim(strtok($request['path'], '?'), '/'));
$request['method'] = strtoupper($request['method']);
return $request;
} | php | {
"resource": ""
} |
q262237 | Router._route | test | protected function _route($request)
{
$path = $request['path'];
$httpMethod = $request['method'];
$host = $request['host'];
$scheme = $request['scheme'];
$allowedSchemes = array_unique([$scheme => $scheme, '*' => '*']);
$allowedMethods = array_unique([$httpMethod => $httpMethod, '*' => '*']);
if ($httpMethod === 'HEAD') {
$allowedMethods += ['GET' => 'GET'];
}
foreach ($this->_routes as $scheme => $hostBasedRoutes) {
if (!isset($allowedSchemes[$scheme])) {
continue;
}
foreach ($hostBasedRoutes as $routeHost => $methodBasedRoutes) {
foreach ($methodBasedRoutes as $method => $routes) {
if (!isset($allowedMethods[$method]) && $httpMethod !== '*') {
continue;
}
foreach ($routes as $route) {
if (!$route->match($request, $variables, $hostVariables)) {
if ($hostVariables === null) {
continue 3;
}
continue;
}
return $route;
}
}
}
}
} | php | {
"resource": ""
} |
q262238 | Router.link | test | public function link($name, $params = [], $options = [])
{
$defaults = [
'basePath' => $this->basePath()
];
$options += $defaults;
$params += $this->_defaults;
if (!isset($this[$name])) {
throw new RouterException("No binded route defined for `'{$name}'`, bind it first with `bind()`.");
}
$route = $this[$name];
return $route->link($params, $options);
} | php | {
"resource": ""
} |
q262239 | Router.clear | test | public function clear()
{
$this->_basePath = '';
$this->_strategies = [];
$this->_defaults = [];
$this->_routes = [];
$scope = $this->_classes['scope'];
$this->_scopes = [new $scope(['router' => $this])];
} | php | {
"resource": ""
} |
q262240 | WorkflowViewWidget.createJs | test | private function createJs()
{
$nodes = $this->_workflow->getAllStatuses();
$trList = [];
$nodeList = [];
foreach($nodes as $node) {
$n = new \stdClass();
$n->id = $node->getId();
$n->label = $node->getLabel();
if( $node->getMetadata('color') ){
if( $node->getWorkflow()->getInitialStatusId() == $node->getId() ){
$n->borderWidth = 4;
$n->color = new \stdClass();
$n->color->border = 'rgb(0,255,42)';
// $n->color->background = $node->getMetadata('color');
} else {
// $n->color = $node->getMetadata('color');
}
}
$nodeList[] = $n;
$transitions = $node->getTransitions();
foreach($transitions as $transition){
$t = new \stdClass();
$t->from = $n->id;
$t->to = $transition->getEndStatus()->getId();
$t->arrows = 'to';
$trList[] = $t;
}
}
$jsonNodes = \yii\helpers\Json::encode($nodeList);
$jsonTransitions = \yii\helpers\Json::encode($trList);
$js=<<<EOS
var {$this->visNetworkId} = new vis.Network(
document.getElementById('{$this->containerId}'),
{
nodes: new vis.DataSet($jsonNodes),
edges: new vis.DataSet($jsonTransitions)
},
{
"physics": {
"solver": "repulsion"
}
}
);
EOS;
return $js;
} | php | {
"resource": ""
} |
q262241 | FileTokenStorage.get | test | public function get()
{
if (!$this->empty())
{
return $this->file->disk()->get(
$this->hashName
);
}
return null;
} | php | {
"resource": ""
} |
q262242 | SendpulseApi.getToken | test | private function getToken() {
$data = array(
'grant_type' => 'client_credentials',
'client_id' => $this->userId,
'client_secret' => $this->secret,
);
$requestResult = $this->sendRequest( 'oauth/access_token', 'POST', $data, false );
if( $requestResult->http_code != 200 ) {
return false;
}
$this->refreshToken = 0;
$this->token = $requestResult->data->access_token;
$this->storage->set($this->token);
return true;
} | php | {
"resource": ""
} |
q262243 | SendpulseApi.listAddressBooks | test | public function listAddressBooks( $limit = NULL, $offset = NULL ) {
$data = array();
if( !is_null( $limit ) ) {
$data['limit'] = $limit;
}
if( !is_null( $offset ) ) {
$data['offset'] = $offset;
}
$requestResult = $this->sendRequest( 'addressbooks', 'GET', $data );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262244 | SendpulseApi.getEmailsFromBook | test | public function getEmailsFromBook( $id ) {
if( empty( $id ) ) {
return $this->handleError( 'Empty book id' );
}
$requestResult = $this->sendRequest( 'addressbooks/' . $id . '/emails' );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262245 | SendpulseApi.addEmails | test | public function addEmails( $bookId, $emails ) {
if( empty( $bookId ) || empty( $emails ) ) {
return $this->handleError( 'Empty book id or emails' );
}
$data = array(
'emails' => serialize( $emails )
);
$requestResult = $this->sendRequest( 'addressbooks/' . $bookId . '/emails', 'POST', $data );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262246 | SendpulseApi.campaignCost | test | public function campaignCost( $bookId ) {
if( empty( $bookId ) ) {
return $this->handleError( 'Empty book id' );
}
$requestResult = $this->sendRequest( 'addressbooks/' . $bookId . '/cost' );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262247 | SendpulseApi.createCampaign | test | public function createCampaign( $senderName, $senderEmail, $subject, $body, $bookId, $name = '', $attachments = '' ) {
if( empty( $senderName ) || empty( $senderEmail ) || empty( $subject ) || empty( $body ) || empty( $bookId ) ) {
return $this->handleError( 'Not all data.' );
}
if( !empty( $attachments ) ) {
$attachments = serialize( $attachments );
}
$data = array(
'sender_name' => $senderName,
'sender_email' => $senderEmail,
'subject' => $subject,
'body' => base64_encode( $body ),
'list_id' => $bookId,
'name' => $name,
'attachments' => $attachments
);
$requestResult = $this->sendRequest( 'campaigns', 'POST', $data );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262248 | SendpulseApi.addSender | test | public function addSender( $senderName, $senderEmail ) {
if( empty( $senderName ) || empty( $senderEmail ) ) {
return $this->handleError( 'Empty sender name or email' );
}
$data = array(
'email' => $senderEmail,
'name' => $senderName
);
$requestResult = $this->sendRequest( 'senders', 'POST', $data );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262249 | SendpulseApi.activateSender | test | public function activateSender( $email, $code ) {
if( empty( $email ) || empty( $code ) ) {
return $this->handleError( 'Empty email or activation code' );
}
$data = array(
'code' => $code
);
$requestResult = $this->sendRequest( 'senders/' . $email . '/code', 'POST', $data );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262250 | SendpulseApi.pushListWebsiteSubscriptions | test | public function pushListWebsiteSubscriptions( $websiteId, $limit = NULL, $offset = NULL ) {
$data = array();
if( !is_null( $limit ) ) {
$data['limit'] = $limit;
}
if( !is_null( $offset ) ) {
$data['offset'] = $offset;
}
$requestResult = $this->sendRequest( 'push/websites/'.$websiteId.'/subscriptions', 'GET', $data );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262251 | SendpulseApi.pushSetSubscriptionState | test | public function pushSetSubscriptionState( $subscriptionId, $stateValue ) {
$data = array(
'id' => $subscriptionId,
'state' => $stateValue
);
$requestResult = $this->sendRequest( 'push/subscriptions/state', 'POST', $data );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262252 | SendpulseApi.createPushTask | test | public function createPushTask( $taskInfo, $additionalParams = array() ) {
$data = $taskInfo;
if (!isset($data['ttl'])) {
$data['ttl'] = 0;
}
if( empty($data['title']) || empty($data['website_id']) || empty($data['body']) ) {
return $this->handleError( 'Not all data' );
}
if ($additionalParams) {
foreach($additionalParams as $key=>$val) {
$data[$key] = $val;
}
}
$requestResult = $this->sendRequest( '/push/tasks', 'POST', $data );
return $this->handleResult( $requestResult );
} | php | {
"resource": ""
} |
q262253 | TokenStorageManager.hashName | test | protected function hashName()
{
$userId = $this->app['config']->get('sendpulse.api_user_id');
$secret = $this->app['config']->get('sendpulse.api_secret');
return md5($userId . '::' . $secret);
} | php | {
"resource": ""
} |
q262254 | CommunicationAdapter.sendToWebsite | test | public function sendToWebsite($url, array $params)
{
// Sending request
$client = $this->getClient();
$response = $client->request('POST', $url, [
'query' => http_build_query($params, '', '&')
]);
// Getting response body
$responseString = $response->getBody()->getContents();
$responseString = trim($responseString);
return $responseString;
} | php | {
"resource": ""
} |
q262255 | CommunicationAdapter.sendToApi | test | public function sendToApi($url, array $params, $responseType = self::RESPONSE_NEW_LINE, array $notDecode = null, $forceArray = array())
{
$this->preSendToApiCheck();
// Merging post-data
$fields = array();
$fields['loginName'] = $this->getAccount()->getLoginName();
$fields['loginPassword'] = $this->getAccount()->getLoginPassword();
$fields = array_merge($fields, $params);
// Sending request
$client = $this->getClient();
$response = $client->request(
'POST',
$url,
['form_params' => $fields]
);
$query = http_build_query($params);
// Getting response body
$responseString = $response->getBody()->getContents();
$responseString = trim($responseString);
// Decoding and returning response
if ($responseType == self::RESPONSE_NEW_LINE) {
return $this->decodeNewLineEncodedResponse($responseString, $query, $forceArray);
} else {
return $this->decodeUrlEncodedResponse($responseString, $query, $notDecode, $forceArray);
}
} | php | {
"resource": ""
} |
q262256 | CommunicationAdapter.preSendToApiCheck | test | protected function preSendToApiCheck()
{
if ($this->getAccount() === null) {
throw new \Exception('Please provided an account');
}
if (!$this->getAccount()->isValid()) {
throw new \Exception('Please provided valid account');
}
return true;
} | php | {
"resource": ""
} |
q262257 | CommunicationAdapter.decodeNewLineEncodedResponse | test | protected function decodeNewLineEncodedResponse($responseString, $requestQuery, array $forceArray = array())
{
// Splitting response body
$parts = explode(chr(10), $responseString);
// Getting the status
$status = trim($parts[0]);
$responseArray = [];
// Valid answer?
if (is_numeric($status)) {
// Successful?
if ($status != '0') {
$responseArray['errorCode'] = $status;
$responseArray['errorMessage'] = trim($parts[1]);
} else {
$responseArray['errorCode'] = $status;
$partCount = count($parts);
for ($i = 1; $i < $partCount; $i++) {
$tmp = preg_split('/[\s\t]+/', $parts[$i], 2);
$key = trim($tmp[0]);
$value = trim($tmp[1]);
// if key already exists, open new array dimension
if (isset($responseArray[$key])) {
if (!is_array($responseArray[$key])) {
$tmpValue = $responseArray[$key];
$responseArray[$key] = array();
$responseArray[$key][] = $tmpValue;
$responseArray[$key][] = $value;
} else {
$responseArray[$key][] = $value;
}
} else {
// Just save
$responseArray[$key] = $value;
}
}
}
} else {
$responseArray['errorCode'] = '';
$responseArray['errorMessage'] = trim($responseString);
}
foreach ($forceArray as $value) {
if (isset($responseArray[$value]) && !is_array($responseArray[$value])) {
$responseArray[$value] = array($responseArray[$value]);
}
}
$responseArray['responseString'] = $responseString;
$responseArray['requestQuery'] = $requestQuery;
return $responseArray;
} | php | {
"resource": ""
} |
q262258 | CommunicationAdapter.decodeUrlEncodedResponse | test | protected function decodeUrlEncodedResponse(
$responseString,
$requestQuery,
array $notDecode = null,
$forceArray = array()
)
{
if (empty($notDecode)) {
$responseString = urldecode($responseString);
}
if (!empty($forceArray)) {
foreach ($forceArray as $param) {
$responseString = str_replace($param.'=', $param.'[]=', $responseString);
}
}
// Splitting response body
$responseArray = [];
parse_str($responseString, $responseArray);
if (!empty($notDecode) && is_array($responseArray)) {
foreach ($responseArray as $index => $value) {
if (!in_array($index, $notDecode)) {
$value = urldecode($value);
}
$responseArray[$index] = $value;
}
}
$responseArray['responseString'] = $responseString;
$responseArray['requestQuery'] = $requestQuery;
if (!isset($responseArray['errorCode'])) {
$responseArray['errorCode'] = 99;
$responseArray['errorMessage'] = $responseString;
}
return $responseArray;
} | php | {
"resource": ""
} |
q262259 | ImapHelper.fetchMails | test | public function fetchMails(ImapAdapter $imap, $search, $markProcessed = true, $assume = false, \Closure $callbackFunction = null)
{
$folder = 'INBOX';
$imap->selectFolder($folder);
$result = $imap->search(array($search));
$messages = [];
foreach ($result as $id) {
$message = null;
try {
$message = $imap->getMessage($id);
$messages[$id]['id'] = $id;
$messages[$id]['folder'] = $folder;
// Zend-mail sometimes got problems, with incorrect e-mails
try {
$messages[$id]['subject'] = utf8_decode($message->getHeader('subject', 'string'));
} catch (\Exception $e) {
$messages[$id]['subject'] = '-No subject-';
}
try {
$messages[$id]['received'] = strtotime($message->getHeader('date', 'string'));
} catch (\Exception $e) {
$messages[$id]['received'] = '-No date-';
}
$messages[$id]['plainText'] = $this->getPlainText($message);
$messages[$id]['attachments'] = $this->getAttachments($message);
$messages[$id]['type'] = $this->getTypeOfMail($messages[$id]);
if ($assume) {
$messages[$id]['orderNumber'] = $this->assumeOrderNumber($messages[$id]);
$messages[$id]['domainName'] = $this->assumeDomainName($messages[$id]);
}
$success = true;
if (is_callable($callbackFunction)) {
$success = $callbackFunction($id, $messages[$id]);
}
} catch (ExceptionInterface $e) {
// General decoding error -> removeMessage
unset($messages[$id]);
// Always mark as processed
$success = true;
}
if ($markProcessed && $success) {
$this->markProcessed($imap, $id, $message);
}
}
return $messages;
} | php | {
"resource": ""
} |
q262260 | ImapHelper.markProcessed | test | protected function markProcessed(ImapAdapter $imap, $id, Message $message = null)
{
$flags = $message ? $message->getFlags() : [];
$flags[] = self::PROCESSED_FLAG;
try {
$imap->setFlags($id, $flags);
} catch (ExceptionInterface $e) {
// Nothing to do
}
} | php | {
"resource": ""
} |
q262261 | ImapHelper.getTypeOfMail | test | protected function getTypeOfMail(array $mail)
{
foreach (self::$subjects as $key => $subject) {
if (stristr($mail['subject'], $subject) !== false) {
return $key;
}
}
foreach (self::$bodies as $key => $body) {
if (preg_match($body, $mail['plainText'])) {
return $key;
}
}
return null;
} | php | {
"resource": ""
} |
q262262 | Util.autoRefund | test | public function autoRefund(array $params)
{
if (false === isset($params['refundReasonCode'])) {
$params['refundReasonCode'] = self::AUTO_REFUND_REASON_OTHER;
}
$response = $this
->communicationAdapter
->sendToApi(
self::COMODO_AUTO_REFUND_URL,
$params,
CommunicationAdapter::RESPONSE_URL_ENCODED
);
if ($response['errorCode'] == 0) {
return true;
} else {
throw $this->createException($response);
}
} | php | {
"resource": ""
} |
q262263 | Util.autoApplySSL | test | public function autoApplySSL(array $params)
{
// Two choices, we want url-encoded
$params['responseFormat'] = CommunicationAdapter::RESPONSE_URL_ENCODED;
$params['showCertificateID'] = 'Y';
// Send request
$arr = $this
->communicationAdapter
->sendToApi(self::COMODO_AUTO_APPLY_URL, $params, CommunicationAdapter::RESPONSE_URL_ENCODED);
// Successful
if ($arr['errorCode'] == 1 || $arr['errorCode'] == 0) {
$result = new AutoApplyResult();
if ($arr['errorCode'] == 0) {
$paid = true;
} else {
$paid = false;
}
$result
->setPaid($paid)
->setCertificateID($arr['certificateID'])
->setExpectedDeliveryTime($arr['expectedDeliveryTime'])
->setOrderNumber($arr['orderNumber'])
->setTotalCost($arr['totalCost'])
->setRequestQuery($arr['requestQuery']);
if (isset($arr['uniqueValue'])) {
$result->setUniqueValue($arr['uniqueValue']);
}
return $result;
} else {
throw $this->createException($arr);
}
} | php | {
"resource": ""
} |
q262264 | Util.autoReplaceSSL | test | public function autoReplaceSSL(array $params)
{
// Two choices, we want url-encoded
$params['responseFormat'] = CommunicationAdapter::RESPONSE_URL_ENCODED;
// Send request
$arr = $this
->communicationAdapter
->sendToApi(
self::COMODO_AUTO_REPLACE_URL,
$params,
CommunicationAdapter::RESPONSE_URL_ENCODED
);
// Successful
if ($arr['errorCode'] == 0) {
$result = new AutoReplaceResult();
$result
->setCertificateID($arr['certificateID'])
->setExpectedDeliveryTime($arr['expectedDeliveryTime']);
if (isset($arr['uniqueValue'])) {
$result->setUniqueValue($arr['uniqueValue']);
}
return $result;
} else {
throw $this->createException($arr);
}
} | php | {
"resource": ""
} |
q262265 | Util.autoRevokeSSL | test | public function autoRevokeSSL(array $params)
{
// Two choices, we want url-encoded
$params['responseFormat'] = CommunicationAdapter::RESPONSE_URL_ENCODED;
return $this->sendBooleanRequest(
self::COMODO_AUTO_REVOKE_URL,
$params,
CommunicationAdapter::RESPONSE_URL_ENCODED
);
} | php | {
"resource": ""
} |
q262266 | Util.collectSsl | test | public function collectSsl(array $params)
{
// Not decode the following indexes
$notDecode = array('caCertificate', 'certificate', 'netscapeCertificateSequence', 'zipFile');
// Force threating as array
$forceArray = array('caCertificate');
// Two choices, we want url-encoded
$params['responseFormat'] = CommunicationAdapter::RESPONSE_URL_ENCODED;
// Send request
$arr = $this
->communicationAdapter
->sendToApi(
self::COMODO_COLLECT_SSL_URL,
$params,
CommunicationAdapter::RESPONSE_URL_ENCODED,
$notDecode,
$forceArray
);
// Successful
if ($arr['errorCode'] >= 0) {
$result = new CollectSslResult();
$this->fill($result, $arr, array('notBefore', 'notAfter'));
/*
* Comodo does not provide these data, when not a EV certificate (Bug?). So we fill this manually to "not required".
*
* https://secure.comodo.net/api/pdf/webhostreseller/sslcertificates/CollectSSL%20v1.17.pdf
*/
if (!isset($arr['evClickThroughStatus'])) {
$result->setEvClickThroughStatus(-1);
}
if (!isset($arr['brandValStatus'])) {
$result->setBrandValStatus(-1);
}
return $result;
} else {
throw $this->createException($arr);
}
} | php | {
"resource": ""
} |
q262267 | Util.getDCVEMailAddressList | test | public function getDCVEMailAddressList(array $params)
{
// Force threating as array
$forceArray = array('whois_email', 'level2_email', 'level3_email');
// Response is always new line encoded
$responseArray = $this
->communicationAdapter
->sendToApi(
self::COMODO_DCV_MAIL_URL,
$params,
CommunicationAdapter::RESPONSE_NEW_LINE,
null,
$forceArray
);
if ($responseArray['errorCode'] == 0) {
$result = new GetDCVEMailAddressListResult();
if (isset($responseArray['whois_email'][0]) && $responseArray['whois_email'][0] == 'none') {
unset($responseArray['whois_email'][0]);
}
$result
->setDomainName($responseArray['domain_name'])
->setWhoisEmail($responseArray['whois_email'])
->setLevel2Emails($responseArray['level2_email'])
->setRequestQuery($responseArray['requestQuery']);
if (isset($responseArray['level3_email'])) {
$result->setLevel3Emails($responseArray['level3_email']);
}
return $result;
} else {
throw $this->createException($responseArray);
}
} | php | {
"resource": ""
} |
q262268 | Util.sslChecker | test | public function sslChecker(array $params)
{
// Response is always new line encoded
$responseArray = $this
->communicationAdapter
->sendToApi(
self::COMODO_SSLCHECKER,
$params,
CommunicationAdapter::RESPONSE_URL_ENCODED
);
if ($responseArray['error_code'] == 0) {
$result = new SslCheckerResult();
$result
->setServerUrl($responseArray['server_url'])
->setServerDomainIsIDN($responseArray['server_domain_isIDN'])
->setServerDomainUtf8($responseArray['server_domain_utf8'])
->setServerDomainAce($responseArray['server_domain_ace'])
->setServerIp($responseArray['server_ip'])
->setServerPort($responseArray['server_port'])
->setServerSoftware($responseArray['server_software'])
->setCertNotBeforeFromUnixTimestamp($responseArray['cert_notBefore'])
->setCertNotAfterFromUnixTimestamp($responseArray['cert_notAfter'])
->setCertValidityNotBefore($responseArray['cert_validity_notBefore'])
->setCertValidityNotAfter($responseArray['cert_validity_notAfter'])
->setCertKeyAlgorithm($responseArray['cert_key_algorithm'])
->setCertKeySize($responseArray['cert_key_size'])
->setCertSubjectCN($responseArray['cert_subject_DN'])
->setCertSubjectCN($responseArray['cert_subject_CN'])
->setCertSubjectOU($responseArray['cert_subject_OU'])
->setCertSubjectOrganization($responseArray['cert_subject_O'])
->setCertSubjectStreetAddress1($responseArray['cert_subject_streetAddress_1'])
->setCertSubjectStreetAddress2($responseArray['cert_subject_streetAddress_2'])
->setCertSubjectStreetAddress3($responseArray['cert_subject_streetAddress_3'])
->setCertSubjectLocality($responseArray['cert_subject_L'])
->setCertSubjectState($responseArray['cert_subject_S'])
->setCertSubjectPostalCode($responseArray['cert_subject_postalCode'])
->setCertSubjectCountry($responseArray['cert_subject_C'])
->setCertIsMultiDomain($responseArray['cert_isMultiDomain'])
->setCertIsWildcard($responseArray['cert_isWildcard'])
->setCertIssuerDN($responseArray['cert_issuer_DN'])
->setCertIssuerCN($responseArray['cert_issuer_CN'])
->setCertIssuerOrganization($responseArray['cert_issuer_O'])
->setCertIssuerOrganization($responseArray['cert_issuer_C'])
->setCertIssuerBrand($responseArray['cert_issuer_brand'])
->setCertPolicyOID($responseArray['cert_policyOID'])
->setCertValidation($responseArray['cert_validation']);
return $result;
} else {
throw $this->createException($responseArray);
}
} | php | {
"resource": ""
} |
q262269 | Util.webHostReport | test | public function webHostReport(array $params) {
if (empty($params['lastResultNo'])) {
$params['lastResultNo'] = 10;
}
// Response is always new line encoded
$responseArray = $this
->communicationAdapter
->sendToApi(
self::COMODO_WEB_HOST_REPORT,
$params,
CommunicationAdapter::RESPONSE_URL_ENCODED
);
if ($responseArray['error_code'] == 0) {
$result = new WebHostReportResult();
$result->importEntries($responseArray);
return $result;
} else {
throw $this->createException($responseArray);
}
} | php | {
"resource": ""
} |
q262270 | Util.enterDCVCode | test | public function enterDCVCode(array $params)
{
// Check parameters
if (!isset($params['dcvCode'])) {
throw new ArgumentException(-3, 'Please provide an order-number', 'dcvCode', '');
}
if (!isset($params['orderNumber'])) {
throw new ArgumentException(-3, 'Please provide an order-number', 'orderNumber', '');
}
// this is not a official request, so we need to use the website
$responseString = $this
->communicationAdapter
->sendToWebsite(self::COMODO_DCV_CODE_URL, $params);
// Decode answer from website
if (stristr($responseString, 'You have entered the correct Domain Control Validation code') !== false) {
return true;
} elseif (stristr($responseString, 'the certificate has already been issued') !== false) {
throw new ArgumentException(-104, 'The certificate has already been issued', 'certificate', $responseString);
} elseif (stristr($responseString, 'Invalid Validation Code!') !== false) {
throw new ArgumentException(-103, 'Invalid Validation Code', 'validation-code', $responseString);
} else {
throw new UnknownException(99, 'UnknownException', $responseString);
}
} | php | {
"resource": ""
} |
q262271 | Util.createException | test | protected function createException($responseArray)
{
if (is_array($responseArray) === false) {
return new UnknownException(
0,
'Internal error',
$responseArray['responseString']
);
}
switch ($responseArray['errorCode']) {
case -1: // Not using https:
case -17: // Wrong HTTP-method
return new RequestException(
$responseArray['errorCode'],
$responseArray['errorMessage'],
$responseArray['responseString']
);
case -2: // unrecognized argument
case -3: // missing argument
case -4: // invalid argument
case -7: // invalid ISO Country
case -18: // Name = Fully-Qualified Domain Name
case -35: // Name = = IP
case -19: // Name = = Accessible IP
return new ArgumentException(
$responseArray['errorCode'],
$responseArray['errorMessage'],
((isset($responseArray['errorItem'])) ? $responseArray['errorItem'] : null),
$responseArray['responseString']
);
case -16: // Permission denied
case -15: // insufficient credits
return new AccountException(
$responseArray['errorCode'],
$responseArray['errorMessage'],
$responseArray['responseString']
);
case -5: // contains wildcard
case -6: // no wildcard, but must have
case -8: // missing field
case -9: // base64 decode exception
case -10: // decode exception
case -11: // unsupported algorithm
case -12: // invalid signature
case -13: // unsupported key size
case -20: // Already rejected / Order relevated
case -21: // Already revoked
case -26: // current being issued
case -40: // key compromised
return new CSRException(
$responseArray['errorCode'],
$responseArray['errorMessage'],
$responseArray['responseString']
);
case -14:
return new UnknownApiException(
$responseArray['errorCode'],
$responseArray['errorMessage'],
$responseArray['responseString']
);
default:
return new UnknownException(
$responseArray['errorCode'],
$responseArray['errorMessage'],
$responseArray['responseString']
);
}
} | php | {
"resource": ""
} |
q262272 | MetaGenerator.generate | test | public function generate()
{
$title = $this->getTitle();
$description = $this->getDescription();
$keywords = $this->getKeywords();
$canonical = $this->getCanonical();
$html[] = "<title>$title</title>";
if (! empty($description)) {
$html[] = "<meta name='description' content='$description' />";
}
if (! empty($keywords)) {
$html[] = "<meta name='keywords' content='$keywords' />";
}
if (! empty($canonical)) {
$html[] = "<link rel='canonical' href='$canonical' />";
}
return implode(PHP_EOL, $html);
} | php | {
"resource": ""
} |
q262273 | MetaGenerator.setDescription | test | public function setDescription($description)
{
$description = strip_tags($description);
if (strlen($description) > $this->max_description_length) {
$description = substr($description, 0, $this->max_description_length);
}
$this->description = $description;
} | php | {
"resource": ""
} |
q262274 | MetaGenerator.reset | test | public function reset()
{
$this->title = null;
$this->description = null;
$this->keywords = null;
$this->canonical = null;
} | php | {
"resource": ""
} |
q262275 | SEOServiceProvider.registerBindings | test | public function registerBindings()
{
// Register the sitemap.xml generator
$this->app->singleton('calotype.seo.generators.sitemap', function ($app) {
return new SitemapGenerator();
});
// Register the meta tags generator
$this->app->singleton('calotype.seo.generators.meta', function ($app) {
return new MetaGenerator($app['config']->get('calotype-seo::defaults'));
});
// Register the robots.txt generator
$this->app->singleton('calotype.seo.generators.robots', function ($app) {
return new RobotsGenerator();
});
// Register the open graph properties generator
$this->app->singleton('calotype.seo.generators.opengraph', function ($app) {
return new OpenGraphGenerator();
});
} | php | {
"resource": ""
} |
q262276 | OpenGraphGenerator.generate | test | public function generate()
{
$html = array();
foreach ($this->properties as $property => $value) {
$html[] = strtr(static::OPENGRAPH_TAG, array(
'[property]' => static::OPENGRAPH_PREFIX . $property,
'[value]' => $value
));
}
return implode(PHP_EOL, $html);
} | php | {
"resource": ""
} |
q262277 | SitemapGenerator.addRaw | test | public function addRaw(array $data)
{
$this->validateData($data);
$data = $this->prepareData($data);
$this->entries[] = $data;
} | php | {
"resource": ""
} |
q262278 | SitemapGenerator.prepareData | test | public function prepareData(array $data)
{
$data = $this->replaceAttributes($data);
// Remove trailing slashes from the location
if (array_key_exists('loc', $data)) {
$data['loc'] = trim($data['loc'], '/');
}
return $data;
} | php | {
"resource": ""
} |
q262279 | SitemapGenerator.contains | test | public function contains($url)
{
$url = trim($url, '/');
foreach ($this->entries as $entry) {
if ($entry['loc'] == $url) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q262280 | SitemapGenerator.validateData | test | protected function validateData($data)
{
$data = $this->replaceAttributes($data);
foreach ($this->required as $required) {
if (! array_key_exists($required, $data)) {
$replacement = array_search($required, $this->replacements);
if ($replacement !== false) {
$required = $replacement;
}
throw new \InvalidArgumentException("Required sitemap property [$required] is not present.");
}
}
} | php | {
"resource": ""
} |
q262281 | BatchCommand.fillIndex | test | public function fillIndex($index)
{
/** @param Command $value */
$map = function ($value) use ($index) {
if ($value->getIndex() === null) {
$value->index($index);
}
};
array_map($map, $this->commands);
return $this;
} | php | {
"resource": ""
} |
q262282 | BatchCommand.fillType | test | public function fillType($type)
{
/** @param Command $value */
$map = function ($value) use ($type) {
if ($value->getType() === null) {
$value->type($type);
}
};
array_map($map, $this->commands);
return $this;
} | php | {
"resource": ""
} |
q262283 | IndexRequest.index | test | public function index($index)
{
$this->params['index'] = array();
$args = func_get_args();
foreach ($args as $arg) {
$this->params['index'][] = $arg;
}
return $this;
} | php | {
"resource": ""
} |
q262284 | IndexRequest.type | test | public function type($type)
{
$this->params['type'] = array();
$args = func_get_args();
foreach ($args as $arg) {
$this->params['type'][] = $arg;
}
return $this;
} | php | {
"resource": ""
} |
q262285 | IndexRequest.settings | test | public function settings($settings, $merge = true)
{
if ($settings instanceof \Sherlock\wrappers\IndexSettingsWrapper)
$newSettings = $settings->toArray();
else if (is_array($settings))
$newSettings = $settings;
else
throw new \Sherlock\common\exceptions\BadMethodCallException("Unknown parameter provided to settings(). Must be array of settings or IndexSettingsWrapper.");
if ($merge)
$this->params['indexSettings'] = array_merge($this->params['indexSettings'], $newSettings);
else
$this->params['indexSettings'] = $newSettings;
return $this;
} | php | {
"resource": ""
} |
q262286 | IndexRequest.delete | test | public function delete()
{
if (!isset($this->params['index']))
throw new exceptions\RuntimeException("Index cannot be empty.");
$index = implode(',', $this->params['index']);
$command = new Command();
$command->index($index)
->action('delete');
$this->batch->clearCommands();
$this->batch->addCommand($command);
$ret = parent::execute();
return $ret[0];
} | php | {
"resource": ""
} |
q262287 | IndexRequest.create | test | public function create()
{
if (!isset($this->params['index']))
throw new exceptions\RuntimeException("Index cannot be empty.");
$index = implode(',', $this->params['index']);
//Final JSON should be object properties, not an array. So we need to iterate
//through the array members and merge into an associative array.
$mappings = array();
foreach ($this->params['indexMappings'] as $type => $mapping) {
$mappings = array_merge($mappings, array($type => $mapping));
}
$body = array(
"settings" => $this->params['indexSettings'],
"mappings" => $mappings
);
$command = new Command();
$command->index($index)
->action('put')
->data(json_encode($body, JSON_FORCE_OBJECT));
$this->batch->clearCommands();
$this->batch->addCommand($command);
/**
* @var \Sherlock\responses\IndexResponse
*/
$ret = parent::execute();
//clear out mappings, settings
$this->resetIndex();
return $ret[0];
} | php | {
"resource": ""
} |
q262288 | IndexRequest.updateSettings | test | public function updateSettings()
{
if (!isset($this->params['index'])) {
throw new exceptions\RuntimeException("Index cannot be empty.");
}
$index = implode(',', $this->params['index']);
$body = array("index" => $this->params['indexSettings']);
$command = new Command();
$command->index($index)
->id('_settings')
->action('put')
->data(json_encode($body, JSON_FORCE_OBJECT));
$this->batch->clearCommands();
$this->batch->addCommand($command);
$ret = parent::execute();
//clear out mappings, settings
//$this->resetIndex();
return $ret[0];
} | php | {
"resource": ""
} |
q262289 | RawRequest.execute | test | public function execute()
{
if (!isset($this->params['uri'])) {
throw new exceptions\RuntimeException("URI is required for RawRequest");
}
if (!isset($this->params['method'])) {
throw new exceptions\RuntimeException("Method is required for RawRequest");
}
$command = new Command();
$command->index($this->params['uri'])
->action($this->params['method']);
if (isset($this->params['body'])) {
$command->data($this->params['body']);
}
$this->batch->clearCommands();
$this->batch->addCommand($command);
$ret = parent::execute();
return $ret[0];
} | php | {
"resource": ""
} |
q262290 | RawRequest.toJSON | test | public function toJSON()
{
$finalQuery = "";
if (isset($this->params['body'])) {
$finalQuery = json_encode($this->params['body']);
}
return $finalQuery;
} | php | {
"resource": ""
} |
q262291 | SearchRequest.sort | test | public function sort($value)
{
$args = func_get_args();
//single param, array of sorts
if (count($args) == 1 && is_array($args[0])) {
$args = $args[0];
}
foreach ($args as $arg) {
if ($arg instanceof \Sherlock\components\SortInterface) {
$this->params['sort'][] = $arg->toArray();
}
}
return $this;
} | php | {
"resource": ""
} |
q262292 | SearchRequest.facets | test | public function facets($facets)
{
$this->params['facets'] = array();
if (is_array($facets)){
$args = $facets;
}else{
$args = func_get_args();
}
foreach ($args as $arg) {
if ($arg instanceof FacetInterface) {
$this->params['facets'][] = $arg;
}
}
return $this;
} | php | {
"resource": ""
} |
q262293 | SearchRequest.composeFinalQuery | test | private function composeFinalQuery()
{
$finalQuery = array();
if (isset($this->params['fields'])) {
$finalQuery['fields'] = $this->params['fields'];
}
if (isset($this->params['query']) && $this->params['query'] instanceof components\QueryInterface) {
$finalQuery['query'] = $this->params['query']->toArray();
}
if (isset($this->params['filter']) && $this->params['filter'] instanceof components\FilterInterface) {
$finalQuery['filter'] = $this->params['filter']->toArray();
}
if (isset($this->params['facets'])) {
$tFacets = array();
foreach ($this->params['facets'] as $facet) {
//@todo Investigate a better way of doing this
//array_merge is supposedly slow when merging arrays of arrays
if ($facet instanceof FacetInterface) {
$tFacets = array_merge($tFacets, $facet->toArray());
}
}
$finalQuery['facets'] = $tFacets;
unset($tFacets);
}
if (isset($this->params['highlight']) && $this->params['highlight'] instanceof components\HighlightInterface) {
$finalQuery['highlight'] = $this->params['highlight']->toArray();
}
foreach (array('from', 'size', 'timeout', 'sort', 'min_score') as $key) {
if (isset($this->params[$key])) {
$finalQuery[$key] = $this->params[$key];
}
}
$finalQuery = json_encode($finalQuery, true);
return $finalQuery;
} | php | {
"resource": ""
} |
q262294 | BaseComponent.convertParams | test | protected function convertParams($params)
{
$paramArray = array();
foreach ($params as $param) {
if (isset($this->params[$param]) === true) {
$paramArray[$param] = $this->params[$param];
}
}
return $paramArray;
} | php | {
"resource": ""
} |
q262295 | Sherlock.addNode | test | public function addNode($host, $port = 9200)
{
$this->settings['cluster']->addNode($host, $port, $this->settings['cluster.autodetect']);
return $this;
} | php | {
"resource": ""
} |
q262296 | Bool.must | test | public function must($value)
{
$args = $this->normalizeFuncArgs(func_get_args());
foreach ($args as $arg) {
if ($arg instanceof FilterInterface) {
$this->params['must'][] = $arg->toArray();
}
}
return $this;
} | php | {
"resource": ""
} |
q262297 | DeleteDocumentRequest.document | test | public function document($id)
{
if (!$this->batch instanceof BatchCommand) {
throw new exceptions\RuntimeException("Cannot delete a document from an external BatchCommandInterface");
}
$command = new Command();
$command->id($id)
->action('delete');
//Only doing this because typehinting is wonky without it...
if ($this->batch instanceof BatchCommand) {
$this->batch->addCommand($command);
}
return $this;
} | php | {
"resource": ""
} |
q262298 | DeleteDocumentRequest.documents | test | public function documents($values)
{
if ($values instanceof BatchCommandInterface) {
$this->batch = $values;
} elseif (is_array($values)) {
$isBatch = true;
$batch = new BatchCommand();
/**
* @param mixed $value
*/
$map = function ($value) use ($isBatch, $batch) {
if (!$value instanceof Command) {
$isBatch = false;
} else {
$batch->addCommand($value);
}
};
array_map($map, $values);
if (!$isBatch) {
throw new exceptions\BadMethodCallException("If an array is supplied, all elements must be a Command object.");
}
$this->batch = $batch;
} else {
throw new exceptions\BadMethodCallException("Documents method only accepts arrays of Commands or BatchCommandInterface objects");
}
return $this;
} | php | {
"resource": ""
} |
q262299 | DeleteDocumentRequest.execute | test | public function execute()
{
//if this is an internal Sherlock BatchCommand, make sure index/types/action are filled
if ($this->batch instanceof BatchCommand) {
$this->batch->fillIndex($this->params['index'][0])
->fillType($this->params['type'][0]);
}
return parent::execute();
} | 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.