sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function registerFatalHandler()
{
$error = $this;
// When shutdown, the current working directory will be set to the web
// server directory, store it for later use
$cwd = getcwd();
register_shutdown_function(function () use ($error, $cwd) {
$e = error_get_last();
if (!$e || !in_array($e['type'], array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE))) {
// No error or not fatal error
return;
}
ob_get_length() && ob_end_clean();
// Reset the current working directory to make sure everything work as usual
chdir($cwd);
$exception = new \ErrorException($e['message'], $e['type'], 0, $e['file'], $e['line']);
if ($error->triggerHandler('fatal', $exception)) {
// Handled!
return;
}
// Fallback to error handlers
if ($error->triggerHandler('error', $exception)) {
// Handled!
return;
}
// Fallback to internal error Handlers
$error->internalHandleException($exception);
});
} | Detect fatal error and register fatal handler | entailment |
public function triggerHandler($type, $exception)
{
foreach ($this->handlers[$type] as $handler) {
$result = call_user_func_array($handler, array($exception, $this->wei));
if (true === $result) {
return true;
}
}
return false;
} | Trigger a error handler
@param string $type The type of error handlers
@param \Exception|\Throwable $exception
@return bool | entailment |
public function handleException($exception)
{
if (!$this->ignorePrevHandler && $this->prevExceptionHandler) {
call_user_func($this->prevExceptionHandler, $exception);
}
if (404 == $exception->getCode()) {
if ($this->triggerHandler('notFound', $exception)) {
return;
}
}
if (!$this->triggerHandler('error', $exception)) {
$this->internalHandleException($exception);
}
restore_exception_handler();
} | The exception handler to render pretty message
@param \Exception|\Throwable $exception | entailment |
public function displayException($e, $debug)
{
// Render CLI message
if ($this->enableCli && php_sapi_name() == 'cli') {
$this->displayCliException($e);
return;
}
// Render HTML message
$code = $e->getCode();
$file = $e->getFile();
$line = $e->getLine();
if (!$debug) {
$view = isset($this->{'view' . $code}) ? $this->{'view' . $code} : $this->view;
$message = isset($this->{'message' . $code}) ? $this->{'message' . $code} : $this->message;
$detail = isset($this->{'detail' . $code}) ? $this->{'detail' . $code} : $this->detail;
if ($view) {
require $view;
return;
}
} else {
$message = $e->getMessage();
$detail = sprintf('Threw by %s in %s on line %s', get_class($e), $file, $line);
$fileInfo = $this->getFileCode($file, $line);
$trace = htmlspecialchars($e->getTraceAsString(), ENT_QUOTES);
$detail = "<h2>File</h2>"
. "<p class=\"text-danger\">$file</p>"
. "<p><pre>$fileInfo</pre></p>"
. "<h2>Trace</h2>"
. "<p class=\"text-danger\">$detail</p>"
. "<p><pre>$trace</pre></p>";
}
$title = htmlspecialchars($message, ENT_QUOTES);
$message = nl2br($title);
$html = '<!DOCTYPE html>'
. '<html>'
. '<head>'
. '<meta name="viewport" content="width=device-width">'
. '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'
. "<title>$title</title>"
. '<style type="text/css">'
. 'body { font-size: 14px; color: #333; padding: 15px 20px 20px 20px; }'
. 'h1, h2, p, pre { margin: 0; padding: 0; }'
. 'body, pre { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif, "\5fae\8f6f\96c5\9ed1", "\5b8b\4f53"; }'
. 'h1 { font-size: 36px; }'
. 'h2 { font-size: 20px; margin: 20px 0 0; }'
. 'pre { font-size:13px; line-height: 1.42857143; }'
. '.text-danger { color: #fa5b50 }'
. '</style>'
. '</head>'
. '<body>'
. "<h1>$message</h1>"
. $detail
. '</body>'
. '</html>';
echo $html;
} | Render exception message
@param \Exception|\Throwable $e
@param bool $debug Whether show debug trace | entailment |
protected function displayCliException($e)
{
echo 'Exception', PHP_EOL,
$this->highlight($e->getMessage()),
'File', PHP_EOL,
$this->highlight($e->getFile() . ' on line ' . $e->getLine()),
'Trace', PHP_EOL,
$this->highlight($e->getTraceAsString());
if ($this->autoExit) {
exit($this->getExitCode($e));
}
} | Render exception message for CLI
@param \Exception|\Throwable $e | entailment |
public function handleError($code, $message, $file, $line)
{
if (!(error_reporting() & $code)) {
// This error code is not included in error_reporting
return;
}
restore_error_handler();
throw new \ErrorException($message, $code, 500, $file, $line);
} | The error handler convert PHP error to exception
@param int $code The level of the error raised
@param string $message The error message
@param string $file The filename that the error was raised in
@param int $line The line number the error was raised at
@throws \ErrorException convert PHP error to exception
@internal use for set_error_handler only | entailment |
public function getFileCode($file, $line, $range = 20)
{
$code = file($file);
$half = (int)($range / 2);
$start = $line - $half;
0 > $start && $start = 0;
$total = count($code);
$end = $line + $half;
$total < $end && $end = $total;
$len = strlen($end);
array_unshift($code, null);
$content = '';
for ($i = $start; $i < $end; $i++) {
$temp = str_pad($i, $len, 0, STR_PAD_LEFT) . ': ' . $code[$i];
if ($line != $i) {
$content .= htmlspecialchars($temp, ENT_QUOTES);
} else {
$content .= '<strong class="text-danger">' . htmlspecialchars($temp, ENT_QUOTES) . '</strong>';
}
}
return $content;
} | Get file code in specified range
@param string $file The file name
@param int $line The file line
@param int $range The line range
@return string | entailment |
protected function createArray(string $fieldName, array $aggregation): array
{
$return = [];
$buckets = $aggregation['buckets'] ?? $aggregation[$fieldName]['buckets'] ?? null;
if (!$buckets) {
return $return;
}
$attributeId = $this->isAttribute($fieldName);
foreach ($buckets as $key => $bucket) {
$return[$key]['count'] = $bucket['doc_count'];
$return[$key][($attributeId === false ? $fieldName : 'attributeValueId')] = $bucket['key'];
if ($attributeId !== false) {
$return[$key]['attributeId'] = $attributeId;
}
}
return array_values($return);
} | @param string $fieldName
@param array $aggregation
@return array | entailment |
protected function isAttribute(string $name)
{
$searchParam = '_attr';
if (mb_substr_count($name, $searchParam, 'UTF-8') > 0) {
return str_replace($searchParam, '', $name);
}
return false;
} | @param string $name
@return bool|mixed | entailment |
public function beforeCompile(): void
{
// Breaks at other mode then CLI
if (PHP_SAPI !== 'cli') return;
$builder = $this->getContainerBuilder();
// Verify that we have http.request
if (!$builder->hasDefinition('http.request')) {
throw new RuntimeException('Service http.request is needed');
}
$config = $this->validateConfig($this->defaults);
$builder->getDefinition('http.request')
->setFactory(Request::class, [
new Statement(UrlScript::class, [$config['url']]),
$config['query'],
$config['post'],
$config['files'],
$config['cookies'],
$config['headers'],
$config['method'],
$config['remoteAddress'],
$config['remoteHost'],
$config['rawBodyCallback'],
]);
} | Decorate services | entailment |
public function getResultFromResponse(Response $response)
{
$buckets = $response->getData()['aggregations']['variant']['buckets'];
foreach ($buckets as $bucket) {
$source = $bucket['value']['hits']['hits'][0]['_source'];
$data = json_decode($source['scope'], true);
$element = $data['data'][0];
$included = $data['included'];
$included = $this->getIncludedArray($included);
$mapperClass = $this->getMapperClass($element['type']);
if (is_null($mapperClass)) {
throw new EntityNotFoundException("Entity mapper class for {$element['type']} was not found");
}
$element['attributes'] = array_merge($element['attributes'], $source);
$result[] = $this->createObject($mapperClass, $element, $included);
}
return $result ?? [];
} | @param Response $response
@return array
@throws EntityNotFoundException | entailment |
public function end()
{
$content = ob_get_clean();
switch ($this->type) {
case 'append' :
$this->data[$this->name] .= $content;
break;
case 'prepend' :
$this->data[$this->name] = $content . $this->data[$this->name];
break;
case 'set' :
$this->data[$this->name] = $content;
}
return '';
} | Store current block content
@return string | entailment |
public function ap(M\Monadic $app) : M\Monadic
{
return $app->bind($this->value);
} | {@inheritdoc} | entailment |
public function orElse(Either $either) : Either
{
return !isset($this->value) ? $either : new static($this->value);
} | {@inheritdoc} | entailment |
public function setFactor(FilterFactorValue $factor)
{
$this->factorItem[$factor->getId()] = $factor->getCoefficient();
return $this;
} | @param FilterFactorValue $factor
@return $this | entailment |
protected function doCreateObject(array $array)
{
$attribute = new Attribute(isset($array['attributes']) && is_array($array['attributes']) ? $array['attributes'] : $array);
if (isset($array['attributeValues'])) {
$mapper = new AttributeValuesMapper();
foreach ($array['attributeValues'] as $item) {
$attribute->values[] = $mapper->createObject($item);
}
}
if (isset($array['attributeGroups'])) {
$mapper = new AttributeGroupsMapper();
$attribute->group = $mapper->createObject($array['attributeGroups']);
}
return $attribute;
} | @param array $array
@return Attribute | entailment |
public function run(JsUtils $js){
parent::run($js);
if(isset($this->close)){
$js->execOn("click", "#".$this->identifier." .close", "$(this).closest('.message').transition('fade')");
}
} | {@inheritDoc}
@see \Ajax\semantic\html\base\HtmlSemDoubleElement::run() | entailment |
public static function lift(callable $function, Left $left) : callable
{
return function () use ($function, $left) {
if (
array_reduce(
func_get_args($function),
function (bool $status, Either $val) {
return $val->isLeft() ? false : $status;
},
true
)
) {
$args = array_map(
function (Either $either) {
return $either
->orElse(Either::right(null))
->getRight();
},
func_get_args()
);
return self::right(call_user_func($function, ...$args));
}
return $left;
};
} | lift method.
@param callable $function
@param Left $left
@return callable | entailment |
protected function createObject($mapperClass, $element, $included)
{
/** @var Mapper $mapper */
$mapper = new $mapperClass;
return $mapper->createObject(array_merge($this->getAttributes($element), $included));
} | @param $mapperClass
@param $element
@param $included
@return mixed | entailment |
protected function getResultFromResponse(Response $response)
{
$included = $this->getIncludedArray($response->getIncluded());
$includedFull = $this->getIncludedArray($response->getIncluded(), false);
$result = [];
foreach ($response->getData() as $element) {
$type = $element['attributes']['type'];
$entity = $includedFull[$type][$element['attributes'][substr($type, 0, -1) . 'Id']];
if (is_null($mapperClass = $this->getMapperClass($type))) {
throw new EntityNotFoundException("Entity mapper class for $type was not found");
}
$result[] = $this->createObject($mapperClass, $entity, $included);
}
return $result;
} | @param Response $response
@return array
@throws EntityNotFoundException | entailment |
public function makeSingle(Response $response)
{
if (!$response->getSuccess()) {
return 0;
}
$data = $response->getData();
if (isset($data[0])) {
$item = $this->getAttributes($data[0]);
return (int)$item['count'];
}
return 0;
} | @param Response $response
@return int|null|\SphereMall\MS\Entities\Entity | entailment |
protected function doCreateObject(array $array)
{
$raw = [];
foreach ($array as $item) {
$raw[$item['attributeId']]['id'] = $item['attributeId'];
$raw[$item['attributeId']]['title'] = $item['title'];
$raw[$item['attributeId']]['code'] = $item['code'];
$raw[$item['attributeId']]['cssClass'] = $item['cssClass'];
$raw[$item['attributeId']]['orderNumber'] = $item['orderNumber'];
$raw[$item['attributeId']]['showInSpecList'] = $item['showInSpecList'];
$raw[$item['attributeId']]['useInFilter'] = $item['useInFilter'];
$raw[$item['attributeId']]['description'] = $item['description'];
$raw[$item['attributeId']]['attributeGroupId'] = $item['attributeGroupId'];
$raw[$item['attributeId']]['displayType'] = $item['displayType'];
$raw[$item['attributeId']]['attributeValues'][] = [
'id' => $item['id'],
'value' => $item['value'],
'cssClass' => $item['cssClass'],
'title' => $item['valueTitle'],
'amount' => $item['amount'],
'orderNumber' => $item['orderNumberAttributeValues'] ?? null
];
}
$mapper = new AttributesMapper();
$result = [];
foreach ($raw as $item) {
$result[] = $mapper->createObject($item);
}
return $result;
} | @param array $array
@return array | entailment |
public function concat(array $files)
{
$baseUrl = trim($this->baseUrl, '/');
$url = $this->concatUrl . '?f=' . implode(',', $files);
return $baseUrl ? $url . '&b=' . trim($this->baseUrl, '/') : $url;
} | Returns the Minify concat URL for list of files
@param array $files
@return string
@link https://github.com/mrclay/minify | entailment |
public function detailAll(array $ids = [])
{
$uriAppend = 'detail/list';
$params = $this->getQueryParams();
if ($ids){
$params['ids'] = implode(',', $ids);
}
$response = $this->handler->handle('GET', false, $uriAppend, $params);
return $this->make($response);
} | @param array $ids
@return Entity[]
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function detailById(int $id)
{
$all = $this->detail($id);
return $this->checkAndReturnSingleResult($all);
} | @param int $id
@return Entity
@throws EntityNotFoundException
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function detailByCode(string $code)
{
$all = $this->detail($code);
return $this->checkAndReturnSingleResult($all);
} | @param string $code
@return Entity
@throws EntityNotFoundException
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
public function set($route)
{
if (is_string($route)) {
$this->routes[] = array(
'pattern' => $route
) + $this->routeOptions;
} elseif (is_array($route)) {
$this->routes[] = $route + $this->routeOptions;
} else {
throw new \InvalidArgumentException(sprintf(
'Expected argument of type string or array, "%s" given',
is_object($route) ? get_class($route) : gettype($route)
));
}
return $this;
} | Add one route
@param array $route the options of the route
@throws \InvalidArgumentException When argument is not string or array
@return $this | entailment |
public function getRoute($id)
{
return isset($this->routes[$id]) ? $this->routes[$id] : false;
} | Get the route by id
@param string $id The id of the route
@return false|array | entailment |
protected function compile(&$route)
{
if ($route['regex']) {
return $route;
}
$regex = preg_replace('#[.\+*?[^\]${}=!|:-]#', '\\\\$0', $route['pattern']);
$regex = str_replace(array('(', ')'), array('(?:', ')?'), $regex);
$regex = str_replace(array('<', '>'), array('(?P<', '>.+?)'), $regex);
if ($route['rules']) {
$search = $replace = array();
foreach ($route['rules'] as $key => $rule) {
$search[] = '<' . $key . '>.+?';
$replace[] = '<' . $key . '>' . $rule;
}
$regex = str_replace($search, $replace, $regex);
}
$route['regex'] = '#^' . $regex . '$#uUD';
return $route;
} | Prepare the route pattern to regex
@param array $route the route array
@return array | entailment |
public function match($pathInfo, $method = null)
{
$pathInfo = rtrim($pathInfo, '/');
!$pathInfo && $pathInfo = '/';
foreach ($this->routes as $id => $route) {
if (false !== ($parameters = $this->matchRoute($pathInfo, $method, $id))) {
return $parameters;
}
}
return false;
} | Check if there is a route matches the path info and method,
and return the parameters, or return false when not matched
@param string $pathInfo The path info to match
@param string|null $method The request method to match, maybe GET, POST, etc
@return false|array | entailment |
public function matchParamSet($pathInfo, $method = 'GET')
{
$params = $this->match($pathInfo, $method);
$restParams = $this->matchRestParamSet($pathInfo, $method);
return $params ? array_merge(array($params), $restParams) : $restParams;
} | Parse the path info to parameter set
@param string $pathInfo The path info to match
@param string|null $method The request method to match, maybe GET, POST, etc
@return array | entailment |
protected function matchRoute($pathInfo, $method, $id)
{
$route = $this->compile($this->routes[$id]);
// When $route['method'] is not provided, accepts all request methods
if ($method && $route['method'] && !preg_match('#' . $route['method'] . '#i', $method)) {
return false;
}
// Check if the route matches the path info
if (!preg_match($route['regex'], $pathInfo, $matches)) {
return false;
}
// Get params in the path info
$parameters = array();
foreach ($matches as $key => $parameter) {
if (is_int($key)) {
continue;
}
$parameters[$key] = $parameter;
}
$parameters += $route['defaults'];
preg_match_all('#<([a-zA-Z0-9_]++)>#', $route['pattern'], $matches);
foreach ($matches[1] as $key) {
if (!array_key_exists($key, $parameters)) {
$parameters[$key] = null;
}
}
return array('_id' => $id) + $parameters;
} | Check if the route matches the path info and method,
and return the parameters, or return false when not matched
@param string $pathInfo The path info to match
@param string $method The request method to match
@param string $id The id of the route
@return false|array | entailment |
public function matchRestParamSet($path, $method = 'GET')
{
$rootCtrl = '';
$params = array();
$routes = array();
// Split out format
if (strpos($path, '.') !== false) {
$params['_format'] = pathinfo($path, PATHINFO_EXTENSION);
$path = substr($path, 0, - strlen($params['_format']) - 1);
}
$parts = $this->parsePath($path);
// Split out namespace
if (count($parts) > 1 && in_array($parts[0], $this->namespaces)) {
$rootCtrl .= array_shift($parts) . '/';
}
// Split out scope
if (count($parts) > 1 && in_array($parts[0], $this->scopes)) {
$rootCtrl .= array_shift($parts) . '/';
}
$baseCtrl = $rootCtrl;
// The first parameter must be controller name,
// the second parameter may be action name or id, eg posts/show, posts/1
// the last parameter may be controller name or action name or null, eg posts/1/comments, posts/1/edit
$lastParts = array_pad(array_splice($parts, count($parts) % 2 == 0 ? -2 : -3), 3, null);
list($ctrl, $actOrId, $ctrlOrAct) = $lastParts;
// Generate part of controller name and query parameters
$count = count($parts);
for ($i = 0; $i < $count; $i += 2) {
$baseCtrl .= $parts[$i] . '/';
$params[$this->camelize($this->singularize($parts[$i])) . 'Id'] = $parts[$i + 1];
}
if (is_null($actOrId)) {
// GET|POST|... /, GET|POST|... posts
$routes[] = array(
'controller' => $baseCtrl . ($ctrl ?: $this->defaultController),
'action' => $this->methodToAction($method, true),
);
} elseif (is_null($ctrlOrAct)) {
// GET posts/show
if ($this->isAction($actOrId)) {
$routes[] = array(
'controller' => $baseCtrl . $ctrl,
'action' => $actOrId,
);
}
// GET|PUT|... posts/1
$routes[] = array(
'controller' => $baseCtrl . $ctrl,
'action' => $this->methodToAction($method),
'id' => $actOrId
);
// GET posts/1/comment/new => comment::new postId=1
if ($count >= 2 && $this->isAction($actOrId)) {
$routes[] = array(
'controller' => $rootCtrl . $ctrl,
'action' => $actOrId,
);
}
} else {
// GET posts/1/edit
$routes[] = array(
'controller' => $baseCtrl . $ctrl,
'action' => $ctrlOrAct,
'id' => $actOrId
);
// GET|PUT|... posts/1/comments
$routes[] = array(
'controller' => $baseCtrl . $ctrl . '/' . $ctrlOrAct,
'action' => $this->methodToAction($method, true),
$this->camelize($this->singularize($ctrl)) . 'Id' => $actOrId,
);
// GET|PUT|... posts/1/comments, use the last parameter as main controller name
$routes[] = array('controller' => $rootCtrl . $ctrlOrAct) + $routes[1];
}
foreach ($routes as &$route) {
$route['controller'] = $this->camelize($route['controller']);
$route['action'] = $this->camelize($route['action']);
$route += $params;
}
return $routes;
} | Parse the path info to multi REST parameters
@param string $path
@param string $method
@return array | entailment |
protected function parsePath($path)
{
$path = ltrim($path, '/');
foreach ($this->combinedResources as $resource) {
if (strpos($path, $resource) !== false) {
list($part1, $part2) = explode($resource, $path, 2);
$parts = array_merge(explode('/', $part1), array($resource), explode('/', $part2));
return array_values(array_filter($parts));
}
}
return explode('/', $path);
} | Parse path to resource names, actions and ids
@param string $path
@return array | entailment |
protected function singularize($word)
{
if (isset($this->singulars[$word])) {
return $this->singulars[$word];
}
foreach ($this->singularRules as $rule => $replacement) {
if (preg_match($rule, $word)) {
$this->singulars[$word] = preg_replace($rule, $replacement, $word);
return $this->singulars[$word];
}
}
$this->singulars[$word] = $word;
return $word;
} | Returns a word in singular form.
The implementation is borrowed from Doctrine Inflector
@param string $word
@return string
@link https://github.com/doctrine/inflector | entailment |
protected function methodToAction($method, $collection = false)
{
if ($method == 'GET' && $collection) {
$method = $method . '-collection';
}
return isset($this->methodToAction[$method]) ? $this->methodToAction[$method] : $this->defaultAction;
} | Convert HTTP method to action name
@param string $method
@param bool $collection
@return string | entailment |
protected function doValidate($input)
{
if (in_array($input, $this->invalid, true)) {
$this->addError('empty');
return false;
} else {
return true;
}
} | {@inheritdoc} | entailment |
public function dispatch($controller, $action = null, array $params = array(), $throwException = true)
{
$notFound = array();
$action || $action = $this->defaultAction;
$classes = $this->getControllerClasses($controller);
foreach ($classes as $class) {
if (!class_exists($class)) {
$notFound['controllers'][$controller][] = $class;
continue;
}
if (!$this->isActionAvailable($class, $action)) {
$notFound['actions'][$action][$controller][] = $class;
continue;
}
// Find out existing controller and action
$this->setController($controller);
$this->setAction($action);
$this->request->set($params);
try {
$instance = $this->getControllerInstance($class);
return $this->execute($instance, $action);
} catch (\RuntimeException $e) {
if ($e->getCode() === self::FORWARD) {
return $this->response;
} else {
throw $e;
}
}
}
if ($throwException) {
throw $this->buildException($notFound);
} else {
return $notFound;
}
} | Dispatch by specified controller and action
@param string $controller The name of controller
@param null|string $action The name of action
@param array $params The request parameters
@param bool $throwException Whether throw exception when application not found
@return array|Response | entailment |
protected function buildException(array $notFound)
{
$notFound += array('controllers' => array(), 'actions' => array());
// All controllers and actions were not found, prepare exception message
$message = 'The page you requested was not found';
if ($this->wei->isDebug()) {
$detail = $this->request->get('debug-detail');
foreach ($notFound['controllers'] as $controller => $classes) {
$message .= sprintf('%s - controller "%s" not found', "\n", $controller);
$detail && $message .= sprintf(' (class "%s")', implode($classes, '", "'));
}
foreach ($notFound['actions'] as $action => $controllers) {
$method = $this->getActionMethod($action);
foreach ($controllers as $controller => $classes) {
$message .= sprintf('%s - method "%s" not found in controller "%s"', "\n", $method, $controller);
$detail && $message .= sprintf(' (class "%s")', implode($classes, '", "'));
}
}
}
// You can use `$wei->error->notFound(function(){});` to custom the 404 page
return new \RuntimeException($message, 404);
} | Build 404 exception from notFound array
@param array $notFound
@return \RuntimeException | entailment |
protected function execute($instance, $action)
{
$app = $this;
$wei = $this->wei;
$middleware = $this->getMiddleware($instance, $action);
$callback = function () use ($instance, $action, $app) {
$instance->before($app->request, $app->response);
$method = $app->getActionMethod($action);
$response = $instance->$method($app->request, $app->response);
$instance->after($app->request, $response);
return $response;
};
$next = function () use (&$middleware, &$next, $callback, $wei) {
$config = array_splice($middleware, 0, 1);
if ($config) {
$class = key($config);
$service = new $class(array('wei' => $wei) + $config[$class]);
$result = $service($next);
} else {
$result = $callback();
}
return $result;
};
return $this->handleResponse($next())->send();
} | Execute action with middleware
@param \Wei\BaseController $instance
@param string $action
@return Response | entailment |
protected function getMiddleware($instance, $action)
{
$results = array();
$middleware = (array) $instance->getOption('middleware');
foreach ($middleware as $class => $options) {
if ((!isset($options['only']) || in_array($action, (array) $options['only'])) &&
(!isset($options['except']) || !in_array($action, (array) $options['except']))
) {
$results[$class] = $options;
}
}
return $results;
} | Returns middleware for specified action
@param \Wei\BaseController $instance
@param string $action
@return array | entailment |
public function handleResponse($response)
{
switch (true) {
// Render default template and use $response as template variables
case is_array($response) :
$content = $this->view->render($this->getDefaultTemplate(), $response);
return $this->response->setContent($content);
// Response directly
case is_scalar($response) || is_null($response) :
return $this->response->setContent($response);
// Response if not sent
case $response instanceof Response :
return $response;
default :
throw new \InvalidArgumentException(sprintf(
'Expected argument of type array, printable variable or \Wei\Response, "%s" given',
is_object($response) ? get_class($response) : gettype($response)
));
}
} | Handle the response variable returned by controller action
@param mixed $response
@return Response
@throws \InvalidArgumentException | entailment |
public function getControllerClasses($controller)
{
$classes = array();
// Prepare parameters for replacing
$controller = strtr($controller, array('/' => '\\'));
if ($this->controllerFormat) {
// Generate class from format
$namespace = $this->getNamespace();
$class = str_replace(
array('%namespace%', '%controller%'),
array(ucfirst($namespace), ucfirst($controller)),
$this->controllerFormat
);
// Make the class name's first letter uppercase
$upperLetter = strrpos($class, '\\') + 1;
$class[$upperLetter] = strtoupper($class[$upperLetter]);
$classes[] = $class;
}
// Add class from predefined classes
if (isset($this->controllerMap[$controller])) {
$classes[] = $this->controllerMap[$controller];
}
return $classes;
} | Return the controller class names by controllers (without validate if the class exists)
@param string $controller The name of controller
@return array | entailment |
protected function getControllerInstance($class)
{
if (!isset($this->controllerInstances[$class])) {
$this->controllerInstances[$class] = new $class(array(
'wei' => $this->wei,
'app' => $this,
));
}
return $this->controllerInstances[$class];
} | Get the controller instance, if not found, return false instead
@param string $class The class name of controller
@return \Wei\BaseController | entailment |
public function isActionAvailable($object, $action)
{
$method = $this->getActionMethod($action);
try {
$ref = new \ReflectionMethod($object, $method);
if ($ref->isPublic() && $method === $ref->name) {
return true;
} else {
return false;
}
} catch (\ReflectionException $e) {
return false;
}
} | Check if action name is available
Returns false when
1. method is not found
2. method is not public
3. method letters case error
@param object $object The object of controller
@param string $action The name of action
@return bool | entailment |
public function forward($controller, $action = null, array $params = array())
{
$this->response = $this->dispatch($controller, $action, $params);
$this->preventPreviousDispatch();
} | Forwards to the given controller and action
@param string $controller The name of controller
@param null|string $action The name of action
@param array $params The request parameters | entailment |
protected function doCreateObject(array $array)
{
$orderItem = new WishListItem($array);
if (isset($array['products']) && $product = reset($array['products'])) {
$productMapper = new ProductsMapper();
if (isset($array['images'])) {
$product['images'] = $array['images'];
}
$orderItem->product = $productMapper->createObject($product);
}
return $orderItem;
} | @param array $array
@return WishListItem | entailment |
public function getMulti(array $keys)
{
$cas = null;
$keysWithPrefix = array();
foreach ($keys as $key) {
$keysWithPrefix[] = $this->namespace . $key;
}
if ($this->isMemcached3) {
$params = array($keysWithPrefix, \Memcached::GET_PRESERVE_ORDER);
} else {
$params = array($keysWithPrefix, $cas, \Memcached::GET_PRESERVE_ORDER);
}
$values = (array) call_user_func_array(array($this->object, 'getMulti'), $params);
return array_combine($keys, $values);
} | {@inheritdoc}
Note: setMulti method is not reimplemented for it returning only one
"true" or "false" for all items
@link http://www.php.net/manual/en/memcached.setmulti.php
@link https://github.com/php-memcached-dev/php-memcached/blob/master/php_memcached.c#L1219 | entailment |
public function replace($key, $value, $expire = 0)
{
return $this->object->replace($this->namespace . $key, $value, $expire);
} | {@inheritdoc} | entailment |
protected function incDec($key, $offset, $inc = true)
{
$key = $this->namespace . $key;
$method = $inc ? 'increment' : 'decrement';
$offset = abs($offset);
if (false === $this->object->$method($key, $offset)) {
return $this->object->set($key, $offset) ? $offset : false;
}
return $this->object->get($key);
} | Increment/Decrement an item
Memcached do not allow negative number as $offset parameter
@link https://github.com/php-memcached-dev/php-memcached/blob/master/php_memcached.c#L1746
@param string $key The name of item
@param int $offset The value to be increased/decreased
@param bool $inc The operation is increase or decrease
@return int|false Returns the new value on success, or false on failure | entailment |
protected function doValidate($input)
{
if (!$this->isString($input)) {
$this->addError('notString');
return false;
}
if (!$this->validateLuhn($input)) {
$this->addError('invalid');
return false;
}
if (!$this->validateType($input)) {
$this->addError('invalid');
return false;
}
return true;
} | {@inheritdoc} | entailment |
public function validateLuhn($input)
{
$checksum = '';
foreach (str_split(strrev($input)) as $i => $d) {
$checksum .= ($i %2 !== 0) ? ($d * 2) : $d;
}
return array_sum(str_split($checksum)) % 10 === 0;
} | Check if the input is valid luhn number
@param string $input
@return bool
@link https://gist.github.com/troelskn/1287893 | entailment |
public function setType($type)
{
if (is_string($type)) {
if ('all' == strtolower($type)) {
$this->type = array_keys($this->cards);
} else {
$this->type = explode(',', $type);
}
} elseif (is_array($type)) {
$this->type = $type;
} else {
throw new \InvalidArgumentException(sprintf(
'Expected argument of type array or string, "%s" given',
is_object($type) ? get_class($type) : gettype($type)
));
}
return $this;
} | Set allowed credit card types, could be array, string separated by
comma(,) or string "all" means all supported types
@param string|array $type
@return CreditCard
@throws \InvalidArgumentException When parameter is not array or string | entailment |
public function setAjaxSource($url) {
if (Text::startsWith($url, "/")) {
$u=$this->js->getDi()->get("url");
$url=$u->getBaseUri().$url;
}
$ajax="%function (request, response) {
$.ajax({
url: '{$url}',
dataType: 'jsonp',
data: {q : request.term},
success: function(data) {response(data);}
});
}%";
return $this->setParam("source", $ajax);
} | Define source property with an ajax request based on $url
$url must return a JSON array of values
@param String $url
@return $this | entailment |
protected function doValidate($input)
{
$this->addError('invalid');
$validator = null;
$props = array(
'name' => $this->name,
'negative' => true
);
foreach ($this->rules as $rule => $options) {
if (!$this->validate->validateOne($rule, $input, $options, $validator, $props)) {
$this->validators[$rule] = $validator;
}
}
if (!$this->validators) {
$this->errors = array();
return true;
} else {
return false;
}
} | {@inheritdoc} | entailment |
public function is($name)
{
$name = strtolower($name);
if (!array_key_exists($name, $this->patterns)) {
throw new \InvalidArgumentException(sprintf('Unrecognized browser, OS, mobile or tablet name "%s"', $name));
}
if (preg_match('/' . $this->patterns[$name] . '/i', $this->userAgent, $matches)) {
$this->versions[$name] = isset($matches[1]) ? $matches[1] : false;
return true;
} else {
$this->versions[$name] = false;
return false;
}
} | Check if in the specified browser, OS or device
@param string $name The name of browser, OS or device
@throws \InvalidArgumentException When name is not defined in patterns array
@return bool | entailment |
public function getVersion($name)
{
$name = strtolower($name);
if (!isset($this->versions[$name])) {
$this->is($name);
}
return $this->versions[$name];
} | Returns the version of specified browser, OS or device
@param string $name
@return string | entailment |
public function isMobile()
{
$s = $this->server;
if (
isset($s['HTTP_ACCEPT']) &&
(strpos($s['HTTP_ACCEPT'], 'application/x-obml2d') !== false || // Opera Mini; @reference: http://dev.opera.com/articles/view/opera-binary-markup-language/
strpos($s['HTTP_ACCEPT'], 'application/vnd.rim.html') !== false || // BlackBerry devices.
strpos($s['HTTP_ACCEPT'], 'text/vnd.wap.wml') !== false ||
strpos($s['HTTP_ACCEPT'], 'application/vnd.wap.xhtml+xml') !== false) ||
isset($s['HTTP_X_WAP_PROFILE']) ||
isset($s['HTTP_X_WAP_CLIENTID']) ||
isset($s['HTTP_WAP_CONNECTION']) ||
isset($s['HTTP_PROFILE']) ||
isset($s['HTTP_X_OPERAMINI_PHONE_UA']) || // Reported by Nokia devices (eg. C3)
isset($s['HTTP_X_NOKIA_IPADDRESS']) ||
isset($s['HTTP_X_NOKIA_GATEWAY_ID']) ||
isset($s['HTTP_X_ORANGE_ID']) ||
isset($s['HTTP_X_VODAFONE_3GPDPCONTEXT']) ||
isset($s['HTTP_X_HUAWEI_USERID']) ||
isset($s['HTTP_UA_OS']) || // Reported by Windows Smartphones.
isset($s['HTTP_X_MOBILE_GATEWAY']) || // Reported by Verizon, Vodafone proxy system.
isset($s['HTTP_X_ATT_DEVICEID']) || // Seend this on HTC Sensation. @ref: SensationXE_Beats_Z715e
//HTTP_X_NETWORK_TYPE = WIFI
( isset($s['HTTP_UA_CPU']) &&
$s['HTTP_UA_CPU'] == 'ARM' // Seen this on a HTC.
)
) {
return true;
}
return false;
} | Check if the device is mobile
@link https://github.com/serbanghita/Mobile-Detect
@license MIT License https://github.com/serbanghita/Mobile-Detect/blob/master/LICENSE.txt
@return bool | entailment |
function getProject($projectShortCode) {
$findProjectByShortCodeRequest = new findProjectByShortCode ();
$findProjectByShortCodeRequest->projectShortCode = $projectShortCode;
$project = $this->projectService->findProjectByShortCode ( $findProjectByShortCodeRequest )->return;
return new PDProject($project);
} | Find project by shortcode
@return PDProject | entailment |
function getProjects() {
$getUserProjectsRequest = new getUserProjects ();
$getUserProjectsRequest->isSubProjectIncluded = TRUE;
$projects = $this->projectService->getUserProjects ( $getUserProjectsRequest )->return;
$i = 0;
$proj_arr = array ();
if (is_array ( $projects )) {
foreach ( $projects as $project ) {
$pdproject = new PDProject ( $project );
$proj_arr [$i ++] = $pdproject;
}
} else {
$fullProject = $this->getProject ( $projects->projectInfo->shortCode );
$proj_arr [0] = $fullProject;
}
return $proj_arr;
} | Get all user projects
@return Array of PDProject to which the logged in user has access to | entailment |
function getSubmissionTicket() {
if (isset($this->submission) && isset($this->submission->ticket)) {
return $this->submission->ticket;
} else {
throw new Exception("Submission not initialized");
}
} | Get Submission ticket if a submission has been initialized.
@return Submission ticket | entailment |
function getSubmissionName($submissionTicket) {
$submission = $this->getSubmission($submissionTicket);
if (isset($submission)) {
return $submission->submissionInfo->name;
} else {
throw new Exception("Invalid submission ticket");
}
} | Get Submission name for specified ticket.
@param
$submissionTicket
Submission ticket
@return Submission name for the specified ticket. | entailment |
function getSubmissionId($submissionTicket) {
$submission = $this->getSubmission($submissionTicket);
if (isset($submission)) {
return $submission->submissionId;
} else {
throw new Exception("Invalid submission ticket");
}
} | Get Submission ID for specified ticket.
@param
$submissionTicket
Submission ticket
@return Submission ID for the specified ticket. | entailment |
function getSubmissionStatus($submissionTicket) {
$submission = $this->getSubmission($submissionTicket);
if (isset($submission)) {
return $submission->status;
} else {
throw new Exception("Invalid submission ticket");
}
} | Get Submission Status for specified ticket.
@param
$submissionTicket
Submission ticket
@return Status object with string name and integer value | entailment |
function cancelTargetByDocumentTicket($documentTicket, $locale) {
$cancelDocumentRequest = new cancelTargetByDocumentId ();
$dticket = new DocumentTicket ();
$dticket->ticketId = $documentTicket;
$cancelDocumentRequest->documentId = $dticket;
$cancelDocumentRequest->targetLocale = $locale;
return $this->targetService->cancelTargetByDocumentId ( $cancelDocumentRequest );
} | Cancel document for specified target language
@param
$documentTicket
Document ticket to cancel
@param
$locale
Target locale to cancel | entailment |
function cancelTarget($targetTicket) {
$cancelTargetRequest = new cancelTarget ();
$cancelTargetRequest->targetId = $targetTicket;
return $this->targetService->cancelTarget ( $cancelTargetRequest );
} | Cancel target
@param
$targetTicket
Target ticket to cancel | entailment |
function cancelSubmission($submissionTicket, $comment = NULL) {
if ($comment == NULL) {
$cancelSubmissionRequest = new cancelSubmission ();
$cancelSubmissionRequest->submissionId = $submissionTicket;
return $this->submissionService->cancelSubmission ( $cancelSubmissionRequest )->return;
} else {
$cancelSubmissionRequest = new cancelSubmissionWithComment ();
$cancelSubmissionRequest->comment = $comment;
$cancelSubmissionRequest->submissionId = $submissionTicket;
return $this->submissionService->cancelSubmissionWithComment ( $cancelSubmissionRequest )->return;
}
} | Cancel Submission for all languages
@param
$submissionTicket
Submission ticket to cancel
@param
$comment
[OPTIONAL] Cancellation comment | entailment |
function downloadTarget($ticket) {
$downloadTargetResourceRequest = new downloadTargetResource ();
$downloadTargetResourceRequest->targetId = $ticket;
$repositoryItem = $this->targetService->downloadTargetResource ( $downloadTargetResourceRequest )->return;
return $repositoryItem->data->_;
} | Downloads target document from PD
@param
$ticket
Target ticket to download | entailment |
function getCancelledTargetsBySubmissions($submissionTickets, $maxResults) {
$getCancelledTargetsBySubmissionRequest = new getCanceledTargetsBySubmissions ();
$getCancelledTargetsBySubmissionRequest->maxResults = $maxResults;
$getCancelledTargetsBySubmissionRequest->submissionTickets = is_array($submissionTickets)?$submissionTickets:array($submissionTickets);
$cancelledTargets = $this->targetService->getCanceledTargetsBySubmissions ( $getCancelledTargetsBySubmissionRequest )->return;
return $this->_convertTargetsToInternal ( $cancelledTargets );
} | Get cancelled targets for submission(s)
@param
$submissionTickets
Submission ticket or array of submission tickets
@param
$maxResults
Maximum number of cancelled targets to return. This
configuration is to avoid time-outs in case the number of
targets is very large.
@return Array of cancelled PDTarget | entailment |
function getCancelledTargets($maxResults) {
$projects = $this->getProjects ();
$tickets = array ();
$i = 0;
foreach ( $projects as $project ) {
$tickets [$i ++] = $project->ticket;
}
$getCanceledTargetsByProjectsRequest = new getCanceledTargetsByProjects ();
$getCanceledTargetsByProjectsRequest->projectTickets = $tickets;
$getCanceledTargetsByProjectsRequest->maxResults = $maxResults;
$cancelledTargets = $this->targetService->getCanceledTargetsByProjects ( $getCanceledTargetsByProjectsRequest )->return;
return $this->_convertTargetsToInternal ( $cancelledTargets );
} | Get cancelled targets for all projects
@param
$maxResults
Maximum number of cancelled targets to return. This
configuration is to avoid time-outs in case the number of
targets is very large.
@return Array of cancelled PDTarget | entailment |
function getCancelledTargetsByDocuments($documentTickets, $maxResults) {
$getCancelledTargetsByDocumentRequest = new getCanceledTargetsByDocuments ();
$getCancelledTargetsByDocumentRequest->maxResults = $maxResults;
$getCancelledTargetsByDocumentRequest->documentTickets = is_array($documentTickets)?$documentTickets:array($documentTickets);
$cancelledTargets = $this->targetService->getCanceledTargetsByDocuments ( $getCancelledTargetsByDocumentRequest )->return;
return $this->_convertTargetsToInternal ( $cancelledTargets );
} | Get cancelled targets for document(s)
@param
$documentTickets
Document ticket or array of document tickets
@param
$maxResults
Maximum number of cancelled targets to return. This
configuration is to avoid time-outs in case the number of
targets is very large.
@return Array of cancelled PDTarget | entailment |
function getCancelledTargetsByProjects($projectTickets, $maxResults) {
$getCancelledTargetsByProjectsRequest = new getCancelledTargetsByProjects ();
$getCancelledTargetsByProjectsRequest->projectTickets = is_array($projectTickets)?$projectTickets:array($projectTickets);;
$getCancelledTargetsByProjectsRequest->maxResults = $maxResults;
$cancelledTargets = $this->targetService->getCancelledTargetsByProjects ( $getCancelledTargetsByProjectsRequest )->return;
return $this->_convertTargetsToInternal ( $cancelledTargets );
} | Get cancelled targets for project(s)
@param
$projectTickets
PDProject tickets or array of PDProject tickets for which cancelled targets are requested
@param
$maxResults
Maximum number of completed targets to return in this call
@return Array of cancelled PDTarget | entailment |
function getCompletedTargetsByProjects($projectTickets, $maxResults) {
$getCompletedTargetsByProjectsRequest = new getCompletedTargetsByProjects ();
$getCompletedTargetsByProjectsRequest->projectTickets = is_array($projectTickets)?$projectTickets:array($projectTickets);;
$getCompletedTargetsByProjectsRequest->maxResults = $maxResults;
$completedTargets = $this->targetService->getCompletedTargetsByProjects ( $getCompletedTargetsByProjectsRequest )->return;
return $this->_convertTargetsToInternal ( $completedTargets );
} | Get completed targets for project(s)
@param
$projectTickets
PDProject tickets or array of PDProject tickets for which completed targets are requested
@param
$maxResults
Maximum number of completed targets to return in this call
@return Array of completed PDTarget | entailment |
function getCompletedTargets($maxResults) {
$projects = $this->getProjects ();
$tickets = array ();
$i = 0;
foreach ( $projects as $project ) {
$tickets [$i ++] = $project->ticket;
}
$getCompletedTargetsByProjectsRequest = new getCompletedTargetsByProjects ();
$getCompletedTargetsByProjectsRequest->projectTickets = $tickets;
$getCompletedTargetsByProjectsRequest->maxResults = $maxResults;
$completedTargets = $this->targetService->getCompletedTargetsByProjects ( $getCompletedTargetsByProjectsRequest )->return;
return $this->_convertTargetsToInternal ( $completedTargets );
} | Get completed targets for all projects
@param
$maxResults
Maximum number of completed targets to return in this call
@return Array of completed PDTarget | entailment |
function getCompletedTargetsBySubmission($submissionTickets, $maxResults) {
$getCompletedTargetsBySubmissionsRequest = new getCompletedTargetsBySubmissions ();
$getCompletedTargetsBySubmissionsRequest->submissionTickets = is_array($submissionTickets)?$submissionTickets:array($submissionTickets);
$getCompletedTargetsBySubmissionsRequest->maxResults = $maxResults;
$completedTargets = $this->targetService->getCompletedTargetsBySubmissions ( $getCompletedTargetsBySubmissionsRequest )->return;
return $this->_convertTargetsToInternal ( $completedTargets );
} | Get completed targets for submission(s)
@param
$submissionTicket
Submission ticket or array of tickets for which completed targets are requested
@param
$maxResults
Maximum number of completed targets to return in this call
@return Array of completed PDTarget | entailment |
function getCompletedTargetsByDocument($documentTickets, $maxResults) {
$getCompletedTargetsByDocumentsRequest = new getCompletedTargetsByDocuments ();
$getCompletedTargetsByDocumentsRequest->documentTickets = is_array($documentTickets)?$documentTickets:array($documentTickets);
$getCompletedTargetsByDocumentsRequest->maxResults = $maxResults;
$completedTargets = $this->targetService->getCompletedTargetsByDocuments ( $getCompletedTargetsByDocumentsRequest )->return;
return $this->_convertTargetsToInternal ( $completedTargets );
} | Get completed targets by document ticket(s)
@param
$documentTickets
Document ticket or array of tickets for which completed targets are requested
@param
$maxResults
Maximum number of completed targets to return in this call
@return Array of completed PDTarget | entailment |
function getUnstartedSubmissions($project) {
$submissions = array ();
$creatingSubmissions = $this->submissionService->findCreatingSubmissionsByProjectShortCode($project->shortCode)->return;
foreach ($creatingSubmissions as &$creatingSubmission){
$sub = new Submission();
$sub->ticket = $creatingSubmission->ticket;
$sub->name = $creatingSubmission->submissionInfo->name;
array_push($submissions , $sub);
}
return $submissions;
} | Get Unstarted Submissions.
@param
$project
PDProject
@return Array of PDSubmission that have not been started. | entailment |
function initSubmission($submission) {
$this->_validateSubmission ( $submission );
$this->submission = $submission;
$this->submission->ticket = "";
} | Initialize a new Submission
@param
$submission
PDSubmission configuration to initialize a new submission | entailment |
function isSubmitterValid($shortCode, $newSubmitter){
$getSubmittersRequest = new getSubmitters ();
$getSubmittersRequest->projectShortCode = $shortCode;
$submitters = $this->userProfileService->getSubmitters ( $getSubmittersRequest )->return;
if(isset($submitters)){
foreach ($submitters as &$submitter){
if(isset($submitter)){
$info = $submitter;
if(isset($submitter->userInfo)){
$info = $submitter->userInfo;
}
if($info->userName == $newSubmitter && ($info->enabled=='1' || $info->enabled==1 || $info->enabled=='true' || $info->enabled==true)){
return true;
}
}
}
}
return false;
} | Validate Submission submitter
@param
$shortCode
Project shortcode
@param
$submitter
Username to validate | entailment |
function sendDownloadConfirmation($ticket) {
$sendDownloadConfirmationRequest = new sendDownloadConfirmation ();
$sendDownloadConfirmationRequest->targetId = $ticket;
return $this->targetService->sendDownloadConfirmation ( $sendDownloadConfirmationRequest )->return;
} | Sends confirmation that the target resources was downloaded successfully
by the customer.
@param
$ticket
Downloaded target ticket | entailment |
function uploadTranslatable($document) {
if (! isset ( $this->submission ) || ! isset ( $this->submission->ticket )) {
throw new Exception ( "Submission not initialized." );
}
$this->_validateDocument ( $document );
$documentInfo = $document->getDocumentInfo ( $this->submission );
$resourceInfo = $document->getResourceInfo ();
$submitDocumentWithBinaryResourceRequest = new submitDocumentWithBinaryResource ();
$submitDocumentWithBinaryResourceRequest->documentInfo = $documentInfo;
$submitDocumentWithBinaryResourceRequest->resourceInfo = $resourceInfo;
$submitDocumentWithBinaryResourceRequest->data = $document->data;
$documentTicket = $this->documentService->submitDocumentWithBinaryResource ( $submitDocumentWithBinaryResourceRequest )->return;
if (isset ( $documentTicket )) {
$this->submission->ticket = $documentTicket->submissionTicket;
}
return $documentTicket->ticketId;
} | Uploads the document to project director for translation
@param
$document
PDDocument that requires translation
@return Document ticket | entailment |
function uploadTranslationKit($fileName, $data){
$result = "";
$resourceInfo = new ResourceInfo();
$resourceInfo->name = $fileName;
$resourceInfo->size = strlen ( $data );
// Upload file
$workflowRequestTicket = $this->workflowService->upload($resourceInfo, $data)->return;
// Wait until upload is done, or print error message if it failed
$uploadFinished = false;
while (!$uploadFinished) {
// Create delay between two checkUploadAction calls
sleep(DELAY_TIME);
$uploadActionResult = $this->workflowService->checkUploadAction($workflowRequestTicket);
$uploadFinished = $uploadActionResult->processingFinished->booleanValue;
if ($uploadFinished && isset($uploadActionResult->messages)) {
foreach($uploadActionResult->messages as &$message){
$result = $result + $message+";";
}
}
}
return $result;
} | Uploads preliminary delivery file to project director
@param
$fileName
Filename that requires translation
@param
$data
File data (String)
@return Response message | entailment |
protected function doValidate($input)
{
$flag = 0;
if ($this->path) {
$flag = $flag | FILTER_FLAG_PATH_REQUIRED;
}
if ($this->query) {
$flag = $flag | FILTER_FLAG_QUERY_REQUIRED;
}
if (!filter_var($input, FILTER_VALIDATE_URL, $flag)) {
$this->addError('invalid');
return false;
}
return true;
} | {@inheritdoc} | entailment |
public function get($key, $expire = null, $fn = null)
{
$oriKey = $key;
$key = $this->namespace . $key;
$result = array_key_exists($key, $this->data) ? $this->data[$key] : false;
return $this->processGetResult($oriKey, $result, $expire, $fn);
} | {@inheritdoc} | entailment |
public function set($key, $value, $expire = 0)
{
$this->data[$this->namespace . $key] = $value;
return true;
} | {@inheritdoc} | entailment |
public function replace($key, $value, $expire = 0)
{
if (!$this->exists($key)) {
return false;
} else {
$this->data[$this->namespace . $key] = $value;
return true;
}
} | {@inheritdoc} | entailment |
public function incr($key, $offset = 1)
{
if ($this->exists($key)) {
return $this->data[$this->namespace . $key] += $offset;
} else {
return $this->data[$this->namespace . $key] = $offset;
}
} | {@inheritdoc} | entailment |
public function render($attributes=null) {
$this->renderer->getElement()->setDefault($this->getValue());
return $this->renderer->render($attributes);
} | /*
(non-PHPdoc)
@see \Phalcon\Forms\ElementInterface::render() | entailment |
public function renderAsBreadcrumb($menu, array $options = [])
{
$options = array_merge(['template' => $this->defaultTemplate], $options);
if ((!is_array($menu)) && (!$menu instanceof ItemInterface)) {
$path = [];
if (is_array($menu)) {
if (empty($menu)) {
throw new \InvalidArgumentException('The array cannot be empty');
}
$path = $menu;
$menu = array_shift($path);
}
$menu = $this->menuHelper->get($menu, $path);
}
// Look into the menu to fetch the current item
$treeIterator = new \RecursiveIteratorIterator(
new RecursiveItemIterator(
new \ArrayIterator([$menu])
), \RecursiveIteratorIterator::SELF_FIRST
);
$itemFilterIterator = new CurrentItemFilterIterator($treeIterator, $this->matcher);
$itemFilterIterator->rewind();
// Watch for a current item
$current = $itemFilterIterator->current();
$manipulator = new MenuManipulator();
if ($current instanceof ItemInterface) {
// Extract the items for the breadcrumb
$breadcrumbs = $manipulator->getBreadcrumbsArray($current);
} else {
// Current item could not be located, we only send the first item
$breadcrumbs = $manipulator->getBreadcrumbsArray($menu);
}
// Load the template if needed
if (!$options['template'] instanceof \Twig_Template) {
$options['template'] = $this->twig->loadTemplate($options['template']);
}
// renderBlock is @internal, other solution for this ?
return $options['template']->renderBlock('root', ['breadcrumbs' => $breadcrumbs, 'options' => $options]);
} | Render an array or KNP menu as foundation breadcrumb.
@param ItemInterface|string $menu
@param array $options
@return mixed | entailment |
public function handle(string $method, $body = false, $uriAppend = false, array $queryParams = [])
{
$client = new \GuzzleHttp\Client();
$async = $this->client->getAsync();
//Set user authorization
$options = [];
if (!$async) {
$options = $this->setAuthorization();
}
//Generate request URL
$url = $this->client->getGatewayUrl() . '/' . $this->resource->getVersion() . '/' . $this->resource->getURI();
//Base url should end without slash
$url = str_replace('?', '', $url);
$url = rtrim($url, '/');
//Append additional data to url
if ($uriAppend) {
$url = $url . '/' . $uriAppend;
}
//Add query params
if ($queryParams) {
$url = $url . '?' . urldecode(http_build_query($queryParams));
}
if ($body instanceof Entity) {
$body = $body->asArray();
}
if($this->withChannel) {
$options['headers']['Channel-id'] = $this->client->channelId;
}
$options['headers']['Referer'] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ($body) {
switch (strtolower($method)) {
case 'get' :
$options['body'] = json_encode($body);
break;
case 'put':
$options['body'] = http_build_query($body);
$options['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
break;
case 'patch':
$options['body'] = json_encode($body);
$options['headers']['Content-Type'] = 'application/json';
$method = 'PUT';
break;
case 'post':
$options['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
$options['form_params'] = $body;
break;
case 'delete':
$options['body'] = http_build_query($body);
break;
}
}
//Check and generate async request if needed
$time = 0;
if ($async) {
return compact('method', 'url', 'options', 'time');
}
//Call closure if existing
if ($this->client->beforeAPICall) {
call_user_func($this->client->beforeAPICall, $method, $url, $options);
}
$time = microtime(true);
//Return response
try{
$httpResponse = $client->request($method, $url, $options);
}catch (ClientException $e){
$httpResponse = $e->getResponse();
}catch (ServerException $e){
$httpResponse = $e->getResponse();
}
$time = round((microtime(true) - $time), 4);
//Set statistic history for current call
$this->client->setCallStatistic(compact('method', 'url', 'options', 'time'));
return new Response($httpResponse);
} | @param string $method
@param bool $body
@param bool $uriAppend
@param array $queryParams
@return Promise\PromiseInterface|Response
@throws \Exception
@throws \GuzzleHttp\Exception\GuzzleException | entailment |
protected function doValidate($input)
{
if (!$this->isString($input)) {
$this->addError('notString');
return false;
}
$file = stream_resolve_include_path($input);
if (!$file) {
$this->addError('notFound');
return false;
}
return true;
} | {@inheritdoc} | entailment |
public function execute()
{
// Init the retry times
if ($this->retries && is_null($this->leftRetries)) {
$this->leftRetries = $this->retries;
}
// Prepare request
$ch = $this->ch = curl_init();
curl_setopt_array($ch, $this->prepareCurlOptions());
$this->beforeSend && call_user_func($this->beforeSend, $this, $ch);
// Execute request
$response = curl_exec($ch);
// Handle response
$this->handleResponse($response);
$this->complete && call_user_func($this->complete, $this, $ch);
// Retry if response error
if ($this->result === false && $this->leftRetries > 0) {
$this->leftRetries--;
$this->execute();
return;
}
if ($this->throwException && $this->errorException) {
throw $this->errorException;
}
} | Execute the request, parse the response data and trigger relative callbacks | entailment |
protected function prepareCurlOptions()
{
$opts = array();
$url = $this->url;
// CURLOPT_RESOLVE
if ($this->ip) {
$host = parse_url($url, PHP_URL_HOST);
$url = substr_replace($url, $this->ip, strpos($url, $host), strlen($host));
$this->headers['Host'] = $host;
}
switch ($this->method) {
case 'GET' :
$postData = false;
break;
case 'POST' :
$postData = true;
$opts[CURLOPT_POST] = 1;
break;
case 'DELETE':
case 'PUT':
case 'PATCH':
$postData = true;
$opts[CURLOPT_CUSTOMREQUEST] = $this->method;
break;
default:
$postData = false;
$opts[CURLOPT_CUSTOMREQUEST] = $this->method;
}
if ($this->data) {
$data = is_string($this->data) ? $this->data : http_build_query($this->data);
if ($postData) {
$opts[CURLOPT_POSTFIELDS] = $data;
} else {
if (false === strpos($url, '?')) {
$url .= '?' . $data;
} else {
$url .= '&' . $data;
}
}
}
if ($this->files) {
$postFields = isset($opts[CURLOPT_POSTFIELDS]) ? $opts[CURLOPT_POSTFIELDS] : '';
$opts[CURLOPT_POSTFIELDS] = $this->addFileField($postFields, $this->files);
}
if ($this->timeout > 0) {
$opts[CURLOPT_TIMEOUT_MS] = $this->timeout;
}
if ($this->referer) {
// Automatic use current request URL as referer URL
if (true === $this->referer) {
$opts[CURLOPT_REFERER] = $this->url;
} else {
$opts[CURLOPT_REFERER] = $this->referer;
}
}
if ($this->userAgent) {
$opts[CURLOPT_USERAGENT] = $this->userAgent;
}
if ($this->cookies) {
$cookies = array();
foreach ($this->cookies as $key => $value) {
$cookies[] = $key . '=' . urlencode($value);
}
$opts[CURLOPT_COOKIE] = implode('; ', $cookies);
}
if ($this->contentType) {
$this->headers['Content-Type'] = $this->contentType;
}
// Custom headers will overwrite other options
if ($this->headers) {
$headers = array();
foreach ($this->headers as $key => $value) {
$headers[] = $key . ': ' . $value;
}
$opts[CURLOPT_HTTPHEADER] = $headers;
}
$opts[CURLOPT_HEADER] = $this->header;
$opts[CURLOPT_URL] = $url;
$this->curlOptions += $opts + $this->defaultCurlOptions;
return $this->curlOptions;
} | Prepare cURL options
@return array | entailment |
protected function handleResponse($response)
{
$ch = $this->ch;
if (false !== $response) {
$curlInfo = curl_getinfo($ch);
// Parse response header
if ($this->getCurlOption(CURLOPT_HEADER)) {
// Fixes header size error when use CURLOPT_PROXY and CURLOPT_HTTPPROXYTUNNEL is true
// http://sourceforge.net/p/curl/bugs/1204/
if (false !== stripos($response, "HTTP/1.1 200 Connection established\r\n\r\n")) {
$response = str_ireplace("HTTP/1.1 200 Connection established\r\n\r\n", '', $response);
}
$this->responseHeader = trim(substr($response, 0, $curlInfo['header_size']));
$this->responseText = substr($response, $curlInfo['header_size']);
} else {
$this->responseText = $response;
}
$statusCode = $curlInfo['http_code'];
$isSuccess = $statusCode >= 200 && $statusCode < 300 || $statusCode === 304;
if ($isSuccess) {
$this->response = $this->parseResponse($this->responseText, $exception);
if (!$exception) {
$this->result = true;
$this->success && call_user_func($this->success, $this->response, $this);
} else {
$this->triggerError('parser', $exception);
}
} else {
if ($this->responseHeader) {
preg_match('/[\d]{3} (.+?)\r/', $this->responseHeader, $matches);
$statusText = $matches[1];
} else {
$statusText = 'HTTP request error';
}
// + 1000 to avoid conflicts with error service 404 detection
$exception = new \ErrorException($statusText, $statusCode + 1000);
$this->triggerError('http', $exception);
}
} else {
$exception = new \ErrorException(curl_error($ch), curl_errno($ch));
$this->triggerError('curl', $exception);
}
} | Parse response text
@param string $response | entailment |
protected function triggerError($status, \ErrorException $exception)
{
$this->result = false;
$this->errorStatus = $status;
$this->errorException = $exception;
$this->error && call_user_func($this->error, $this, $status, $exception);
} | Trigger error callback
@param string $status
@param \ErrorException $exception | entailment |
protected function parseResponse($data, &$exception)
{
switch ($this->dataType) {
case 'json' :
case 'jsonObject' :
$result = json_decode($data, $this->dataType === 'json');
if (null === $result && json_last_error() != JSON_ERROR_NONE) {
$exception = new \ErrorException('JSON parsing error, the data is ' . $data, json_last_error());
}
break;
case 'xml' :
case 'serialize' :
$methods = array(
'xml' => 'simplexml_load_string',
'serialize' => 'unserialize',
);
$result = @$methods[$this->dataType]($data);
if (false === $result && $e = error_get_last()) {
$exception = new \ErrorException($e['message'], $e['type'], 0, $e['file'], $e['line']);
}
break;
case 'query' :
// Parse $data(string) and assign the result to $result(array)
parse_str($data, $result);
break;
case 'text':
default :
$result = $data;
break;
}
return $result;
} | Parse response data by specified type
@param string $data
@param null $exception A variable to store exception when parsing error
@return mixed | entailment |
public function getCurlOption($option)
{
return isset($this->curlOptions[$option]) ? $this->curlOptions[$option] : null;
} | Returns an option value of the current cURL handle
@param int $option
@return null | entailment |
public function getResponseHeader($name = null, $first = true)
{
// Return response header string when parameter is not provided
if (is_null($name)) {
return $this->responseHeader;
}
$name = strtoupper($name);
$headers = $this->getResponseHeaders();
if (!isset($headers[$name])) {
return $first ? null : array();
} else {
return $first ? current($headers[$name]) : $headers[$name];
}
} | Returns request header value
@param string $name The header name
@param bool $first Return the first element or the whole header values
@return string|array When $first is true, returns string, otherwise, returns array | entailment |
public function getResponseHeaders()
{
if (!is_array($this->responseHeaders)) {
$this->responseHeaders = array();
foreach (explode("\n", $this->responseHeader) as $line) {
$line = explode(':', $line, 2);
$name = strtoupper($line[0]);
$value = isset($line[1]) ? trim($line[1]) : null;
$this->responseHeaders[$name][] = $value;
}
}
return $this->responseHeaders;
} | Returns response headers array
@return array | entailment |
public function getResponseCookies()
{
if (!is_array($this->responseCookies)) {
$cookies = $this->getResponseHeader('SET-COOKIE', false);
$this->responseCookies = array();
foreach ($cookies as $cookie) {
$this->responseCookies += $this->parseCookie($cookie);
}
}
return $this->responseCookies;
} | Returns a key-value array contains the response cookies, like $_COOKIE
@return array | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.