sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function generateAction()
{
$extension = $this->params()->fromRoute('extension', QrCodeServiceInterface::DEFAULT_EXTENSION);
$content = $this->qrCodeService->getQrCodeContent($this->params());
return $this->createResponse($content, $this->qrCodeService->generateContentType($extens... | Generates the QR code and returns it as stream | entailment |
protected function createResponse($content, $contentType)
{
$resp = new HttpResponse();
$resp->setStatusCode(200)
->setContent($content);
$resp->getHeaders()->addHeaders(array(
'Content-Length' => strlen($content),
'Content-Type' => $contentType
... | Creates the response to be returned for a QR Code
@param $content
@param $contentType
@return HttpResponse | entailment |
public function renderImg($message, $extension = null, $size = null, $padding = null, $attribs = array())
{
if (isset($extension)) {
if (is_array($extension)) {
$attribs = $extension;
$extension = null;
} elseif (isset($size)) {
if (is_... | Renders a img tag pointing defined QR code
@param string $message
@param string|null $extension
@param int|null $size
@param null $padding
@param array $attribs
@return string | entailment |
public function renderBase64Img($message, $extension = null, $size = null, $padding = null, $attribs = array())
{
if (isset($extension)) {
if (is_array($extension)) {
$attribs = $extension;
$extension = null;
} elseif (isset($size)) {
i... | Renders a img tag with a base64-encoded QR code
@param string $message
@param string|null $extension
@param int|null $size
@param null $padding
@param array $attribs
@return mixed | entailment |
public function assembleRoute($message, $extension = null, $size = null, $padding = null)
{
$params = array('message' => $message);
if (isset($extension)) {
$params['extension'] = $extension;
if (isset($size)) {
$params['size'] = $size;
if (iss... | Returns the assembled route as string
@param $message
@param null $extension
@param null $size
@param null $padding
@return mixed | entailment |
public static function stop()
{
self::$stopTime = microtime(true);
// 记录内存结束使用
function_exists('memory_get_usage') && self::$stopMemory = memory_get_usage();
Cml::getContainer()->make('cml_debug')->stopAndShowDebugInfo();
Plugin::hook('cml.before_ob_end_flush');
CML... | 程序执行完毕,打印CmlPHP运行信息 | entailment |
public static function catcher($errorType, $errorTip, $errorFile, $errorLine)
{
if (!isset(self::$tipInfoType[$errorType])) {
$errorType = 'Unknow';
}
if ($errorType == E_NOTICE || $errorType == E_USER_NOTICE) {
$color = '#000088';
} else {
$color ... | 错误handler
@param int $errorType 错误类型 分运行时警告、运行时提醒、自定义错误、自定义提醒、未知等
@param string $errorTip 错误提示
@param string $errorFile 发生错误的文件
@param int $errorLine 错误所在行数
@return void | entailment |
public static function addTipInfo($msg, $type = self::TIP_INFO_TYPE_INFO, $color = '')
{
if (Cml::$debug) {
$color && $msg = "<span style='color:{$color}'>" . $msg . '</span>';
switch ($type) {
case self::TIP_INFO_TYPE_INFO:
self::$tipInfo[] = $msg... | 添加调试信息
@param string $msg 调试消息字符串
@param int $type 消息的类型
@param string $color 是否要添加字体颜色
@return void | entailment |
public static function addSqlInfo($sql, $type = self::SQL_TYPE_NORMAL, $other = 0)
{
switch ($type) {
case self::SQL_TYPE_FROM_CACHE:
$sql .= "<span style='color:red;'>[from cache]</span>";
break;
case self::SQL_TYPE_SLOW:
$sql .= "<spa... | 添加一条sql查询的调试信息
@param $sql
@param int $type sql类型 参考常量声明SQL_TYPE_NORMAL、SQL_TYPE_FROM_CACHE、SQL_TYPE_SLOW
@param int $other type = SQL_TYPE_SLOW时带上执行时间 | entailment |
public static function codeSnippet($file, $focus, $range = 7, $style = ['lineHeight' => 20, 'fontSize' => 13])
{
$html = highlight_file($file, true);
if (!$html) {
return false;
}
// 分割html保存到数组
$html = explode('<br />', $html);
$lineNums = count($html);
... | 显示代码片段
@param string $file 文件路径
@param int $focus 出错的行
@param int $range 基于出错行上下显示多少行
@param array $style 样式
@return string | entailment |
public function stopAndShowDebugInfo()
{
if (Request::isAjax()) {
if (Config::get('dump_use_php_console')) {
self::$sql && \Cml\dumpUsePHPConsole(self::$sql, 'sql');
\Cml\dumpUsePHPConsole(self::$tipInfo, 'tipInfo');
\Cml\dumpUsePHPConsole(self::$i... | 输出调试消息
@return void | entailment |
private function makeTableHeader($type, $header, $colspan = 2)
{
if (!$this->bInitialized) {
$header = $this->getVariableName() . " (" . $header . ")";
$this->bInitialized = true;
}
$str_i = ($this->bCollapsed) ? "style=\"font-style:italic\" " : "";
echo "<ta... | create the main table header | entailment |
private function checkType($var)
{
switch (gettype($var)) {
case "resource":
$this->varIsResource($var);
break;
case "object":
$this->varIsObject($var);
break;
case "array":
$this->varIsArray(... | check variable type | entailment |
private function varIsObject($var)
{
$var_ser = serialize($var);
array_push($this->arrHistory, $var_ser);
$this->makeTableHeader("object", "object");
if (is_object($var)) {
$arrObjVars = get_object_vars($var);
foreach ($arrObjVars as $key => $value) {
... | if variable is an object type | entailment |
private function varIsResource($var)
{
$this->makeTableHeader("resourceC", "resource", 1);
echo "<tr>\n<td>\n";
switch (get_resource_type($var)) {
case "fbsql result":
case "mssql result":
case "msql query":
case "pgsql result":
cas... | if variable is a resource type | entailment |
private function varIsDBResource($var, $db = "mysql")
{
if ($db == "pgsql") {
$db = "pg";
}
if ($db == "sybase-db" || $db == "sybase-ct") {
$db = "sybase";
}
$arrFields = ["name", "type", "flags"];
$numrows = call_user_func($db . "_num_rows", $... | if variable is a database resource type | entailment |
private function varIsGDResource($var)
{
$this->makeTableHeader("resource", "gd", 2);
$this->makeTDHeader("resource", "Width");
echo imagesx($var) . $this->closeTDRow();
$this->makeTDHeader("resource", "Height");
echo imagesy($var) . $this->closeTDRow();
$this->makeTD... | if variable is an image/gd resource type | entailment |
private function xmlParse($xml_parser, $data, $bFinal)
{
if (!xml_parse($xml_parser, $data, $bFinal)) {
die(sprintf("XML error: %s at line %d\n",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
} | parse xml | entailment |
private function xmlEndElement($parser, $name)
{
for ($i = 0; $i < $this->xmlCount; $i++) {
eval($this->xmlSData[$i]);
$this->makeTDHeader("xml", "xmlText");
echo (!empty($this->xmlCData[$i])) ? $this->xmlCData[$i] : " ";
echo $this->closeTDRow();
... | xml: initiated when an end tag is encountered | entailment |
private function xmlCharacterData($parser, $data)
{
$count = $this->xmlCount - 1;
if (!empty($this->xmlCData[$count])) {
$this->xmlCData[$count] .= $data;
} else {
$this->xmlCData[$count] = $data;
}
} | xml: initiated when text between tags is encountered | entailment |
public function get($key)
{
if ($this->type === 1) {
$return = $this->memcache->get($key);
} else {
$return = json_decode($this->memcache->get($this->conf['prefix'] . $key), true);
}
is_null($return) && $return = false;
return $return; //orm层做判断用
... | 根据key取值
@param mixed $key 要获取的缓存key
@return mixed | entailment |
public function set($key, $value, $expire = 0)
{
if ($this->type === 1) {
return $this->memcache->set($key, $value, $expire);
} else {
return $this->memcache->set($this->conf['prefix'] . $key, json_encode($value, JSON_UNESCAPED_UNICODE), false, $expire);
}
} | 存储对象
@param mixed $key 要缓存的数据的key
@param mixed $value 要缓存的值,除resource类型外的数据类型
@param int $expire 缓存的有效时间 0为不过期
@return bool | entailment |
public function update($key, $value, $expire = 0)
{
if ($this->type === 1) {
return $this->memcache->replace($key, $value, $expire);
} else {
return $this->memcache->replace($this->conf['prefix'] . $key, json_encode($value, JSON_UNESCAPED_UNICODE), false, $expire);
}
... | 更新对象
@param mixed $key 要更新的数据的key
@param mixed $value 要更新缓存的值,除resource类型外的数据类型
@param int $expire 缓存的有效时间 0为不过期
@return bool | entailment |
public function delete($key)
{
$this->type === 2 && $key = $this->conf['prefix'] . $key;
return $this->memcache->delete($key);
} | 删除对象
@param mixed $key 要删除的数据的key
@return bool | entailment |
public function increment($key, $val = 1)
{
$this->type === 2 && $key = $this->conf['prefix'] . $key;
return $this->memcache->increment($key, abs(intval($val)));
} | 自增
@param mixed $key 要自增的缓存的数据的key
@param int $val 自增的进步值,默认为1
@return bool | entailment |
public function getTopMenuContent($topLocationId, Criterion $criterion = null)
{
$criteria = array(
new Criterion\ParentLocationId($topLocationId),
new Criterion\Visibility(Criterion\Visibility::VISIBLE),
);
if (!empty($criterion)) {
$criteria[] = $criter... | Returns Location objects that we want to display in top menu, based on $topLocationId.
All location objects are fetched under $topLocationId only (not in the whole tree).
One might use $excludeContentTypeIdentifiers to explicitly exclude some content types (e.g. "article").
@param int $topLocationId
@param \eZ\Publis... | entailment |
public function listPlaceListAction(Location $location)
{
/** @var \EzSystems\DemoBundle\Helper\PlaceHelper $placeHelper */
$placeHelper = $this->get('ezdemo.place_helper');
$places = $placeHelper->getPlaceList(
$location,
$this->container->getParameter('ezdemo.place... | Displays all the places contained in a place list.
@param \eZ\Publish\API\Repository\Values\Content\Location $location of a place_list
@return \Symfony\Component\HttpFoundation\Response | entailment |
public function listPlaceListSortedAction(Location $location, $latitude, $longitude, $maxDist)
{
// The Symfony router is configured (routing.yml) not to check for keys needed to generate URL
// template from twig (without calling the controller).
// We need to make sure those keys can't be ... | Displays all the places sorted by proximity contained in a place list
The max distance of the places displayed can be modified in the default config.
@param \eZ\Publish\API\Repository\Values\Content\Location $location of a place_list
@param float $latitude
@param float $longitude
@param int $maxDist Maximum distance f... | entailment |
public function run()
{
// 初始化
reset($this->queue);
for ($i = 0; $i < $this->max; $i++) {
if ($this->makeTask() == -1) {
break;
}
}
// 处理任务队列
reset($this->tasks);
while (count($this->tasks) > 0) {
$task = cur... | 执行线程队列里的所有任务
@return array | entailment |
private function makeTask()
{
$item = each($this->queue);
if (!$item) {
return -1;
}
$item = $item['value'];
$socket = @stream_socket_client($item['host'] . ':80', $errno, $errstr, $this->timeout, STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
if ($so... | 创建任务
@return int 状态: -1=线程队列空, 0=失败, 1=成功 | entailment |
private function processTask(&$task)
{
$read = $write = [$task['socket']];
$n = stream_select($read, $write, $e = null, $this->timeout);
if ($n > 0) {
switch ($task['status']) {
case 0: // ready
fwrite($task['socket'], "GET {$task['path']} HTTP... | 处理任务
@param array $task 任务信息 | entailment |
public function execute(array $args, array $options = [])
{
$this->bootstrap($args, $options);
// get the seed path from the config
$path = $this->getConfig()->getSeedPath();
if (!file_exists($path)) {
$ask = new Dialog();
if ($ask->confirm(Colour::colour('C... | 创建一个新的seeder
@param array $args 参数
@param array $options 选项 | entailment |
public function render()
{
$lines = explode("\n", $this->text);
$maxWidth = 0;
foreach ($lines as $line) {
if (strlen($line) > $maxWidth) {
$maxWidth = strlen($line);
}
}
$maxWidth += $this->padding * 2 + 2;
$output = str_repea... | 渲染文本并返回
@return string | entailment |
public static function pinyin($string, $utf8 = true)
{
$string = ($utf8 === true) ? iconv('utf-8', 'gbk', $string) : $string;
if (self::$pinyinArr == null) {
self::$pinyinArr = self::pinyinCode();
}
$num = strlen($string);
$pinyin = '';
for ($i=0; $i < $nu... | 中文转拼音
@param $string
@param bool $utf8
@return string | entailment |
public function execute(array $args, array $options = [])
{
$template = isset($options['template']) ? $options['template'] : false;
$template || $template = __DIR__ . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'Controller.php.dist';
$name = $args[0];
$name = explode('... | 创建控制器
@param array $args 参数
@param array $options 选项 | entailment |
public function setUrlParams($key = 'path', $val = '')
{
if (is_array($key)) {
self::$urlParams = array_merge(self::$urlParams, $key);
} else {
self::$urlParams[$key] = $val;
}
} | 修改解析得到的请求信息 含应用名、控制器、操作
@param string|array $key path|controller|action|root
@param string $val
@return void | entailment |
public function parseUrl()
{
\Cml\Route::parsePathInfo();
$path = '/';
//定义URL常量
$subDir = dirname($_SERVER['SCRIPT_NAME']);
if ($subDir == '/' || $subDir == '\\') {
$subDir = '';
}
//定义项目根目录地址
self::$urlParams['root'] = $subDir . '/';
... | 解析url
@return void | entailment |
private function isRoute(&$pathInfo)
{
empty($pathInfo) && $pathInfo[0] = '/';//网站根地址
$isSuccess = [];
$route = self::$rules;
$httpMethod = isset($_POST['_method']) ? strtoupper($_POST['_method']) : strtoupper($_SERVER['REQUEST_METHOD']);
switch ($httpMethod) {
... | 匹配路由
@param array $pathInfo
@return mixed | entailment |
public function getSubDirName()
{
substr(self::$urlParams['root'], -1) != '/' && self::$urlParams['root'] .= '/';
substr(self::$urlParams['root'], 0, 1) != '/' && self::$urlParams['root'] = '/' . self::$urlParams['root'];
return self::$urlParams['root'];
} | 获取子目录路径。若项目在子目录中的时候为子目录的路径如/sub_dir/、否则为/
@return string | entailment |
public function getControllerAndAction()
{
//控制器所在路径
$appName = self::getAppName();
$className = $appName . ($appName ? '/' : '') . Cml::getApplicationDir('app_controller_path_name') .
'/' . self::getControllerName() . Config::get('controller_suffix');
$actionController =... | 获取要执行的控制器类名及方法 | entailment |
private function findAction(&$pathInfo, &$path)
{
if ($pathInfo[0] == '/' && !isset($pathInfo[1])) {
$pathInfo = explode('/', trim(Config::get('url_default_action'), '/'));
}
$controllerPath = $controllerName = '';
$routeAppHierarchy = Config::get('route_app_hierarchy', ... | 从文件查找控制器
@param array $pathInfo
@param string $path | entailment |
public function get($pattern, $action)
{
self::$rules[self::REQUEST_METHOD_GET . self::patternFactory($pattern)] = $action;
return $this;
} | 增加get访问方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
public function post($pattern, $action)
{
self::$rules[self::REQUEST_METHOD_POST . self::patternFactory($pattern)] = $action;
return $this;
} | 增加post访问方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
public function put($pattern, $action)
{
self::$rules[self::REQUEST_METHOD_PUT . self::patternFactory($pattern)] = $action;
return $this;
} | 增加put访问方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
public function patch($pattern, $action)
{
self::$rules[self::REQUEST_METHOD_PATCH . self::patternFactory($pattern)] = $action;
return $this;
} | 增加patch访问方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
public function delete($pattern, $action)
{
self::$rules[self::REQUEST_METHOD_DELETE . self::patternFactory($pattern)] = $action;
return $this;
} | 增加delete访问方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
public function options($pattern, $action)
{
self::$rules[self::REQUEST_METHOD_OPTIONS . self::patternFactory($pattern)] = $action;
return $this;
} | 增加options访问方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
public function any($pattern, $action)
{
self::$rules[self::REQUEST_METHOD_ANY . self::patternFactory($pattern)] = $action;
return $this;
} | 增加任意访问方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
public function rest($pattern, $action)
{
self::$rules[self::REST_ROUTE . self::patternFactory($pattern)] = $action;
return $this;
} | 增加REST方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
public function group($namespace, callable $func)
{
if (empty($namespace)) {
throw new \InvalidArgumentException(Lang::get('_NOT_ALLOW_EMPTY_', '$namespace'));
}
self::$group = trim($namespace, '/');
$func();
self::$group = false;
} | 分组路由
@param string $namespace 分组名
@param callable $func 闭包 | entailment |
public function resolve(
AbsolutePathInterface $basePath,
PathInterface $path
) {
if ($path instanceof AbsolutePathInterface) {
return $path;
}
return $basePath->join($path);
} | Resolve a path against a given base path.
@param AbsolutePathInterface $basePath The base path.
@param PathInterface $path The path to resolve.
@return AbsolutePathInterface The resolved path. | entailment |
public function create($path)
{
if ('' === $path) {
$path = AbstractPath::SELF_ATOM;
}
$isAbsolute = false;
$hasTrailingSeparator = false;
$atoms = explode(AbstractPath::ATOM_SEPARATOR, $path);
$numAtoms = count($atoms);
if ($numAtoms > 1) {
... | Creates a new path instance from its string representation.
@param string $path The string representation of the path.
@return PathInterface The newly created path instance. | entailment |
public function createFromAtoms(
$atoms,
$isAbsolute = null,
$hasTrailingSeparator = null
) {
if (null === $isAbsolute) {
$isAbsolute = false;
}
if ($isAbsolute) {
return new AbsolutePath($atoms, $hasTrailingSeparator);
}
retu... | Creates a new path instance from a set of path atoms.
@param mixed<string> $atoms The path atoms.
@param boolean|null $isAbsolute True if the path is absolute.
@param boolean|null $hasTrailingSeparator True if the path has a trailing separator.
@return PathInterface The ... | entailment |
public function createTemporaryPath($prefix = null)
{
if (null === $prefix) {
$prefix = '';
}
return $this->createTemporaryDirectoryPath()
->joinAtoms($this->isolator()->uniqid($prefix, true));
} | Create a path representing a suitable for use as the location for a new
temporary file or directory.
This path is not guaranteed to be unused, but collisions are fairly
unlikely.
@param string|null $prefix A string to use as a prefix for the path name.
@return AbsoluteFileSystemPathInterface A new path instance repr... | entailment |
final public function runAppController($method)
{
//检测csrf跨站攻击
Secure::checkCsrf(Config::get('check_csrf'));
// 关闭GPC过滤 防止数据的正确性受到影响 在db层防注入
if (get_magic_quotes_gpc()) {
Secure::stripslashes($_GET);
Secure::stripslashes($_POST);
Secure::stripslas... | 运行对应的控制器
@param string $method 要执行的控制器方法
@return void | entailment |
public function write($text, $option = [])
{
Output::write($this->format($text, $option));
return $this;
} | 格式化输出
@param string $text 要输出的内容
@param array $option 格式化选项 @see Format
@return $this | entailment |
public function writeln($text, $option = [])
{
Output::writeln($this->format($text, $option));
return $this;
} | 格式化输出
@param string $text 要输出的内容
@param array $option 格式化选项 @see Format
@return $this | entailment |
public function log($level, $message, array $context = [])
{
return Model::getInstance()->cache(Config::get('redis_log_use_cache'))->getInstance()->lPush(
Config::get('log_prefix') . '_' . $level,
$this->format($message, $context)
);
} | 任意等级的日志记录
@param mixed $level 日志等级
@param string $message 要记录到log的信息
@param array $context 上下文信息
@return null | entailment |
private function addLocationsToMenu(ItemInterface $menu, array $searchHits)
{
foreach ($searchHits as $searchHit) {
/** @var Location $location */
$location = $searchHit->valueObject;
$menuItem = isset($menu[$location->parentLocationId]) ? $menu[$location->parentLocationI... | Adds locations from $searchHit to $menu.
@param ItemInterface $menu
@param SearchHit[] $searchHits | entailment |
private function getMenuItems($rootLocationId)
{
$rootLocation = $this->locationService->loadLocation($rootLocationId);
$query = new LocationQuery();
$query->query = new Criterion\LogicalAnd(
array(
new Criterion\ContentTypeIdentifier($this->getTopMenuContentTyp... | Queries the repository for menu items, as locations filtered on the list in TopIdentifierList in menu.ini.
@param int|string $rootLocationId Root location for menu items. Only two levels below this one are searched
@return SearchHit[] | entailment |
public static function prettifyTableName($table, $prefix = '')
{
if ($prefix) {
$table = self::removePrefix($table, $prefix);
}
return self::underscoresToCamelCase($table, true);
} | Convert a mysql table name to a class name, optionally removing a prefix.
@param $table
@param string $prefix
@return mixed | entailment |
public static function underscoresToCamelCase($string, $capitalizeFirstChar = false)
{
$str = str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
if (!empty($str) && !$capitalizeFirstChar) {
$str[0] = strtolower($str[0]);
}
return $str;
} | Convert underscores to CamelCase
borrowed from http://stackoverflow.com/a/2792045.
@param $string
@param bool $capitalizeFirstChar
@return mixed | entailment |
public static function strContains($needles, $haystack)
{
if (!is_array($needles)) {
$needles = (array) $needles;
}
foreach ($needles as $needle) {
if (strpos($haystack, $needle) !== false) {
return true;
}
}
return false;... | Check if a string (haystack) contains one or more words (needles).
@param $needles
@param $haystack
@return bool | entailment |
public static function implodeAndQuote($glue, $pieces)
{
foreach ($pieces as &$piece) {
$piece = self::singleQuote($piece);
}
unset($piece);
return implode($glue, $pieces);
} | Add a single quote to all pieces, then implode with the given glue.
@param $glue
@param $pieces
@return string | entailment |
public static function safePlural($value)
{
$plural = str_plural($value);
if ($plural == $value) {
$plural = $value.'s';
echo 'warning: automatic pluralization of '.$value.' failed, using '.$plural.LF;
}
return $plural;
} | Use laravel pluralization, and if that one fails give a warning and just append "s".
@param $value
@return string | entailment |
public function prepend(ContainerBuilder $container)
{
// Add legacy bundle settings only if it's present.
if ($container->hasExtension('ez_publish_legacy')) {
$legacyConfigFile = __DIR__ . '/../Resources/config/legacy_settings.yml';
$config = Yaml::parse(file_get_contents($l... | Loads DemoBundle configuration.
@param ContainerBuilder $container | entailment |
public function execute(array $args, array $options = [])
{
$this->bootstrap($args, $options);
$version = isset($options['target']) ? $options['target'] : $options['t'];
$removeAll = isset($options['remove-all']) ? $options['remove-all'] : $options['r'];
if ($version && $removeAll)... | Toggle the breakpoint.
@param array $args 参数
@param array $options 选项 | entailment |
private static function createKey($key)
{
$key = is_null($key) ? Config::get("auth_key") : $key;
self::$auth_key = md5($key /*. $_SERVER['HTTP_USER_AGENT']*/);
} | 生成加密KEY
@param string $key
@return void | entailment |
private static function cry($string, $type, $key)
{
self::createKey($key);
$type == 2 && $string = str_replace(['___a', '___b', '___c'], ['/', '+', '='], $string);
$string = $type == 2 ? base64_decode($string) : substr(md5(self::$auth_key . $string), 0, 8) . $string;
$str_len = strl... | 位加密或解密
@param string $string 加密或解密内容
@param int $type 类型:1加密 2解密
@param string $key
@return mixed | entailment |
public static function encrypt($data, $key = null)
{
is_null($key) && $key = Config::get('auth_key');
return self::cry(serialize($data), 1, $key);
} | 加密方法
@param string $data 加密字符串
@param string $key 密钥
@return mixed | entailment |
public static function decrypt($data, $key = null)
{
is_null($key) && $key = Config::get('auth_key');
return unserialize(self::cry($data, 2, $key));
} | 解密方法
@param string $data 解密字符串
@param string $key 密钥
@return mixed | entailment |
public function lock($key, $wouldBlock = false)
{
if (empty($key)) {
return false;
}
$key = $this->getKey($key);
if (
isset($this->lockCache[$key])
&& $this->lockCache[$key] == Model::getInstance()->cache($this->useCache)->getInstance()->get($key)... | 上锁
@param string $key 要上的锁的key
@param bool $wouldBlock 是否堵塞
@return mixed | entailment |
public function buildModel($table, $baseModel, $describes, $foreignKeys, $namespace = '', $prefix = '')
{
$this->table = StringUtils::removePrefix($table, $prefix);
$this->baseModel = $baseModel;
$this->foreignKeys = $this->filterAndSeparateForeignKeys($foreignKeys['all'], $table);
$... | First build the model.
@param $table
@param $baseModel
@param $describes
@param $foreignKeys
@param string $namespace
@param string $prefix | entailment |
public function createModel()
{
$file = '<?php'.$this->namespace.LF.LF;
$file .= '/**'.LF;
$file .= ' * Eloquent class to describe the '.$this->table.' table'.LF;
$file .= ' *'.LF;
$file .= ' * automatically generated by ModelGenerator.php'.LF;
$file .= ' */'.LF;
... | Secondly, create the model. | entailment |
protected function getTimestampFields($model)
{
try {
$baseModel = new ReflectionClass($model);
$timestampFields = [
'created_at' => $baseModel->getConstant('CREATED_AT'),
'updated_at' => $baseModel->getConstant('UPDATED_AT'),
'deleted_... | Detect if we have timestamp field
TODO: not sure about this one yet.
@param $model
@return array | entailment |
protected function filterAndSeparateForeignKeys($foreignKeys, $table)
{
$results = ['local' => [], 'remote' => []];
foreach ($foreignKeys as $foreignKey) {
if ($foreignKey->TABLE_NAME == $table) {
$results['local'][] = $foreignKey;
}
if ($foreignKe... | Only show the keys where table is mentioned.
@param $foreignKeys
@param $table
@return array | entailment |
public function userLinksAction()
{
$response = new Response();
$response->setSharedMaxAge(3600);
$response->setVary('Cookie');
return $this->render(
'eZDemoBundle::page_header_links.html.twig',
array(),
$response
);
} | Renders page header links with cache control.
@return \Symfony\Component\HttpFoundation\Response | entailment |
public function showArticleAction(View $view)
{
$view->addParameters(
[
'showSummary' => $this->container->getParameter('ezdemo.article.full_view.show_summary'),
'showImage' => $this->container->getParameter('ezdemo.article.full_view.show_image'),
]
... | Renders article with extra parameters that controls page elements visibility such as image and summary.
@param \eZ\Publish\Core\MVC\Symfony\View\View $view
@return \Symfony\Component\HttpFoundation\Response | entailment |
public function listBlogPostsAction(ContentView $view, Request $request)
{
$viewParameters = $request->attributes->get('viewParameters');
// This could be changed to use dynamic parameters injection
$languages = $this->getConfigResolver()->getParameter('languages');
// Using the cr... | Displays the list of blog_post
Note: This is a fully customized controller action, it will generate the response and call
the view. Since it is not calling the ViewControler we don't need to match a specific
method signature.
@param \eZ\Publish\Core\MVC\Symfony\View\ContentView $view
@param \Symfony\Component\HttpFoun... | entailment |
public function showBlogPostAction(ContentView $view)
{
$author = $this->getRepository()->getUserService()->loadUser($view->getContent()->contentInfo->ownerId);
$view->addParameters(['author' => $author]);
return $view;
} | Action used to display a blog_post
- Adds the content's author to the response.
Note: This is a partly customized controller action. It is executed just before the original
Viewcontroller's viewLocation method. To be able to do that, we need to implement it's
full signature.
@param ContentView $view
@return View | entailment |
public function viewParentExtraInfoAction(Location $location)
{
$repository = $this->getRepository();
$parentLocation = $repository->getLocationService()->loadLocation($location->parentLocationId);
// TODO once the keyword service is available replace part this subrequest by a full symfony ... | Displays description, tagcloud, tags, ezarchive and calendar
of the parent's of a given location.
@param \eZ\Publish\API\Repository\Values\Content\Location $location
@return \Symfony\Component\HttpFoundation\Response | entailment |
public function viewBreadcrumbAction(Location $location)
{
/** @var WhiteOctober\BreadcrumbsBundle\Templating\Helper\BreadcrumbsHelper $breadcrumbs */
$breadcrumbs = $this->get('white_october_breadcrumbs');
$locationService = $this->getRepository()->getLocationService();
$path = $lo... | Displays breadcrumb for a given $locationId.
@param \eZ\Publish\API\Repository\Values\Content\Location $location
@return \Symfony\Component\HttpFoundation\Response | entailment |
public function increment($value = 1)
{
$this->percent += $value;
$percentage = (double)($this->percent / 100);
$progress = floor($percentage * 50);
$output = "\r[" . str_repeat('>', $progress);
if ($progress < 50) {
$output .= ">" . str_repeat(' ', 50 - $progre... | 进入+ x
@param int $value
@return $this | entailment |
public static function colour($text, $foregroundColors = null, $backgroundColors = null)
{
if (self::$noAnsi) {
return $text;
}
$colour = function ($text) use ($foregroundColors, $backgroundColors) {
$colors = [];
if ($backgroundColors) {
... | 返回格式化后的字符串
@param string $text 要着色的文本
@param string|array|int $foregroundColors 前景色 eg: red、red+highlight、Colors::BLACK、[Colors::BLACK, Colors::HIGHLIGHT]
@param string|int $backgroundColors 背景色
@return string | entailment |
private static function charToCode($color)
{
if (is_array($color)) {
return $color;
} else if (is_string($color)) {
list($color, $option) = explode('+', strtolower($color));
if (!isset(self::$colors[$color])) {
throw new \InvalidArgumentException("... | 返回颜色对应的数字编码
@param int|string|array $color
@return array | entailment |
public static function fromString($path)
{
$pathObject = static::factory()->create($path);
if (!$pathObject instanceof RelativePathInterface) {
throw new Exception\NonRelativePathException($pathObject);
}
return $pathObject;
} | Creates a new relative path instance from its string representation.
@param string $path The string representation of the relative path.
@return RelativePathInterface The newly created relative path instance.
@throws Exception\NonRelativePathException If the supplied string represents a non-relative path... | entailment |
protected function normalizeAtoms($atoms)
{
$atoms = parent::normalizeAtoms($atoms);
if (count($atoms) < 1) {
throw new Exception\EmptyPathException;
}
return $atoms;
} | Normalizes and validates a sequence of path atoms.
This method is called internally by the constructor upon instantiation.
It can be overridden in child classes to change how path atoms are
normalized and/or validated.
@param mixed<string> $atoms The path atoms to normalize.
@return array<string> ... | entailment |
public static function fromDriveAndAtoms(
$atoms,
$drive = null,
$isAnchored = null,
$hasTrailingSeparator = null
) {
return static::factory()->createFromDriveAndAtoms(
$atoms,
$drive,
false,
$isAnchored,
$hasTrailin... | Creates a new relative Windows path from a set of path atoms and a drive
specifier.
@param mixed<string> $atoms The path atoms.
@param string|null $drive The drive specifier.
@param boolean|null $isAnchored True if the path is anchored to the drive root.
@param boolean|null ... | entailment |
public function matchesDriveOrNull($drive)
{
return null === $drive ||
!$this->hasDrive() ||
$this->driveSpecifiersMatch($this->drive(), $drive);
} | Returns true if this path's drive specifier matches the supplied drive
specifier, or if either drive specifier is null.
This method is not case sensitive.
@param string|null $drive The driver specifier to compare to.
@return boolean True if the drive specifiers match, or either drive specifier is null. | entailment |
public function joinDrive($drive)
{
if (null === $drive) {
return $this->createPathFromDriveAndAtoms(
$this->atoms(),
null,
false,
$this->isAnchored(),
false
);
}
return $this->createPath... | Joins the supplied drive specifier to this path.
@return string|null $drive The drive specifier to use, or null to remove the drive specifier.
@return WindowsPathInterface A new path instance with the supplied drive specifier joined to this path. | entailment |
public function string()
{
return
($this->hasDrive() ? $this->drive() . ':' : '') .
($this->isAnchored() ? static::ATOM_SEPARATOR : '') .
implode(static::ATOM_SEPARATOR, $this->atoms()) .
($this->hasTrailingSeparator() ? static::ATOM_SEPARATOR : '');
} | Generate a string representation of this path.
@return string A string representation of this path. | entailment |
public function join(RelativePathInterface $path)
{
if ($path instanceof RelativeWindowsPathInterface) {
if (!$this->matchesDriveOrNull($this->pathDriveSpecifier($path))) {
throw new Exception\DriveMismatchException(
$this->drive(),
$path->... | Joins the supplied path to this path.
@param RelativePathInterface $path The path whose atoms should be joined to this path.
@return PathInterface A new path with the supplied path suffixed to this path.
@throws Exception\DriveMismatchException If the supplied path has a drive that does not match t... | entailment |
public function toAbsolute()
{
if (!$this->hasDrive()) {
throw new InvalidPathStateException(
'Cannot convert relative Windows path to absolute without a ' .
'drive specifier.'
);
}
return $this->createPathFromDriveAndAtoms(
... | Get an absolute version of this path.
If this path is relative, a new absolute path with equivalent atoms will
be returned. Otherwise, this path will be retured unaltered.
@return AbsolutePathInterface An absolute version of this path.
@throws InvalidPathStateException If absolute conversion is not possible for t... | entailment |
protected function validateAtom($atom)
{
parent::validateAtom($atom);
if (false !== strpos($atom, '\\')) {
throw new PathAtomContainsSeparatorException($atom);
} elseif (preg_match('/([\x00-\x1F<>:"|?*])/', $atom, $matches)) {
throw new InvalidPathAtomCharacterExcept... | Validates a single path atom.
This method is called internally by the constructor upon instantiation.
It can be overridden in child classes to change how path atoms are
validated.
@param string $atom The atom to validate.
@throws InvalidPathAtomExceptionInterface If an invalid path atom is encountered. | entailment |
public function ask($question, $isHidden = false, $default = '', $displayDefault = true)
{
if ($displayDefault && !empty($default)) {
$defaultText = $default;
if (strlen($defaultText) > 30) {
$defaultText = substr($default, 0, 30) . '...';
}
$q... | 提问并获取用户输入
@param string $question 问题
@param bool $isHidden 是否要隐藏输入
@param string $default 默认答案
@param bool $displayDefault 是否显示默认答案
@return string | entailment |
private function askHidden()
{
if ('\\' === DIRECTORY_SEPARATOR) {
$exe = __DIR__ . '/bin/hiddeninput.exe';
// handle code running from a phar
if ('phar:' === substr(__FILE__, 0, 5)) {
$tmpExe = sys_get_temp_dir() . '/hiddeninput.exe';
cop... | 隐藏输入如密码等
@return string | entailment |
public function confirm($question, array $choices = ['Y', 'n'], $answer = 'y', $default = 'y', $errorMessage = 'Invalid choice')
{
$text = $question . ' [' . implode('/', $choices) . ']';
$choices = array_map('strtolower', $choices);
$answer = strtolower($answer);
$default = strtolow... | 确认对话框
<code>
if($dialog->confirm('Are you sure?')) { ... }
if($dialog->confirm('Your choice?', null, ['a', 'b', 'c'])) { ... }
</code>
@param string $question 问题
@param array $choices 选项
@param string $answer 通过的答案
@param string $default 默认选项
@param string $errorMessage 错误信息
@return bool | entailment |
public static function writeException($e)
{
if ($e instanceof \Exception) {
$text = sprintf("%s\n[%s]\n%s", $e->getFile() . ':' . $e->getLine(), get_class($e), $e->getMessage());
} else {
$text = $e;
}
$box = new Box($text, '*');
$out = Colour::colour... | 输出异常错误信息
@param mixed $e | entailment |
public function sendMail($mailTo, $mailSubject, $mailMessage)
{
$config = $this->config;
$mail_subject = '=?' . $config['charset'] . '?B?' . base64_encode($mailSubject) . '?=';
$mail_message = chunk_split(base64_encode(preg_replace("/(^|(\r\n))(\.)/", "\1.\3", $mailMessage)));
$head... | 发送邮件
@param string $mailTo 接收人
@param string $mailSubject 邮件主题
@param string $mailMessage 邮件内容
@return string|bool | entailment |
public function normalize(PathInterface $path)
{
if ($path instanceof AbsoluteWindowsPathInterface) {
return $this->normalizeAbsoluteWindowsPath($path);
}
return $this->normalizeRelativeWindowsPath($path);
} | Normalize the supplied path to its most canonical form.
@param PathInterface $path The path to normalize.
@return PathInterface The normalized path. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.