sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function normalizeAbsoluteWindowsPath(
AbsoluteWindowsPathInterface $path
) {
return $this->factory()->createFromDriveAndAtoms(
$this->normalizeAbsolutePathAtoms($path->atoms()),
$this->normalizeDriveSpecifier($path->drive()),
true,
false,
false
);
} | Normalize an absolute Windows path.
@param AbsoluteWindowsPathInterface $path The path to normalize.
@return AbsoluteWindowsPathInterface The normalized path. | entailment |
protected function normalizeRelativeWindowsPath(
RelativeWindowsPathInterface $path
) {
if ($path->isAnchored()) {
$atoms = $this->normalizeAbsolutePathAtoms($path->atoms());
} else {
$atoms = $this->normalizeRelativePathAtoms($path->atoms());
}
return $this->factory()->createFromDriveAndAtoms(
$atoms,
$this->normalizeDriveSpecifier($path->drive()),
false,
$path->isAnchored(),
false
);
} | Normalize a relative Windows path.
@param RelativeWindowsPathInterface $path The path to normalize.
@return RelativeWindowsPathInterface The normalized path. | entailment |
public function execute(array $args, array $options = [])
{
$this->bootstrap($args, $options);
$seedSet = isset($options['seed']) ? $options['seed'] : $options['s'];
$start = microtime(true);
if (empty($seedSet)) {
// run all the seed(ers)
$this->getManager()->seed();
} else {
is_array($seedSet) || $seedSet = [$seedSet];
// run seed(ers) specified in a comma-separated list of classes
foreach ($seedSet as $seed) {
$this->getManager()->seed(trim($seed));
}
}
$end = microtime(true);
Output::writeln('');
Output::writeln(Colour::colour('All Done. Took ' . sprintf('%.4fs', $end - $start), Colour::GREEN));
} | 执行 seeders.
@param array $args 参数
@param array $options 选项 | entailment |
public static function fromDriveAndAtoms(
$drive,
$atoms,
$hasTrailingSeparator = null
) {
return static::factory()->createFromDriveAndAtoms(
$atoms,
$drive,
true,
false,
$hasTrailingSeparator
);
} | Creates a new absolute Windows path from a set of path atoms and a drive
specifier.
@param string $drive The drive specifier.
@param mixed<string> $atoms The path atoms.
@param boolean|null $hasTrailingSeparator True if the path has a trailing separator.
@return AbsoluteWindowsPathInterface The newly created path instance.
@throws InvalidPathAtomExceptionInterface If any of the supplied atoms are invalid. | entailment |
public function joinDrive($drive)
{
if (null === $drive) {
return $this->createPathFromDriveAndAtoms(
$this->atoms(),
null,
false,
true,
false
);
}
return $this->createPathFromDriveAndAtoms(
$this->atoms(),
$drive,
true,
false,
false
);
} | 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 isParentOf(AbsolutePathInterface $path)
{
if (!$this->matchesDriveOrNull($this->pathDriveSpecifier($path))) {
return false;
}
return parent::isParentOf($path);
} | Determine if this path is the direct parent of the supplied path.
@param AbsolutePathInterface $path The child path.
@return boolean True if this path is the direct parent of the supplied path. | entailment |
public function isAncestorOf(AbsolutePathInterface $path)
{
if (!$this->matchesDriveOrNull($this->pathDriveSpecifier($path))) {
return false;
}
return parent::isAncestorOf($path);
} | Determine if this path is an ancestor of the supplied path.
@param AbsolutePathInterface $path The child path.
@return boolean True if this path is an ancestor of the supplied path. | entailment |
public function relativeTo(AbsolutePathInterface $path)
{
if (!$this->matchesDriveOrNull($this->pathDriveSpecifier($path))) {
return $this->toRelative();
}
return parent::relativeTo($path);
} | Determine the shortest path from the supplied path to this path.
For example, given path A equal to '/foo/bar', and path B equal to
'/foo/baz', A relative to B would be '../bar'.
@param AbsolutePathInterface $path The path that the generated path will be relative to.
@return RelativePathInterface A relative path from the supplied path to this path. | entailment |
public function string()
{
return
$this->drive() .
':' .
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 toRelative()
{
return $this->createPathFromDriveAndAtoms(
$this->atoms(),
$this->drive(),
false,
false,
false
);
} | Get a relative version of this path.
If this path is absolute, a new relative path with equivalent atoms will
be returned. Otherwise, this path will be retured unaltered.
@return RelativePathInterface A relative version of this path.
@throws EmptyPathException If this path has no atoms. | entailment |
protected function createPath(
$atoms,
$isAbsolute,
$hasTrailingSeparator = null
) {
if ($isAbsolute) {
return $this->createPathFromDriveAndAtoms(
$atoms,
$this->drive(),
true,
false,
$hasTrailingSeparator
);
}
return $this->createPathFromDriveAndAtoms(
$atoms,
null,
false,
false,
$hasTrailingSeparator
);
} | Creates a new path instance of the most appropriate type.
This method is called internally every time a new path instance is
created as part of another method call. It can be overridden in child
classes to change which classes are used when creating new path
instances.
@param mixed<string> $atoms The path atoms.
@param boolean $isAbsolute True if the new path should be absolute.
@param boolean|null $hasTrailingSeparator True if the new path should have a trailing separator.
@return PathInterface The newly created path instance. | entailment |
public static function levenshteinDistance($string1, $string2, $costReplace = 1, $encoding = 'UTF-8')
{
$mbStringToArrayFunc = function ($string) use ($encoding)
{
$arrayResult = [];
while ($iLen = mb_strlen($string, $encoding)) {
array_push($arrayResult, mb_substr($string, 0, 1, $encoding));
$string = mb_substr($string, 1, $iLen, $encoding);
}
return $arrayResult;
};
$countSameLetter = 0;
$d = [];
$mbLen1 = mb_strlen($string1, $encoding);
$mbLen2 = mb_strlen($string2, $encoding);
$mbStr1 = $mbStringToArrayFunc($string1, $encoding);
$mbStr2 = $mbStringToArrayFunc($string2, $encoding);
$maxCount = count($mbStr1) > count($mbStr2) ? count($mbStr1) : count($mbStr2);
for ($i1 = 0; $i1 <= $mbLen1; $i1++) {
$d[$i1] = [];
$d[$i1][0] = $i1;
}
for ($i2 = 0; $i2 <= $mbLen2; $i2++) {
$d[0][$i2] = $i2;
}
for ($i1 = 1; $i1 <= $mbLen1; $i1++) {
for ($i2 = 1; $i2 <= $mbLen2; $i2++) {
// $cost = ($str1[$i1 - 1] == $str2[$i2 - 1]) ? 0 : 1;
if ($mbStr1[$i1 - 1] === $mbStr2[$i2 - 1]) {
$cost = 0;
$countSameLetter++;
} else {
$cost = $costReplace; //替换
}
$d[$i1][$i2] = min($d[$i1 - 1][$i2] + 1, //插入
$d[$i1][$i2 - 1] + 1, //删除
$d[$i1 - 1][$i2 - 1] + $cost);
}
}
$percent = round(($maxCount - $d[$mbLen1][$mbLen2]) / $maxCount, 2);
//return $d[$mbLen1][$mbLen2];
return ['distance' => $d[$mbLen1][$mbLen2], 'count_same_letter' => $countSameLetter, 'percent' => $percent];
} | 计算两个字符串间的levenshteinDistance
@param string $string1
@param string $string2
@param int $costReplace 定义替换次数
@param string $encoding
@return mixed | entailment |
public static function substrCn($string, $start = 0, $length, $charset = "utf-8", $suffix = '')
{
if (function_exists("mb_substr")){
return mb_substr($string, $start, $length, $charset).$suffix;
} elseif (function_exists('iconv_substr')) {
return iconv_substr($string, $start, $length, $charset).$suffix;
}
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $string, $match);
$slice = join("",array_slice($match[0], $start, $length));
return $slice.$suffix;
} | 字符串截取,支持中文和其他编码
@param string $string 需要转换的字符串
@param int $start 开始位置
@param int $length 截取长度
@param string $charset 编码格式
@param string $suffix 截断字符串后缀
@return string | entailment |
public static function randString($len = 6, $type = 0, $addChars = '')
{
$string = '';
switch ($type) {
case 0:
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
break;
case 1:
$chars = str_repeat('0123456789',3);
break;
case 2:
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
break;
case 3:
$chars = 'abcdefghijklmnopqrstuvwxyz'.$addChars;
break;
case 4:
$chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借".$addChars;
break;
default :
// 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数
$chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
break;
}
if ($len > 10 ) {//位数过长重复字符串一定次数
$chars = $type == 1 ? str_repeat($chars,$len) : str_repeat($chars, 5);
}
if ($type != 4) {
$chars = str_shuffle($chars);
$string = substr($chars, 0, $len);
} else {
// 中文 需要php_mbstring扩展支持
for ($i = 0; $i < $len; $i++){
$string .= self::substrCn($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1, 'utf-8', false);
}
}
return $string;
} | 产生随机字串 //中文 需要php_mbstring扩展支持
默认长度6位 字母和数字混合 支持中文
@param int $len 长度
@param int $type 字串类型 0 字母 1 数字 其它 混合
@param string $addChars 自定义一部分字符
@return string | entailment |
public function set($key, $value, $expire = 0)
{
($expire == 0) && $expire = null;
return apc_store($this->conf['prefix'] . $key, $value, $expire);
} | 存储对象
@param mixed $key 要缓存的数据的key
@param mixed $value 要缓存的值,除resource类型外的数据类型
@param int $expire 缓存的有效时间 0为不过期
@return bool | entailment |
public function update($key, $value, $expire = 0)
{
$arr = $this->get($key);
if (!empty($arr)) {
$arr = array_merge($arr, $value);
return $this->set($key, $arr, $expire);
}
return 0;
} | 更新对象
@param mixed $key 要更新的缓存的数据的key
@param mixed $value 要更新的要缓存的值,除resource类型外的数据类型
@param int $expire 缓存的有效时间 0为不过期
@return bool|int | entailment |
public function increment($key, $val = 1)
{
return apc_inc($this->conf['prefix'] . $key, abs(intval($val)));
} | 自增
@param mixed $key 要自增的缓存的数据的key
@param int $val 自增的进步值,默认为1
@return bool | entailment |
public function decrement($key, $val = 1)
{
return apc_dec($this->conf['prefix'] . $key, abs(intval($val)));
} | 自减
@param mixed $key 要自减的缓存的数据的key
@param int $val 自减的进步值,默认为1
@return bool | entailment |
public function showFeedbackFormAction(Request $request, ContentView $view)
{
// Creating a form using Symfony's form component
$feedback = new Feedback();
$form = $this->createForm($this->get('ezdemo.form.type.feedback'), $feedback);
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isValid()) {
/** @var EmailHelper $emailHelper */
$emailHelper = $this->get('ezdemo.email_helper');
$emailHelper->sendFeebackMessage(
$feedback,
$this->container->getParameter('ezdemo.feedback_form.email_from'),
$this->container->getParameter('ezdemo.feedback_form.email_to')
);
// Adding the confirmation flash message to the session
$this->get('session')->getFlashBag()->add(
'notice',
$this->get('translator')->trans('Thank you for your message, we will get back to you as soon as possible.')
);
return $this->redirect($this->generateUrl($view->getLocation()));
}
}
$view->addParameters(['form' => $form->createView()]);
return $view;
} | Displays the feedback form, and processes posted data.
The signature of this method follows the one from the default view controller, and adds the Request, since
we use to handle form data.
@param \Symfony\Component\HttpFoundation\Request $request
@param \eZ\Publish\Core\MVC\Symfony\View\ContentView $view
@return View | entailment |
private static function parseInputToString($params)
{
return is_array($params) ? array_map(function ($item) {
return trim(htmlspecialchars($item, ENT_QUOTES, 'UTF-8'));
}, $params) : trim(htmlspecialchars($params, ENT_QUOTES, 'UTF-8'));
} | 统一的处理输入-输出为字符串
@param array|string $params
@return array|string | entailment |
private static function parseInputToInt($params)
{
return is_array($params) ? array_map(function ($item) {
return intval($item);
}, $params) : intval($params);
} | 统一的处理输入-输出为整型
@param array|string $params
@return array|int | entailment |
private static function parseInputToBool($params)
{
return is_array($params) ? array_map(function ($item) {
return ((bool)$item);
}, $params) : ((bool)$params);
} | 统一的处理输入-输出为布尔型
@param array|string $params
@return array|bool | entailment |
private static function getReferParams($name)
{
static $params = null;
if (is_null($params)) {
if (isset($_SERVER['HTTP_REFERER'])) {
$args = parse_url($_SERVER['HTTP_REFERER']);
parse_str($args['query'], $params);
}
}
return isset($params[$name]) ? $params[$name] : null;
} | 获取解析后的Refer的参数
@param string $name 参数的key
@return mixed | entailment |
public static function getString($name, $default = null)
{
if (isset($_GET[$name]) && $_GET[$name] !== '') return self::parseInputToString($_GET[$name]);
return $default;
} | 获取get string数据
@param string $name 要获取的变量
@param null $default 未获取到$_GET值时返回的默认值
@return string|null|array | entailment |
public static function postString($name, $default = null)
{
if (isset($_POST[$name]) && $_POST[$name] !== '') return self::parseInputToString($_POST[$name]);
return $default;
} | 获取post string数据
@param string $name 要获取的变量
@param null $default 未获取到$_POST值时返回的默认值
@return string|null|array | entailment |
public static function requestString($name, $default = null)
{
if (isset($_REQUEST[$name]) && $_REQUEST[$name] !== '') return self::parseInputToString($_REQUEST[$name]);
return $default;
} | 获取$_REQUEST string数据
@param string $name 要获取的变量
@param null $default 未获取到$_REQUEST值时返回的默认值
@return null|string|array | entailment |
public static function referString($name, $default = null)
{
$res = self::getReferParams($name);
if (!is_null($res)) return self::parseInputToString($res);
return $default;
} | 获取Refer string数据
@param string $name 要获取的变量
@param null $default 未获取到Refer值时返回的默认值
@return null|string|array | entailment |
public static function getInt($name, $default = null)
{
if (isset($_GET[$name]) && $_GET[$name] !== '') return self::parseInputToInt($_GET[$name]);
return (is_null($default) ? null : intval($default));
} | 获取get int数据
@param string $name 要获取的变量
@param null $default 未获取到$_GET值时返回的默认值
@return int|null|array | entailment |
public static function postInt($name, $default = null)
{
if (isset($_POST[$name]) && $_POST[$name] !== '') return self::parseInputToInt($_POST[$name]);
return (is_null($default) ? null : intval($default));
} | 获取post int数据
@param string $name 要获取的变量
@param null $default 未获取到$_POST值时返回的默认值
@return int|null|array | entailment |
public static function requestInt($name, $default = null)
{
if (isset($_REQUEST[$name]) && $_REQUEST[$name] !== '') return self::parseInputToInt($_REQUEST[$name]);
return (is_null($default) ? null : intval($default));
} | 获取$_REQUEST int数据
@param string $name 要获取的变量
@param null $default 未获取到$_REQUEST值时返回的默认值
@return null|int|array | entailment |
public static function referInt($name, $default = null)
{
$res = self::getReferParams($name);
if (!is_null($res)) return self::parseInputToInt($res);
return (is_null($default) ? null : intval($default));
} | 获取Refer int数据
@param string $name 要获取的变量
@param null $default 未获取到Refer值时返回的默认值
@return null|string|array | entailment |
public static function getBool($name, $default = null)
{
if (isset($_GET[$name]) && $_GET[$name] !== '') return self::parseInputToBool($_GET[$name]);
return (is_null($default) ? null : ((bool)$default));
} | 获取get bool数据
@param string $name 要获取的变量
@param null $default 未获取到$_GET值时返回的默认值
@return bool|null|array | entailment |
public static function postBool($name, $default = null)
{
if (isset($_POST[$name]) && $_POST[$name] !== '') return self::parseInputToBool($_POST[$name]);
return (is_null($default) ? null : ((bool)$default));
} | 获取post bool数据
@param string $name 要获取的变量
@param null $default 未获取到$_POST值时返回的默认值
@return bool|null|array | entailment |
public static function requestBool($name, $default = null)
{
if (isset($_REQUEST[$name]) && $_REQUEST[$name] !== '') return self::parseInputToBool($_REQUEST[$name]);
return (is_null($default) ? null : ((bool)$default));
} | 获取$_REQUEST bool数据
@param string $name 要获取的变量
@param null $default 未获取到$_REQUEST值时返回的默认值
@return null|bool|array | entailment |
public static function referBool($name, $default = null)
{
$res = self::getReferParams($name);
if (!is_null($res)) return self::parseInputToBool($res);
return (is_null($default) ? null : ((bool)$default));
} | 获取Refer bool数据
@param string $name 要获取的变量
@param null $default 未获取到Refer值时返回的默认值
@return null|string|array | entailment |
public static function get($name)
{
if (!self::isExist($name)) return false;
$value = $_COOKIE[Config::get('cookie_prefix') . $name];
return Encry::decrypt($value);
} | 获取某个Cookie值
@param string $name 要获取的cookie名称
@return bool|mixed | entailment |
public static function set($name, $value, $expire = 0, $path = '', $domain = '')
{
empty($expire) && $expire = Config::get('cookie_expire');
empty($path) && $path = Config::get('cookie_path');
empty($domain) && $domain = Config::get('cookie_domain');
$expire = empty($expire) ? 0 : Cml::$nowTime + $expire;
$value = Encry::encrypt($value);
setcookie(Config::get('cookie_prefix') . $name, $value, $expire, $path, $domain);
$_COOKIE[Config::get('cookie_prefix') . $name] = $value;
} | 设置某个Cookie值
@param string $name 要设置的cookie的名称
@param mixed $value 要设置的值
@param int $expire 过期时间
@param string $path path
@param string $domain domain
@return void | entailment |
public static function delete($name, $path = '', $domain = '')
{
self::set($name, '', -3600, $path, $domain);
unset($_COOKIE[Config::get('cookie_prefix') . $name]);
} | 删除某个Cookie值
@param string $name 要删除的cookie的名称
@param string $path path
@param string $domain domain
@return void | entailment |
public function itHasATextSpanLinkedTo($text, $link)
{
$this->assertSession()->pageTextContains($text);
Assertion::assertCount(
1,
$this->getXpath()->findXpath(sprintf('//a[@href="%s"]/span[text()="%s"]', $link, $text))
);
} | Tests that the page contains a specific link with a specific text (the text must be within a span).
@Then It has the text :text in a span linked to :link
@Then I see the text :text in a span linked to :link | entailment |
public function breadcrumbHasTheFollowingLinks(TableNode $table)
{
foreach ($table->getTable() as $breadcrumbItem) {
$text = $breadcrumbItem[0];
$url = $breadcrumbItem[1];
// this is not a link (the current page)
if ($url === 'null') {
$query = sprintf(
'//ul[@id="wo-breadcrumbs"]/li/span[text()="%s"]',
$text
);
} else {
$query = sprintf(
'//ul[@id="wo-breadcrumbs"]/li/a[@href="%s"]/span[text()="%s"]',
$url,
$text
);
}
Assertion::assertCount(
1, $this->getXpath()->findXpath($query)
);
}
} | Tests if a link is present in the breadcrumbs.
@Then the breadcrumb has the following links: | entailment |
public function iShouldSeeAVailidThumbnailForImageWithAlternativeText($imageAlternativeText)
{
$image = $this->getXpath()->findXpath("//img[contains(@alt, '" . $imageAlternativeText . "')]");
if (count($image) == 0) {
throw new \Exception(sprintf('Image with an alternative text `%s` was not found', $imageAlternativeText));
}
$file = $image[0]->getAttribute('src');
$client = new \Guzzle\Http\Client();
$request = $client->get($this->locatePath($file));
$response = $request->send();
Assertion::equalTo(
$response->getStatusCode(), 200
);
Assertion::assertRegexp(
'/image\/(.*)/', $response->getHeader('content-type')->__toString()
);
} | Test if image is present on page and is downloadable (`img` tag must contain `alt` attribute).
@Then I (should) see a valid thumbnail for image with alternative text :imageAlternativeText | entailment |
public function bootstrap(array $args, array $options = [])
{
if (false === class_exists('\Phinx\Config\Config')) {
throw new \RuntimeException('please use `composer require linhecheng/cmlphp-ext-phinx` cmd to install phinx.');
}
if (!$this->getConfig()) {
$this->loadConfig($options);
}
$this->loadManager($args, $options);
// report the paths
Output::writeln(
'using migration path ' .
Colour::colour(str_replace(Cml::getApplicationDir('secure_src'), '{secure_src}', $this->getConfig()->getMigrationPath()), Colour::GREEN)
);
Output::writeln(
'using seed path ' .
Colour::colour(str_replace(Cml::getApplicationDir('secure_src'), '{secure_src}', $this->getConfig()->getSeedPath()), Colour::GREEN)
);
$exportPath = false;
if (isset($options['e'])) {
$exportPath = $options['e'];
} else if (isset($options['export'])) {
$exportPath = $options['export'];
}
if ($exportPath) {
is_dir($exportPath) || $exportPath = $this->getConfig()->getExportPath();
is_dir($exportPath) || mkdir($exportPath, 0700, true);
Output::writeln(
'using export path:' .
Colour::colour(str_replace(Cml::getApplicationDir('secure_src'), '{secure_src}', $exportPath), Colour::GREEN)
);
$merge = (isset($options['m']) || isset($options['merge'])) ? 'merge_export_' . date('Y-m-d-H-i-s') . '.sql' : false;
$this->getManager()->getEnvironment()->setExportPath($exportPath, $merge);
}
$this->getConfig()->echoAdapterInfo();
} | Bootstrap Phinx.
@param array $args
@param array $options | entailment |
protected function loadConfig($options)
{
if (isset($options['env']) && !in_array($options['env'], ['cli', 'product', 'development'])) {
throw new \InvalidArgumentException('option --env\'s value must be [cli, product, development]');
}
$env = 'development';
isset($options['env']) && $env = $options['env'];
Output::writeln('using config -- ' . Colour::colour($env, Colour::GREEN));
$this->setConfig(new Config($env));
} | Parse the config file and load it into the config object
@param array $options 选项
@throws \InvalidArgumentException
@return void | entailment |
protected function loadManager($args, $options)
{
if (null === $this->getManager()) {
$manager = new Manager($this->getConfig(), $args, $options);
$this->setManager($manager);
}
} | Load the migrations manager and inject the config
@param array $args
@param array $options | entailment |
public function getTables()
{
$this->currentQueryIsMaster = false;
$stmt = $this->prepare('SHOW TABLES;', $this->rlink);
$this->execute($stmt);
$tables = [];
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$tables[] = $row['Tables_in_' . $this->conf['master']['dbname']];
}
return $tables;
} | 获取当前db所有表名
@return array | entailment |
public function getAllTableStatus()
{
$this->currentQueryIsMaster = false;
$stmt = $this->prepare('SHOW TABLE STATUS FROM ' . $this->conf['master']['dbname'], $this->rlink);
$this->execute($stmt);
$res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$return = [];
foreach ($res as $val) {
$return[$val['Name']] = $val;
}
return $return;
} | 获取当前数据库中所有表的信息
@return array | entailment |
public function getDbFields($table, $tablePrefix = null, $filter = 0)
{
static $dbFieldCache = [];
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
if ($filter == 1 && Cml::$debug) return '*'; //debug模式时直接返回*
$table = strtolower($tablePrefix . $table);
$info = false;
if (isset($dbFieldCache[$table])) {
$info = $dbFieldCache[$table];
} else {
Config::get('db_fields_cache') && $info = \Cml\simpleFileCache($this->conf['master']['dbname'] . '.' . $table);
if (!$info || Cml::$debug) {
$this->currentQueryIsMaster = false;
$stmt = $this->prepare("SHOW COLUMNS FROM $table", $this->rlink, false);
$this->execute($stmt, false);
$info = [];
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$info[$row['Field']] = [
'name' => $row['Field'],
'type' => $row['Type'],
'notnull' => (bool)($row['Null'] === ''), // not null is empty, null is yes
'default' => $row['Default'],
'primary' => (strtolower($row['Key']) == 'pri'),
'autoinc' => (strtolower($row['Extra']) == 'auto_increment'),
];
}
count($info) > 0 && \Cml\simpleFileCache($this->conf['master']['dbname'] . '.' . $table, $info);
}
$dbFieldCache[$table] = $info;
}
if ($filter) {
if (count($info) > 0) {
$info = implode('`,`', array_keys($info));
$info = '`' . $info . '`';
} else {
return '*';
}
}
return $info;
} | 获取表字段
@param string $table 表名
@param mixed $tablePrefix 表前缀,不传则获取配置中配置的前缀
@param int $filter 0 获取表字段详细信息数组 1获取字段以,号相隔组成的字符串
@return mixed | entailment |
public function get($key, $and = true, $useMaster = false, $tablePrefix = null)
{
if (is_string($useMaster) && is_null($tablePrefix)) {
$tablePrefix = $useMaster;
$useMaster = false;
}
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
list($tableName, $condition) = $this->parseKey($key, $and);
$tableName = $tablePrefix . $tableName;
$sql = "SELECT * FROM {$tableName} WHERE {$condition} LIMIT 0, 1000";
if ($this->openCache && $this->currentQueryUseCache) {
$cacheKey = md5($sql . json_encode($this->bindParams)) . $this->getCacheVer($tableName);
$return = Model::getInstance()->cache()->get($cacheKey);
} else {
$return = false;
}
if ($return === false) { //cache中不存在这条记录
$this->currentQueryIsMaster = $useMaster;
$stmt = $this->prepare($sql, $useMaster ? $this->wlink : $this->rlink);
$this->execute($stmt);
$return = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$this->openCache && $this->currentQueryUseCache && Model::getInstance()->cache()->set($cacheKey, $return, $this->conf['cache_expire']);
$this->currentQueryUseCache = true;
} else {
if (Cml::$debug) {
$this->currentSql = $sql;
$this->debugLogSql(Debug::SQL_TYPE_FROM_CACHE);
$this->currentSql = '';
}
$this->clearBindParams();
}
return $return;
} | 根据key取出数据
@param string $key get('user-uid-123');
@param bool $and 多个条件之间是否为and true为and false为or
@param bool|string $useMaster 是否使用主库 默认读取从库 此选项为字符串时为表前缀$tablePrefix
@param null|string $tablePrefix 表前缀
@return array | entailment |
public function set($table, $data, $tablePrefix = null)
{
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
$tableName = $tablePrefix . $table;
if (is_array($data)) {
$s = $this->arrToCondition($data);
$this->currentQueryIsMaster = true;
$stmt = $this->prepare("INSERT INTO {$tableName} SET {$s}", $this->wlink);
$this->execute($stmt);
$this->setCacheVer($tableName);
return $this->insertId();
} else {
return false;
}
} | 新增 一条数据
@param string $table 表名
@param array $data eg: ['username'=>'admin', 'email'=>'[email protected]']
@param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀
@return bool|int | entailment |
public function setMulti($table, $field, $data, $tablePrefix = null, $openTransAction = true)
{
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
$tableName = $tablePrefix . $table;
if (is_array($data) && is_array($field)) {
$field = array_flip(array_values($field));
foreach ($field as $key => $val) {
$field[$key] = $data[0][$val];
}
$s = $this->arrToCondition($field);
try {
$openTransAction && $this->startTransAction();
$this->currentQueryIsMaster = true;
$stmt = $this->prepare("INSERT INTO {$tableName} SET {$s}", $this->wlink);
$idArray = [];
foreach ($data as $row) {
$this->bindParams = array_values($row);
$this->execute($stmt);
$idArray[] = $this->insertId();
}
$openTransAction && $this->commit();
} catch (\InvalidArgumentException $e) {
$openTransAction && $this->rollBack();
throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
$this->setCacheVer($tableName);
return $idArray;
} else {
return false;
}
} | 新增多条数据
@param string $table 表名
@param array $field 字段 eg: ['title', 'msg', 'status', 'ctime‘]
@param array $data eg: 多条数据的值 [['标题1', '内容1', 1, '2017'], ['标题2', '内容2', 1, '2017']]
@param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀
@param bool $openTransAction 是否开启事务 默认开启
@throws \InvalidArgumentException
@return bool|array | entailment |
public function update($key, $data = null, $and = true, $tablePrefix = null)
{
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
$tableName = $condition = '';
if (is_array($data)) {
list($tableName, $condition) = $this->parseKey($key, $and, true, true);
} else {
$data = $key;
}
if (empty($tableName)) {
$tableAndCacheKey = $this->tableFactory(false);
$tableName = $tableAndCacheKey[0];
$upCacheTables = $tableAndCacheKey[1];
} else {
$tableName = $tablePrefix . $tableName;
$upCacheTables = [$tableName];
isset($this->forceIndex[$tableName]) && $tableName .= ' force index(' . $this->forceIndex[$tableName] . ') ';
}
if (empty($tableName)) {
throw new \InvalidArgumentException(Lang::get('_PARSE_SQL_ERROR_NO_TABLE_', 'update'));
}
$s = $this->arrToCondition($data);
$whereCondition = $this->sql['where'];
$whereCondition .= empty($condition) ? '' : (empty($whereCondition) ? 'WHERE ' : '') . $condition;
if (empty($whereCondition)) {
throw new \InvalidArgumentException(Lang::get('_PARSE_SQL_ERROR_NO_CONDITION_', 'update'));
}
$this->currentQueryIsMaster = true;
$stmt = $this->prepare("UPDATE {$tableName} SET {$s} {$whereCondition}", $this->wlink);
$this->execute($stmt);
foreach ($upCacheTables as $tb) {
$this->setCacheVer($tb);
}
return $stmt->rowCount();
} | 根据key更新一条数据
@param string|array $key eg: 'user'(表名)、'user-uid-$uid'(表名+条件) 、['xx'=>'xx' ...](即:$data数组如果条件是通用whereXX()、表名是通过table()设定。这边可以直接传$data的数组)
@param array | null $data eg: ['username'=>'admin', 'email'=>'[email protected]'] 可以直接通过$key参数传递
@param bool $and 多个条件之间是否为and true为and false为or
@param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀
@return boolean | entailment |
public function delete($key = '', $and = true, $tablePrefix = null)
{
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
$tableName = $condition = '';
empty($key) || list($tableName, $condition) = $this->parseKey($key, $and, true, true);
if (empty($tableName)) {
$tableAndCacheKey = $this->tableFactory(false);
$tableName = $tableAndCacheKey[0];
$upCacheTables = $tableAndCacheKey[1];
} else {
$tableName = $tablePrefix . $tableName;
$upCacheTables = [$tableName];
isset($this->forceIndex[$tableName]) && $tableName .= ' force index(' . $this->forceIndex[$tableName] . ') ';
}
if (empty($tableName)) {
throw new \InvalidArgumentException(Lang::get('_PARSE_SQL_ERROR_NO_TABLE_', 'delete'));
}
$whereCondition = $this->sql['where'];
$whereCondition .= empty($condition) ? '' : (empty($whereCondition) ? 'WHERE ' : '') . $condition;
if (empty($whereCondition)) {
throw new \InvalidArgumentException(Lang::get('_PARSE_SQL_ERROR_NO_CONDITION_', 'delete'));
}
$this->currentQueryIsMaster = true;
$limit = '';
if ($this->sql['limit']) {
$limit = explode(',', $this->sql['limit']);
$limit = 'LIMIT ' . $limit[1];
}
$stmt = $this->prepare("DELETE FROM {$tableName} {$whereCondition} {$limit}", $this->wlink);
$this->execute($stmt);
foreach ($upCacheTables as $tb) {
$this->setCacheVer($tb);
}
return $stmt->rowCount();
} | 根据key值删除数据
@param string|int $key eg: 'user'(表名,即条件通过where()传递)、'user-uid-$uid'(表名+条件)、啥也不传(即通过table传表名)
@param bool $and 多个条件之间是否为and true为and false为or
@param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀
@return boolean | entailment |
public function truncate($tableName)
{
$tableName = $this->tablePrefix . $tableName;
$this->currentQueryIsMaster = true;
$stmt = $this->prepare("TRUNCATE {$tableName}");
$this->setCacheVer($tableName);
return $stmt->execute();//不存在会报错,但无关紧要
} | 根据表名删除数据 这个操作太危险慎用。不过一般情况程序也没这个权限
@param string $tableName 要清空的表名
@return bool | entailment |
public function count($field = '*', $isMulti = false, $useMaster = false)
{
return $this->aggregation($field, $isMulti, $useMaster, 'COUNT');
} | 获取 COUNT(字段名或*) 的结果
@param string $field 要统计的字段名
@param bool|string $isMulti 结果集是否为多条 默认只有一条。传字符串时相当于执行了 groupBy($isMulti)
@param bool|string $useMaster 是否使用主库 默认读取从库
@return mixed | entailment |
public function max($field = 'id', $isMulti = false, $useMaster = false)
{
return $this->aggregation($field, $isMulti, $useMaster, 'MAX');
} | 获取 MAX(字段名) 的结果
@param string $field 要统计的字段名
@param bool|string $isMulti 结果集是否为多条 默认只有一条。传字符串时相当于执行了 groupBy($isMulti)
@param bool|string $useMaster 是否使用主库 默认读取从库
@return mixed | entailment |
private function aggregation($field, $isMulti = false, $useMaster = false, $operation = 'COUNT')
{
is_string($isMulti) && $this->groupBy($isMulti)->columns($isMulti);
$count = $this->columns(["{$operation}({$field})" => '__res__'])->select(null, null, $useMaster);
if ($isMulti) {
$return = [];
foreach ($count as $val) {
$return[$val[$isMulti]] = $operation === 'COUNT' ? intval($val['__res__']) : floatval($val['__res__']);
}
return $return;
} else {
return $operation === 'COUNT' ? intval($count[0]['__res__']) : floatval($count[0]['__res__']);
}
} | 获取max(字段名)的结果
@param string $field 要统计的字段名
@param bool|string $isMulti 结果集是否为多条 默认只有一条。传字符串时相当于执行了 groupBy($isMulti)
@param bool|string $useMaster 是否使用主库 默认读取从库
@param string $operation 聚合操作
@return mixed | entailment |
private function tableFactory($isRead = true)
{
$table = $operator = '';
$cacheKey = [];
foreach ($this->table as $key => $val) {
$realTable = $this->getRealTableName($key);
$cacheKey[] = $isRead ? $this->getCacheVer($realTable) : $realTable;
$on = null;
if (isset($this->join[$key])) {
$operator = ' INNER JOIN';
$on = $this->join[$key];
} elseif (isset($this->leftJoin[$key])) {
$operator = ' LEFT JOIN';
$on = $this->leftJoin[$key];
} elseif (isset($this->rightJoin[$key])) {
$operator = ' RIGHT JOIN';
$on = $this->rightJoin[$key];
} else {
empty($table) || $operator = ' ,';
}
if (is_null($val)) {
$table .= "{$operator} {$realTable}";
} else {
$table .= "{$operator} {$realTable} AS `{$val}`";
}
isset($this->forceIndex[$realTable]) && $table .= ' force index(' . $this->forceIndex[$realTable] . ') ';
is_null($on) || $table .= " ON {$on}";
}
if (empty($table)) {
throw new \InvalidArgumentException(Lang::get('_PARSE_SQL_ERROR_NO_TABLE_', $isRead ? 'select' : 'update/delete'));
}
return [$table, $cacheKey];
} | table组装工厂
@param bool $isRead 是否为读操作
@return array | entailment |
public function forceIndex($table, $index, $tablePrefix = null)
{
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
$this->forceIndex[$tablePrefix . $table] = $index;
return $this;
} | 强制使用索引
@param string $table 要强制索引的表名(不带前缀)
@param string $index 要强制使用的索引
@param string $tablePrefix 表前缀 不传则获取配置中配置的前缀
@return $this | entailment |
public function buildSql($offset = null, $limit = null, $isSelect = false)
{
is_null($offset) || $this->limit($offset, $limit);
$this->sql['columns'] == '' && ($this->sql['columns'] = '*');
$columns = $this->sql['columns'];
$tableAndCacheKey = $this->tableFactory();
empty($this->sql['limit']) && ($this->sql['limit'] = "LIMIT 0, 100");
$sql = "SELECT $columns FROM {$tableAndCacheKey[0]} " . $this->sql['where'] . $this->sql['groupBy'] . $this->sql['having']
. $this->sql['orderBy'] . $this->union . $this->sql['limit'];
if ($isSelect) {
return [$sql, $tableAndCacheKey[1]];
} else {
$this->currentSql = $sql;
$sql = $this->buildDebugSql();
$this->reset();
$this->clearBindParams();
$this->currentSql = '';
return " ({$sql}) ";
}
} | 构建sql
@param null $offset 偏移量
@param null $limit 返回的条数
@param bool $isSelect 是否为select调用, 是则不重置查询参数并返回cacheKey/否则直接返回sql并重置查询参数
@return string|array | entailment |
public function select($offset = null, $limit = null, $useMaster = false)
{
list($sql, $cacheKey) = $this->buildSql($offset, $limit, true);
if ($this->openCache && $this->currentQueryUseCache) {
$cacheKey = md5($sql . json_encode($this->bindParams)) . implode('', $cacheKey);
$return = Model::getInstance()->cache()->get($cacheKey);
} else {
$return = false;
}
if ($return === false) {
$this->currentQueryIsMaster = $useMaster;
$stmt = $this->prepare($sql, $useMaster ? $this->wlink : $this->rlink);
$this->execute($stmt);
$return = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$this->openCache && $this->currentQueryUseCache && Model::getInstance()->cache()->set($cacheKey, $return, $this->conf['cache_expire']);
$this->currentQueryUseCache = true;
} else {
if (Cml::$debug) {
$this->currentSql = $sql;
$this->debugLogSql(Debug::SQL_TYPE_FROM_CACHE);
$this->currentSql = '';
}
$this->reset();
$this->clearBindParams();
}
return $return;
} | 获取多条数据
@param int $offset 偏移量
@param int $limit 返回的条数
@param bool $useMaster 是否使用主库 默认读取从库
@return array | entailment |
public function insertId($link = null)
{
is_null($link) && $link = $this->wlink;
return $link->lastInsertId();
} | 获取上一INSERT的主键值
@param \PDO $link
@return int | entailment |
public function connect($host, $username, $password, $dbName, $charset = 'utf8', $engine = '', $pConnect = false)
{
$link = '';
try {
$host = explode(':', $host);
if (substr($host[0], 0, 11) === 'unix_socket') {
$dsn = "mysql:dbname={$dbName};unix_socket=" . substr($host[0], 12);
} else {
$dsn = "mysql:host={$host[0]};" . (isset($host[1]) ? "port={$host[1]};" : '') . "dbname={$dbName}";
}
if ($pConnect) {
$link = new \PDO($dsn, $username, $password, [
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset"
]);
} else {
$link = new \PDO($dsn, $username, $password, [
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset"
]);
}
} catch (\PDOException $e) {
throw new PdoConnectException(
'Pdo Connect Error! {' .
$host[0] . (isset($host[1]) ? ':' . $host[1] : '') . ', ' . $dbName .
'} Code:' . $e->getCode() . ', ErrorInfo!:' . $e->getMessage(),
0,
$e
);
}
//$link->exec("SET names $charset");
isset($this->conf['sql_mode']) && $link->exec('set sql_mode="' . $this->conf['sql_mode'] . '";'); //放数据库配 特殊情况才开
if (!empty($engine) && $engine == 'InnoDB') {
$link->exec('SET innodb_flush_log_at_trx_commit=2');
}
return $link;
} | Db连接
@param string $host 数据库host
@param string $username 数据库用户名
@param string $password 数据库密码
@param string $dbName 数据库名
@param string $charset 字符集
@param string $engine 引擎
@param bool $pConnect 是否为长连接
@return mixed | entailment |
public function increment($key, $val = 1, $field = null, $tablePrefix = null)
{
list($tableName, $condition) = $this->parseKey($key, true);
if (is_null($field) || empty($tableName) || empty($condition)) {
$this->clearBindParams();
return false;
}
$val = abs(intval($val));
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
$tableName = $tablePrefix . $tableName;
$this->currentQueryIsMaster = true;
$stmt = $this->prepare('UPDATE `' . $tableName . "` SET `{$field}` = `{$field}` + {$val} WHERE $condition", $this->wlink);
$this->execute($stmt);
$this->setCacheVer($tableName);
return $stmt->rowCount();
} | 指定字段的值+1
@param string $key 操作的key user-id-1
@param int $val
@param string $field 要改变的字段
@param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀
@return bool | entailment |
public function prepare($sql, $link = null, $resetParams = true)
{
$resetParams && $this->reset();
is_null($link) && $link = $this->currentQueryIsMaster ? $this->wlink : $this->rlink;
$sqlParams = [];
foreach ($this->bindParams as $key => $val) {
$sqlParams[] = ':param' . $key;
}
$this->currentSql = $sql;
$sql = vsprintf($sql, $sqlParams);
$stmt = $link->prepare($sql);//pdo默认情况prepare出错不抛出异常只返回Pdo::errorInfo
if ($stmt === false) {
$error = $link->errorInfo();
if (in_array($error[1], [2006, 2013])) {
$link = $this->connectDb($this->currentQueryIsMaster ? 'wlink' : 'rlink', true);
$stmt = $link->prepare($sql);
if ($stmt === false) {
$error = $link->errorInfo();
} else {
return $stmt;
}
}
throw new \InvalidArgumentException(
'Pdo Prepare Sql error! ,【Sql: ' . $this->buildDebugSql() . '】,【Code: ' . $link->errorCode() . '】, 【ErrorInfo!:
' . $error[2] . '】 '
);
}
return $stmt;
} | 预处理语句
@param string $sql 要预处理的sql语句
@param \PDO $link
@param bool $resetParams
@return \PDOStatement | entailment |
public function execute($stmt, $clearBindParams = true)
{
foreach ($this->bindParams as $key => $val) {
is_int($val) ? $stmt->bindValue(':param' . $key, $val, \PDO::PARAM_INT) : $stmt->bindValue(':param' . $key, $val, \PDO::PARAM_STR);
}
//empty($param) && $param = $this->bindParams;
$this->conf['log_slow_sql'] && $startQueryTimeStamp = microtime(true);
if (!$stmt->execute()) {
$error = $stmt->errorInfo();
throw new \InvalidArgumentException('Pdo execute Sql error!,【Sql : ' . $this->buildDebugSql() . '】,【Error:' . $error[2] . '】');
}
$slow = 0;
if ($this->conf['log_slow_sql']) {
$queryTime = microtime(true) - $startQueryTimeStamp;
if ($queryTime > $this->conf['log_slow_sql']) {
if (Plugin::hook('cml.mysql_query_slow', ['sql' => $this->buildDebugSql(), 'query_time' => $queryTime]) !== false) {
Log::notice('slow_sql', ['sql' => $this->buildDebugSql(), 'query_time' => $queryTime]);
}
$slow = $queryTime;
}
}
if (Cml::$debug) {
$this->debugLogSql($slow > 0 ? Debug::SQL_TYPE_SLOW : Debug::SQL_TYPE_NORMAL, $slow);
}
$this->currentQueryIsMaster = true;
$this->currentSql = '';
$clearBindParams && $this->clearBindParams();
return true;
} | 执行预处理语句
@param object $stmt PDOStatement
@param bool $clearBindParams
@return bool | entailment |
private function debugLogSql($type = Debug::SQL_TYPE_NORMAL, $other = 0)
{
Debug::addSqlInfo($this->buildDebugSql(), $type, $other);
} | Debug模式记录查询语句显示到控制台
@param int $type
@param int $other $other type = SQL_TYPE_SLOW时带上执行时间 | entailment |
private function buildDebugSql()
{
$bindParams = $this->bindParams;
foreach ($bindParams as $key => $val) {
$bindParams[$key] = str_replace('\\\\', '\\', addslashes($val));
}
return vsprintf(str_replace('%s', "'%s'", $this->currentSql), $bindParams);
} | 组装sql用于DEBUG
@return string | entailment |
public function close()
{
if (!Config::get('session_user')) {
//开启会话自定义保存时,不关闭防止会话保存失败
$this->wlink = null;
unset($this->wlink);
}
$this->rlink = null;
unset($this->rlink);
} | 关闭连接 | entailment |
public function version($link = null)
{
is_null($link) && $link = $this->wlink;
return $link->getAttribute(\PDO::ATTR_SERVER_VERSION);
} | 获取mysql 版本
@param \PDO $link
@return string | entailment |
public function rollBack($rollBackTo = false)
{
if ($rollBackTo === false) {
return $this->wlink->rollBack();
} else {
return $this->wlink->exec("ROLLBACK TO {$rollBackTo}");
}
} | 回滚事务
@param bool $rollBackTo 是否为还原到某个保存点
@return bool | entailment |
public function callProcedure($procedureName = '', $bindParams = [], $isSelect = true)
{
$this->bindParams = $bindParams;
$this->currentQueryIsMaster = true;
$stmt = $this->prepare("exec {$procedureName}", $this->wlink);
$this->execute($stmt);
if ($isSelect) {
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
} else {
return $stmt->rowCount();
}
} | 调用存储过程
@param string $procedureName 要调用的存储过程名称
@param array $bindParams 绑定的参数
@param bool|true $isSelect 是否为返回数据集的语句
@return array|int | entailment |
public function handle()
{
// This is the model that all your others will extend
$baseModel = '\Illuminate\Database\Eloquent\Model'; // default laravel 5
// This is the path where we will store your new models
$path = storage_path('models');
if ($this->option('output')) {
$path = $this->option('output');
}
// The namespace of the models
$namespace = 'App'; // default namespace for clean laravel 5 installation
if ($this->option('namespace')) {
$namespace = $this->option('namespace');
}
// get the prefix from the config
$prefix = Database::getTablePrefix();
$generator = new ModelGenerator($baseModel, $path, $namespace, $prefix);
$generator->start();
} | Execute the console command.
@return mixed | entailment |
public function lPush($name, $data)
{
return $this->getDriver()->lPush($name, $this->encodeDate($data));
} | 从列表头入队
@param string $name 要从列表头入队的队列的名称
@param mixed $data 要入队的数据
@return mixed | entailment |
public function lPop($name)
{
$data = $this->getDriver()->lPop($name);
$data && $data = $this->decodeDate($data);
return $data;
} | 从列表头出队
@param string $name 要从列表头出队的队列的名称
@return mixed | entailment |
public function rPush($name, $data)
{
return $this->getDriver()->rPush($name, $this->encodeDate($data));
} | 从列表尾入队
@param string $name 要从列表尾入队的队列的名称
@param mixed $data 要入队的数据
@return mixed | entailment |
public function rPop($name)
{
$data = $this->getDriver()->rPop($name);
$data && $data = $this->decodeDate($data);
return $data;
} | 从列表尾出队
@param string $name 要从列表尾出队的队列的名称
@return mixed | entailment |
public function fromArray($data)
{
foreach ($data as $param => $value) {
if (!method_exists($this, 'set' . ucfirst($param))) {
continue;
}
$this->{'set' . ucfirst($param)}($value);
}
return $this;
} | Converts array to response model
@param array $data
@return $this | entailment |
public function toArray($method)
{
$vars = get_object_vars($this);
$className = explode('\\', get_called_class());
return $vars + array('model' => end($className));
} | Convert object to an associative array
@param string $method The API method called
@return array | entailment |
private function initBaseDir($templateFile)
{
$baseDir = Cml::getContainer()->make('cml_route')->getAppName();
$baseDir && $baseDir .= '/';
$baseDir .= Cml::getApplicationDir('app_view_path_name') . (Config::get('html_theme') != '' ? DIRECTORY_SEPARATOR . Config::get('html_theme') : '');
$layOutRootDir = $baseDir;
if ($templateFile === '') {
$baseDir .= '/' . Cml::getContainer()->make('cml_route')->getControllerName() . '/';
$file = Cml::getContainer()->make('cml_route')->getActionName();
} else {
$templateFile = str_replace('.', '/', $templateFile);
$baseDir .= DIRECTORY_SEPARATOR . dirname($templateFile) . DIRECTORY_SEPARATOR;
$file = basename($templateFile);
}
return [
'layoutDir' => Cml::getApplicationDir('apps_path') . DIRECTORY_SEPARATOR . $layOutRootDir,
'layoutCacheRootPath' => Cml::getApplicationDir('runtime_cache_path') . DIRECTORY_SEPARATOR . $layOutRootDir . DIRECTORY_SEPARATOR,
'templateDir' => Cml::getApplicationDir('apps_path') . DIRECTORY_SEPARATOR . $baseDir, //指定模板文件存放目录
'cacheDir' => Cml::getApplicationDir('runtime_cache_path') . DIRECTORY_SEPARATOR . $baseDir, //指定缓存文件存放目录
'file' => $file
];
} | 初始化目录
@param string $templateFile 模板文件名
@return string | entailment |
public function display($templateFile = '')
{
$options = $this->initBaseDir($templateFile);
$compiler = new BladeCompiler($options['cacheDir'], $options['layoutCacheRootPath']);
$compiler->directive('datetime', function ($timestamp) {
return preg_replace('/\(\s*?(\S+?)\s*?\|(.*?)\)/i', '<?php echo date(trim("${2}"), ${1}); ?>', $timestamp);
});
$compiler->directive('hook', function ($hook) {
return preg_replace('/\((.*?)\)/', '<?php \Cml\Plugin::hook("$1"); ?>', $hook);
});
$compiler->directive('urldeper', function () {
return '<?php echo \Cml\Config::get("url_model") == 3 ? "&" : "?"; ?>';
});
$compiler->directive('get', function ($key) {
return preg_replace('/\((.*?)\)/', '<?php echo \Cml\Http\Input::getString("${1}");?>', $key);
});
$compiler->directive('post', function ($key) {
return preg_replace('/\((.*?)\)/', '<?php echo \Cml\Http\Input::postString("${1}");?>', $key);
});
$compiler->directive('request', function ($key) {
return preg_replace('/\((.*?)\)/', '<?php echo \Cml\Http\Input::requestString("${1}");?>', $key);
});
$compiler->directive('url', function ($key) {
return preg_replace('/\((.*?)\)/', '<?php echo \Cml\Http\Response::url("${1}"); ?>', $key);
});
$compiler->directive('public', function () {
return '<?php echo \Cml\Config::get("static__path", \Cml\Cml::getContainer()->make("cml_route")->getSubDirName());?>';
});
$compiler->directive('token', function () {
return '<input type="hidden" name="CML_TOKEN" value="<?php echo \Cml\Secure::getToken();?>" />';
});
$compiler->directive('lang', function ($lang) {
return preg_replace('/\((.*?)\)/', '<?php echo \Cml\Lang::get("${1}"); ?>', $lang);
});
$compiler->directive('config', function ($config) {
return preg_replace('/\((.*?)\)/', '<?php echo \Cml\Config::get("${1}"); ?>', $config);
});
$compiler->directive('assert', function ($url) {
return preg_replace('/\((.*?)\)/', '<?php echo \Cml\Tools\StaticResource::parseResourceUrl("${1}"); ?>', $url);
});
$compiler->directive('acl', function ($url) {
return preg_replace('/\((.*?)\)/', '<?php if (\Cml\Vendor\Acl::checkAcl("${1}")) : ?>', $url);
});
$compiler->directive('endacl', function () {
return '<?php endif; ?>';
});
foreach ($this->rule as $pattern => $func) {
$compiler->directive($pattern, $func);
}
$finder = new FileViewFinder([$options['templateDir'], $options['layoutDir']]);
$finder->addExtension(trim(Config::get('html_template_suffix'), '.'));
$factory = new Factory($compiler, $finder);
header('Content-Type:text/html; charset=' . Config::get('default_charset'));
echo $factory->make($options['file'], $this->args)->render();
Cml::cmlStop();
return;
} | 抽象display
@param string $templateFile 模板文件
@return mixed | entailment |
public function execute(array $args, array $options = [])
{
if (!isset($args[0])) {
throw new \InvalidArgumentException('arg action must be input');
}
$action = explode('::', $args[0]);
if (!class_exists($action[0])) {
throw new \InvalidArgumentException('action not not found!');
}
if (isset($args[1])) {
$frequency = abs(intval($args[1]));
} else {
$frequency = null;
}
ProcessManage::addTask($action, $frequency);
} | 添加一个后台任务
@param array $args 传递给命令的参数
@param array $options 传递给命令的选项
@throws \InvalidArgumentException | entailment |
public static function fromString($path)
{
$pathObject = static::factory()->create($path);
if (!$pathObject instanceof AbsolutePathInterface) {
throw new Exception\NonAbsolutePathException($pathObject);
}
return $pathObject;
} | Creates a new absolute path from its string representation.
@param string $path The string representation of the absolute path.
@return AbsolutePathInterface The newly created absolute path.
@throws Exception\NonAbsolutePathException If the supplied string represents a non-absolute path. | entailment |
public function isParentOf(AbsolutePathInterface $path)
{
return $path->hasAtoms() &&
$this->normalize()->atoms() ===
$path->parent()->normalize()->atoms();
} | Determine if this path is the direct parent of the supplied path.
@param AbsolutePathInterface $path The child path.
@return boolean True if this path is the direct parent of the supplied path. | entailment |
public function isAncestorOf(AbsolutePathInterface $path)
{
$parentAtoms = $this->normalize()->atoms();
return $parentAtoms === array_slice(
$path->normalize()->atoms(),
0,
count($parentAtoms)
);
} | Determine if this path is an ancestor of the supplied path.
@param AbsolutePathInterface $path The child path.
@return boolean True if this path is an ancestor of the supplied path. | entailment |
public function relativeTo(AbsolutePathInterface $path)
{
$parentAtoms = $path->normalize()->atoms();
$childAtoms = $this->normalize()->atoms();
if ($childAtoms === $parentAtoms) {
$diffAtoms = array(static::SELF_ATOM);
} else {
$diffAtoms = array_diff_assoc($childAtoms, $parentAtoms);
$diffAtomIndices = array_keys($diffAtoms);
$diffAtoms = array_slice(
$childAtoms,
array_shift($diffAtomIndices)
);
$fillCount =
(count($parentAtoms) - count($childAtoms)) +
count($diffAtoms);
if ($fillCount > 0) {
$diffAtoms = array_merge(
array_fill(0, $fillCount, static::PARENT_ATOM),
$diffAtoms
);
}
}
return $this->createPath($diffAtoms, false, false);
} | Determine the shortest path from the supplied path to this path.
For example, given path A equal to '/foo/bar', and path B equal to
'/foo/baz', A relative to B would be '../bar'.
@param AbsolutePathInterface $path The path that the generated path will be relative to.
@return RelativePathInterface A relative path from the supplied path to this path. | entailment |
public function searchForPaginatedContent($searchText, $currentPage, $languages)
{
// Generating query
$query = new Query();
$query->query = new Criterion\FullText($searchText);
$query->filter = new Criterion\LogicalAnd(
array(
new Criterion\Visibility(Criterion\Visibility::VISIBLE),
new Criterion\LanguageCode($languages, true),
)
);
// Initialize pagination.
$pager = new Pagerfanta(
new ContentSearchAdapter($query, $this->searchService)
);
$pager->setMaxPerPage($this->searchListLimit);
$pager->setCurrentPage($currentPage);
return $pager;
} | Search for content for a given $searchText and returns a pager.
@param string $searchText to be looked up
@param int $currentPage to be displayed
@param array $languages to include in the search
@return \Pagerfanta\Pagerfanta | entailment |
public function buildListFromSearchResult(SearchResult $searchResult)
{
$list = array();
foreach ($searchResult->searchHits as $searchHit) {
$list[$searchHit->valueObject->id] = $searchHit->valueObject;
}
return $list;
} | Builds a list from $searchResult.
Returned array consists of a hash of objects, indexed by their ID.
@param \eZ\Publish\API\Repository\Values\Content\Search\SearchResult $searchResult
@return array | entailment |
public static function parsePathInfo()
{
$urlModel = Config::get('url_model');
$pathInfo = self::$pathInfo;
if (empty($pathInfo)) {
$isCli = Request::isCli(); //是否为命令行访问
if ($isCli) {
isset($_SERVER['argv'][1]) && $pathInfo = explode('/', $_SERVER['argv'][1]);
} else {
//修正可能由于nginx配置不当导致的子目录获取有误
if (false !== ($fixScriptName = stristr($_SERVER['SCRIPT_NAME'], '.php', true))) {
$_SERVER['SCRIPT_NAME'] = $fixScriptName . '.php';
}
$urlPathInfoDeper = Config::get('url_pathinfo_depr');
if ($urlModel === 1 || $urlModel === 2) { //pathInfo模式(含显示、隐藏index.php两种)SCRIPT_NAME
if (isset($_GET[Config::get('var_pathinfo')])) {
$param = str_replace(Config::get('url_html_suffix'), '', $_GET[Config::get('var_pathinfo')]);
} else {
$param = preg_replace('/(.*)\/(.+)\.php(.*)/i', '\\1\\3', preg_replace(
[
'/\\' . Config::get('url_html_suffix') . '/',
'/\&.*/', '/\?.*/'
],
'',
$_SERVER['REQUEST_URI']
));//这边替换的结果是带index.php的情况。不带index.php在以下处理
$scriptName = dirname($_SERVER['SCRIPT_NAME']);
if ($scriptName && $scriptName != '/') {//假如项目在子目录这边去除子目录含模式1和模式2两种情况(伪静态到子目录)
$param = substr($param, strpos($param, $scriptName) + strlen($scriptName));//之所以要strpos是因为子目录或请求string里可能会有多个/而SCRIPT_NAME里只会有1个
}
}
$param = trim($param, '/' . $urlPathInfoDeper);
} elseif ($urlModel === 3 && isset($_GET[Config::get('var_pathinfo')])) {//兼容模式
$urlString = $_GET[Config::get('var_pathinfo')];
unset($_GET[Config::get('var_pathinfo')]);
$param = trim(str_replace(
Config::get('url_html_suffix'),
'',
ltrim($urlString, '/')
), $urlPathInfoDeper);
}
$pathInfo = explode($urlPathInfoDeper, $param);
}
}
isset($pathInfo[0]) && empty($pathInfo[0]) && $pathInfo = ['/'];
self::$pathInfo = $pathInfo;
Plugin::hook('cml.after_parse_path_info');
} | 解析url获取pathinfo
@return void | entailment |
public static function loadAppRoute($app = 'web', $inConfigDir = true)
{
static $loaded = [];
if (isset($loaded[$app])) {
return;
}
$path = $app . DIRECTORY_SEPARATOR . ($inConfigDir ? Cml::getApplicationDir('app_config_path_name') . DIRECTORY_SEPARATOR : '') . 'route.php';
$appRoute = Cml::getApplicationDir('apps_path') . DIRECTORY_SEPARATOR . $path;
if (!is_file($appRoute)) {
throw new \InvalidArgumentException(Lang::get('_NOT_FOUND_', $path));
}
$loaded[$app] = 1;
Cml::requireFile($appRoute);
} | 载入应用单独的路由
@param string $app 应用名称
@param string $inConfigDir 配置文件是否在Config目录中 | entailment |
public static function executeCallableRoute(callable $call, $route = '')
{
call_user_func($call);
Cml::$debug && Debug::addTipInfo(Lang::get('_CML_EXECUTION_ROUTE_IS_', "callable route:{{$route}}", Config::get('url_model')));
Cml::cmlStop();
} | 执行闭包路由
@param callable $call 闭包
@param string $route 路由string | entailment |
public function getAppName()
{
if (!self::$urlParams['path']) {
$pathInfo = \Cml\Route::getPathInfo();
self::$urlParams['path'] = $pathInfo[0];//用于绑定系统命令
}
return trim(self::$urlParams['path'], '\\/');
} | 获取应用目录可以是多层目录。如web、admin等.404的时候也必须有值用于绑定系统命令
@return string | entailment |
public function parseUrl()
{
\Cml\Route::parsePathInfo();
$dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector $r) {
foreach ($this->routes as $route) {
$r->addRoute($route['method'], $route['uri'], $route['action']);
}
});
$httpMethod = isset($_POST['_method']) ? strtoupper($_POST['_method']) : strtoupper($_SERVER['REQUEST_METHOD']);
$routeInfo = $dispatcher->dispatch($httpMethod, implode('/', \Cml\Route::getPathInfo()));
switch ($routeInfo[0]) {
case Dispatcher::NOT_FOUND:
case Dispatcher::METHOD_NOT_ALLOWED:
break;
case Dispatcher::FOUND:
$_GET += $routeInfo[2];
if (is_callable($routeInfo[1])) {
\Cml\Route::executeCallableRoute($routeInfo[1], 'fastRoute');
}
$this->parseUrlParams($routeInfo[1]);
break;
}
return $dispatcher;
} | 解析url
@return mixed | entailment |
private function parseUrlParams($uri)
{
//is_array($action) ? $action['__rest'] = 1 : ['__rest' => 0, '__action' => $action];
if (is_array($uri) && !isset($uri['__action'])) {
self::$urlParams['path'] = $uri[0];
self::$urlParams['controller'] = $uri[1];
if (isset($uri['__rest'])) {
self::$urlParams['action'] = strtolower(isset($_POST['_method']) ? $_POST['_method'] : $_SERVER['REQUEST_METHOD']) . ucfirst($uri[2]);
} else {
self::$urlParams['action'] = $uri[2];
}
} else {
$rest = false;
if (is_array($uri) && $uri['__rest'] === 0) {
$rest = true;
$uri = $uri['__action'];
}
$path = '/';
$routeArr = explode('/', $uri);
if ($rest) {
self::$urlParams['action'] = strtolower(isset($_POST['_method']) ? $_POST['_method'] : $_SERVER['REQUEST_METHOD']) . ucfirst(array_pop($routeArr));
} else {
self::$urlParams['action'] = array_pop($routeArr);
}
self::$urlParams['controller'] = ucfirst(array_pop($routeArr));
$controllerPath = '';
$routeAppHierarchy = Config::get('route_app_hierarchy', 1);
$i = 0;
while ($dir = array_shift($routeArr)) {
if ($i++ < $routeAppHierarchy) {
$path .= $dir . '/';
} else {
$controllerPath .= $dir . '/';
}
}
self::$urlParams['controller'] = $controllerPath . self::$urlParams['controller'];
unset($routeArr);
self::$urlParams['path'] = $path ? $path : '/';
unset($path);
}
//定义URL常量
$subDir = dirname($_SERVER['SCRIPT_NAME']);
if ($subDir == '/' || $subDir == '\\') {
$subDir = '';
}
//定义项目根目录地址
self::$urlParams['root'] = $subDir . '/';
} | 解析uri参数
@param $uri | entailment |
public function any($pattern, $action)
{
$this->addRoute($this->httpMethod, $pattern, $action);
return $this;
} | 增加任意访问方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
public function rest($pattern, $action)
{
is_array($action) ? $action['__rest'] = 1 : $action = ['__rest' => 0, '__action' => $action];
$this->addRoute($this->httpMethod, $pattern, $action);
return $this;
} | 增加REST方式路由
@param string $pattern 路由规则
@param string|array $action 执行的操作
@return $this | entailment |
private function addRoute($method, $pattern, $action)
{
if (is_array($method)) {
foreach ($method as $verb) {
$this->routes[$verb . $pattern] = ['method' => $verb, 'uri' => self::patternFactory($pattern), 'action' => $action];
}
} else {
$this->routes[$method . $pattern] = ['method' => $method, 'uri' => self::patternFactory($pattern), 'action' => $action];
}
} | 添加一个路由
@param array|string $method
@param string $pattern
@param mixed $action
@return void | entailment |
public function normalize(PathInterface $path)
{
if ($path instanceof WindowsPathInterface) {
return $this->windowsNormalizer()->normalize($path);
}
return $this->unixNormalizer()->normalize($path);
} | Normalize the supplied path to its most canonical form.
@param PathInterface $path The path to normalize.
@return PathInterface The normalized path. | entailment |
public static function redirect($url, $time = 0)
{
strpos($url, 'http') === false && $url = self::url($url, 0);
if (!headers_sent()) {
($time === 0) && header("Location: {$url}");
header("refresh:{$time};url={$url}");
exit();
} else {
exit("<meta http-equiv='Refresh' content='{$time};URL={$url}'>");
}
} | 重定向
@param string $url 重写向的目标地址
@param int $time 等待时间
@return void | entailment |
public static function show404Page($tpl = null)
{
self::sendHttpStatus(404);
is_null($tpl) && $tpl = Config::get('404_page');
is_file($tpl) && Cml::requireFile($tpl);
exit();
} | 显示404页面
@param string $tpl 模板路径
@return void | entailment |
public static function fullUrl($url = '', $echo = true)
{
$url = Request::baseUrl() . self::url($url, false);
if ($echo) {
echo $url;
return '';
} else {
return $url;
}
} | URL组装(带域名端口) 支持不同URL模式
eg: \Cml\Http\Response::fullUrl('Home/Blog/cate/id/1')
@param string $url URL表达式 路径/控制器/操作/参数1/参数1值/.....
@param bool $echo 是否输出 true输出 false return
@return string | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.