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($extension)); }
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 )); return $resp; }
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_array($size)) { $attribs = $size; $size = null; } elseif (isset($padding) && is_array($padding)) { $attribs = $padding; $padding = null; } } } return $this->renderer->render(self::IMG_TEMPLATE, array( 'src' => $this->assembleRoute($message, $extension, $size, $padding), 'attribs' => $attribs )); }
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)) { if (is_array($size)) { $attribs = $size; $size = null; } elseif (isset($padding) && is_array($padding)) { $attribs = $padding; $padding = null; } } } $image = $this->qrCodeService->getQrCodeContent($message, $extension, $size, $padding); $contentType = $this->qrCodeService->generateContentType( isset($extension) ? $extension : QrCodeServiceInterface::DEFAULT_EXTENSION ); return $this->renderer->render(self::IMG_BASE64_TEMPLATE, array( 'base64' => base64_encode($image), 'contentType' => $contentType, 'attribs' => $attribs )); }
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 (isset($padding)) { $params['padding'] = $padding; } } } $this->routeOptions['name'] = 'acelaya-qrcode'; return $this->router->assemble($params, $this->routeOptions); }
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_OB_START && ob_end_flush(); }
程序执行完毕,打印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 = 'red'; } $mess = "<span style='color:{$color}'>"; $mess .= '<b>' . self::$tipInfoType[$errorType] . "</b>[在文件 {$errorFile} 中,第 {$errorLine} 行]:"; $mess .= $errorTip; $mess .= '</span>'; self::addTipInfo($mess); }
错误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; break; case self::TIP_INFO_TYPE_INCLUDE_LIB: self::$includeLib[] = $msg; break; case self::TIP_INFO_TYPE_SQL: self::$sql[] = $msg; break; case self::TIP_INFO_TYPE_INCLUDE_FILE: self::$includeFile[] = str_replace('\\', '/', str_replace([Cml::getApplicationDir('secure_src'), CML_PATH], ['{secure_src}', '{cmlphp_src}'], $msg)); break; } } }
添加调试信息 @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 .= "<span style='color:red;'>[slow sql, {$other}]</span>"; break; } self::addTipInfo($sql, self::TIP_INFO_TYPE_SQL); }
添加一条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); // 代码的html $codeHtml = ''; // 获取相应范围起止索引 $start = ($focus - $range) < 1 ? 0 : ($focus - $range - 1); $end = (($focus + $range) > $lineNums ? $lineNums - 1 : ($focus + $range - 1)); // 修正开始标签 // 有可能取到的片段缺少开始的span标签,而它包含代码着色的CSS属性 // 如果缺少,片段开始的代码则没有颜色了,所以需要把它找出来 if (substr($html[$start], 0, 5) !== '<span') { while (($start - 1) >= 0) { $match = []; preg_match('/<span style="color: #([\w]+)"(.(?!<\/span>))+$/', $html[--$start], $match); if (!empty($match)) { $html[$start] = "<span style=\"color: #{$match[1]}\">" . $html[$start]; break; } } } for ($line = $start; $line <= $end; $line++) { // 在行号前填充0 $index_pad = str_pad($line + 1, strlen($end), 0, STR_PAD_LEFT); ($line + 1) == $focus && $codeHtml .= "<p style='height: " . $style['lineHeight'] . "px; width: 100%; _width: 95%; background-color: red; opacity: 0.4; filter:alpha(opacity=40); font-size:15px; font-weight: bold;'>"; $codeHtml .= "<span style='margin-right: 10px;line-height: " . $style['lineHeight'] . "px; color: #807E7E;'>{$index_pad}</span>{$html[$line]}"; $codeHtml .= (($line + 1) == $focus ? '</p>' : ($line != $end ? '<br />' : '')); } // 修正结束标签 if (substr($codeHtml, -7) !== '</span>') { $codeHtml .= '</span>'; } return <<<EOT <div style="position: relative; font-size: {$style['fontSize']}px; background-color: #BAD89A;"> <div style="_width: 95%; line-height: {$style['lineHeight']}px; position: relative; z-index: 2; overflow: hidden; white-space:nowrap; text-overflow:ellipsis;">{$codeHtml}</div> </div> EOT; }
显示代码片段 @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::$includeFile, 'includeFile'); } else { $deBugLogData = [ 'tipInfo' => self::$tipInfo ]; self::$sql && $deBugLogData['sql'] = self::$sql; if (!empty($deBugLogData)) { Cml::requireFile(CML_CORE_PATH . DIRECTORY_SEPARATOR . 'ConsoleLog.php', ['deBugLogData' => $deBugLogData]); } } } else { View::getEngine('html') ->assign('includeLib', Debug::getIncludeLib()) ->assign('includeFile', Debug::getIncludeFiles()) ->assign('tipInfo', Debug::getTipInfo()) ->assign('sqls', Debug::getSqls()) ->assign('usetime', Debug::getUseTime()) ->assign('usememory', Debug::getUseMemory()); Cml::showSystemTemplate(Config::get('debug_page')); } }
输出调试消息 @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 "<table cellspacing=2 cellpadding=3 class=\"dBug_" . $type . "\"> <tr> <td " . $str_i . "class=\"dBug_" . $type . "Header\" colspan=" . $colspan . " onClick='dBug_toggleTable(this)'>" . $header . "</td> </tr>"; }
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($var); break; case "NULL": $this->varIsNULL(); break; case "boolean": $this->varIsBoolean($var); break; default: $var = ($var == "") ? "[empty string]" : $var; echo "<table cellspacing=0><tr>\n<td>" . $var . "</td>\n</tr>\n</table>\n"; break; } }
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) { $value = (!is_object($value) && !is_array($value) && trim($value) == "") ? "[empty string]" : $value; $this->makeTDHeader("object", $key); //check for recursion if (is_object($value) || is_array($value)) { $var_ser = serialize($value); if (in_array($var_ser, $this->arrHistory, TRUE)) { $value = (is_object($value)) ? "*RECURSION* -> $" . get_class($value) : "*RECURSION*"; } } if (in_array(gettype($value), $this->arrType)) { $this->checkType($value); } else { echo $value; } echo $this->closeTDRow(); } $arrObjMethods = get_class_methods(get_class($var)); foreach ($arrObjMethods as $key => $value) { $this->makeTDHeader("object", $value); echo "[function]" . $this->closeTDRow(); } } else { echo "<tr><td>" . $this->error("object") . $this->closeTDRow(); } array_pop($this->arrHistory); echo "</table>"; }
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": case "sybase-db result": case "sybase-ct result": case "mysql result": $db = current(explode(" ", get_resource_type($var))); $this->varIsDBResource($var, $db); break; case "gd": $this->varIsGDResource($var); break; case "xml": $this->varIsXmlResource($var); break; default: echo get_resource_type($var) . $this->closeTDRow(); break; } echo $this->closeTDRow() . "</table>\n"; }
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", $var); $numfields = call_user_func($db . "_num_fields", $var); $this->makeTableHeader("resource", $db . " result", $numfields + 1); echo "<tr><td class=\"dBug_resourceKey\">&nbsp;</td>"; $field = []; for ($i = 0; $i < $numfields; $i++) { $field_header = $field_name = ""; for ($j = 0; $j < count($arrFields); $j++) { $db_func = $db . "_field_" . $arrFields[$j]; if (function_exists($db_func)) { $fheader = call_user_func($db_func, $var, $i) . " "; if ($j == 0) { $field_name = $fheader; } else { $field_header .= $fheader; } } } $field[$i] = call_user_func($db . "_fetch_field", $var, $i); echo "<td class=\"dBug_resourceKey\" title=\"" . $field_header . "\">" . $field_name . "</td>"; } echo "</tr>"; for ($i = 0; $i < $numrows; $i++) { $row = call_user_func($db . "_fetch_array", $var, constant(strtoupper($db) . "_ASSOC")); echo "<tr>\n"; echo "<td class=\"dBug_resourceKey\">" . ($i + 1) . "</td>"; for ($k = 0; $k < $numfields; $k++) { $fieldrow = $row[($field[$k]->name)]; $fieldrow = ($fieldrow == "") ? "[empty string]" : $fieldrow; echo "<td>" . $fieldrow . "</td>\n"; } echo "</tr>\n"; } echo "</table>"; if ($numrows > 0) { call_user_func($db . "_data_seek", $var, 0); } }
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->makeTDHeader("resource", "Colors"); echo imagecolorstotal($var) . $this->closeTDRow(); echo "</table>"; }
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] : "&nbsp;"; echo $this->closeTDRow(); $this->makeTDHeader("xml", "xmlComment"); echo (!empty($this->xmlDData[$i])) ? $this->xmlDData[$i] : "&nbsp;"; echo $this->closeTDRow(); $this->makeTDHeader("xml", "xmlChildren"); unset($this->xmlCData[$i], $this->xmlDData[$i]); } echo $this->closeTDRow(); echo "</table>"; $this->xmlCount = 0; }
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[] = $criterion; } $query = new LocationQuery( array( 'query' => new Criterion\LogicalAnd($criteria), 'sortClauses' => array(new SortClause\Location\Priority(LocationQuery::SORT_ASC)), ) ); $query->limit = $this->defaultMenuLimit; $query->performCount = false; return $this->searchHelper->buildListFromSearchResult($this->repository->getSearchService()->findLocations($query)); }
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\Publish\API\Repository\Values\Content\Query\Criterion $criterion Additional criterion for filtering. @return \eZ\Publish\API\Repository\Values\Content\Location[] Location objects, indexed by their contentId.
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.places.place_list.content_types'), $this->getConfigResolver()->getParameter('languages') ); return $this->render( 'eZDemoBundle:parts/place:place_list.html.twig', array('places' => $places) ); }
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 used here. if ($latitude == 'key_lat' || $longitude == 'key_lon' || $maxDist == 'key_dist') { throw $this->createNotFoundException('Invalid parameters'); } /** @var \EzSystems\DemoBundle\Helper\PlaceHelper $placeHelper */ $placeHelper = $this->get('ezdemo.place_helper'); $languages = $this->getConfigResolver()->getParameter('languages'); $language = (!empty($languages)) ? $languages[0] : null; $sortClauses = array( new SortClause\MapLocationDistance( 'place', 'location', $latitude, $longitude, Query::SORT_ASC, $language ), ); $places = $placeHelper->getPlaceListSorted( $location, $latitude, $longitude, $this->container->getParameter('ezdemo.places.place_list.content_types'), $maxDist, $sortClauses, $languages ); return $this->render( 'eZDemoBundle:parts/place:place_list.html.twig', array('places' => $places) ); }
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 for the search in km @return \Symfony\Component\HttpFoundation\Response @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
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 = current($this->tasks); $this->processTask($task); if ($task['status'] == -1 || $task['status'] == 2) { if ($this->saveSuccess) { $this->success[] = $task; } unset($this->tasks[key($this->tasks)]); $this->makeTask(); } else { $this->tasks[key($this->tasks)] = $task; } if (!next($this->tasks)) { reset($this->tasks); } } return $this->getSuccessInfo(); }
执行线程队列里的所有任务 @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 ($socket) { $this->tasks[] = [ 'host' => $item['host'], 'path' => $item['path'], 'socket' => $socket, 'response' => '', 'status' => 0, // -1=error, 0=ready, 1=active, 2=done ]; return 1; } else { return 0; } }
创建任务 @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/1.1\r\nHost: {$task['host']}\r\n\r\n"); $task['status'] = 1; break; case 1: // active $data = fread($task['socket'], $this->readDataLen); if (strlen($data) == 0) { fclose($task['socket']); echo "Failed to connect {$task['host']}.<br />\n"; $task['status'] = -1; } else { $task['status'] = 2; $task['response'] .= $data; } break; } } }
处理任务 @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('Create seeds directory?', [Colour::RED, Colour::HIGHLIGHT]))) { mkdir($path, 0755, true); } } $this->verifySeedDirectory($path); $path = realpath($path); $className = $args[0]; if (!Util::isValidPhinxClassName($className)) { throw new \InvalidArgumentException(sprintf( 'The seed class name "%s" is invalid. Please use CamelCase format', $className )); } // Compute the file path $filePath = $path . DIRECTORY_SEPARATOR . $className . '.php'; if (is_file($filePath)) { throw new \InvalidArgumentException(sprintf( 'The file "%s" already exists', basename($filePath) )); } // inject the class names appropriate to this seeder $contents = file_get_contents($this->getSeedTemplateFilename()); $classes = [ '$useClassName' => 'Phinx\Seed\AbstractSeed', '$className' => $className, '$baseClassName' => 'AbstractSeed', ]; $contents = strtr($contents, $classes); if (false === file_put_contents($filePath, $contents)) { throw new \RuntimeException(sprintf( 'The file "%s" could not be written to', $path )); } Output::writeln('using seed base class ' . $classes['$useClassName']); Output::writeln('created ' . str_replace(Cml::getApplicationDir('secure_src'), '{secure_src}', $filePath)); }
创建一个新的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_repeat($this->periphery, $maxWidth) . "\n";//first line foreach ($lines as $line) { $space = $maxWidth - (strlen($line) + 2 + $this->padding * 2); $output .= $this->periphery . str_repeat(' ', $this->padding) . $line . str_repeat(' ', $space + $this->padding) . $this->periphery . "\n"; } $output .= str_repeat($this->periphery, $maxWidth); return $output; }
渲染文本并返回 @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 < $num; $i++) { $temp = ord(substr($string, $i, 1)); if ($temp > 160) { $temp2 = ord(substr($string, ++$i, 1)); $temp = $temp * 256 + $temp2 - 65536; } if ($temp > 0 && $temp < 160) { $pinyin .= chr($temp); } elseif ($temp < -20319 || $temp > -10247){ $pinyin .= ''; } else { $total =sizeof(self::$pinyinArr) - 1; for ($j = $total; $j >= 0; $j--) { if (self::$pinyinArr[$j][1] <= $temp) { break; } } $pinyin .= self::$pinyinArr[$j][0]; } } return ($utf8==true) ? iconv('gbk', 'utf-8', $pinyin) : $pinyin; }
中文转拼音 @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('-', $name); if (count($name) < 1) { throw new \InvalidArgumentException(sprintf( 'The arg name "%s" is invalid. eg: adminbase-Blog/Category', $name )); } $namespace = str_replace('/', '\\', trim(trim($name[0], '\\/'))); $path = Cml::getApplicationDir('apps_path') . DIRECTORY_SEPARATOR . $namespace . DIRECTORY_SEPARATOR . Cml::getApplicationDir('app_controller_path_name') . DIRECTORY_SEPARATOR; $component = explode('/', trim(trim($name[1], '/'))); if (count($component) > 1) { $className = ucfirst(array_pop($component)) . Config::get('controller_suffix'); $component = implode(DIRECTORY_SEPARATOR, $component); $path .= $component . DIRECTORY_SEPARATOR; $component = '\\' . $component; } else { $className = ucfirst($component[0]) . Config::get('controller_suffix'); $component = ''; } if (!is_dir($path) && false == mkdir($path, 0700, true)) { throw new \RuntimeException(sprintf( 'The path "%s" could not be create', $path )); } $contents = strtr(file_get_contents($template), ['$namespace' => $namespace, '$component' => $component, '$className' => $className]); $file = $path . $className . '.php'; if (is_file($file)) { throw new \RuntimeException(sprintf( 'The file "%s" is exist', $file )); } if (false === file_put_contents($file, $contents)) { throw new \RuntimeException(sprintf( 'The file "%s" could not be written to', $path )); } Output::writeln(Colour::colour('Controller created successfully. ', Colour::GREEN)); }
创建控制器 @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 . '/'; $pathInfo = \Cml\Route::getPathInfo(); //检测路由 if (self::$rules) {//配置了路由,所有请求通过路由处理 $isRoute = self::isRoute($pathInfo); if ($isRoute[0]) {//匹配路由成功 if (is_array($isRoute['route'])) { self::$urlParams['action'] = $isRoute['route'][2]; self::$urlParams['controller'] = $isRoute['route'][1]; $path = self::$urlParams['path'] = $isRoute['route'][0]; if (is_callable($isRoute['route'][3])) { $isRoute['route'][3](); } } else { $routeArr = explode('/', $isRoute['route']); $isRoute = null; 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); } } else { self::findAction($pathInfo, $path); //未匹配到路由 按文件名映射查找 } } else { self::findAction($pathInfo, $path);//未匹配到路由 按文件名映射查找 } $pathInfo = array_values($pathInfo); for ($i = 0; $i < count($pathInfo); $i += 2) { $_GET[$pathInfo[$i]] = $pathInfo[$i + 1]; } unset($pathInfo); self::$urlParams['path'] = $path ? $path : '/'; unset($path); $_REQUEST = array_merge($_REQUEST, $_GET); }
解析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) { case 'GET': $rMethod = self::REQUEST_METHOD_GET; break; case 'POST': $rMethod = self::REQUEST_METHOD_POST; break; case 'PUT': $rMethod = self::REQUEST_METHOD_PUT; break; case 'PATCH': $rMethod = self::REQUEST_METHOD_PATCH; break; case 'DELETE': $rMethod = self::REQUEST_METHOD_DELETE; break; case 'OPTIONS': $rMethod = self::REQUEST_METHOD_OPTIONS; break; default : $rMethod = self::REQUEST_METHOD_ANY; } foreach ($route as $k => $v) { $rulesMethod = substr($k, 0, 1); if ( $rulesMethod != $rMethod && $rulesMethod != self::REQUEST_METHOD_ANY && $rulesMethod != self::REST_ROUTE ) { //此条路由不符合当前请求方式 continue; } unset($v); $singleRule = substr($k, 1); $arr = $singleRule === '/' ? [$singleRule] : explode('/', ltrim($singleRule, '/')); if ($arr[0] == $pathInfo[0]) { array_shift($arr); foreach ($arr as $key => $val) { if (isset($pathInfo[$key + 1]) && $pathInfo[$key + 1] !== '') { if (strpos($val, '\d') && !is_numeric($pathInfo[$key + 1])) {//数字变量 $route[$k] = false;//匹配失败 break 1; } elseif (strpos($val, ':') === false && $val != $pathInfo[$key + 1]) {//字符串 $route[$k] = false;//匹配失败 break 1; } } else { $route[$k] = false;//匹配失败 break 1; } } } else { $route[$k] = false;//匹配失败 } if ($route[$k] !== false) {//匹配成功的路由 $isSuccess[] = $k; } } if (empty($isSuccess)) { $returnArr[0] = false; } else { //匹配到多条路由时 选择最长的一条(匹配更精确) usort($isSuccess, function ($item1, $item2) { return strlen($item1) >= strlen($item2) ? 0 : 1; }); if (is_callable($route[$isSuccess[0]])) { \Cml\Route::executeCallableRoute($route[$isSuccess[0]], substr($isSuccess[0], 1)); } is_array($route[$isSuccess[0]]) || $route[$isSuccess[0]] = trim(str_replace('\\', '/', $route[$isSuccess[0]]), '/'); //判断路由的正确性 if (!is_array($route[$isSuccess[0]]) && count(explode('/', $route[$isSuccess[0]])) < 2) { throw new \InvalidArgumentException(Lang::get('_ROUTE_PARAM_ERROR_', substr($isSuccess[0], 1))); } $returnArr[0] = true; $successRoute = explode('/', $isSuccess[0]); foreach ($successRoute as $key => $val) { $t = explode('\d', $val); if (strpos($t[0], ':') !== false) { $_GET[ltrim($t[0], ':')] = $pathInfo[$key]; } unset($pathInfo[$key]); } if (substr($isSuccess[0], 0, 1) == self::REST_ROUTE) { $actions = explode('/', $route[$isSuccess[0]]); $arrKey = count($actions) - 1; $actions[$arrKey] = strtolower($httpMethod) . ucfirst($actions[$arrKey]); $route[$isSuccess[0]] = implode('/', $actions); } self::$matchRoute = substr($isSuccess[0], 1); $returnArr['route'] = $route[$isSuccess[0]]; } return $returnArr; }
匹配路由 @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 = Cml::getApplicationDir('apps_path') . '/' . $className . '.php'; if (is_file($actionController)) { return ['class' => str_replace('/', '\\', $className), 'action' => self::getActionName(), 'route' => self::$matchRoute]; } else { return false; } }
获取要执行的控制器类名及方法
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', 1); $i = 0; $controllerSuffix = Config::get('controller_suffix'); while ($dir = array_shift($pathInfo)) { $controllerName = ucfirst($dir); $controller = Cml::getApplicationDir('apps_path') . $path . Cml::getApplicationDir('app_controller_path_name') . '/' . $controllerPath . $controllerName . $controllerSuffix . '.php'; if ($i >= $routeAppHierarchy && is_file($controller)) { self::$urlParams['controller'] = $controllerPath . $controllerName; break; } else { if ($i++ < $routeAppHierarchy) { $path .= $dir . '/'; } else { $controllerPath .= $dir . '/'; } } } empty(self::$urlParams['controller']) && self::$urlParams['controller'] = $controllerName;//用于404的时候挂载插件用 self::$urlParams['action'] = array_shift($pathInfo); }
从文件查找控制器 @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) { if ('' === $atoms[0]) { $isAbsolute = true; array_shift($atoms); --$numAtoms; } if ('' === $atoms[$numAtoms - 1]) { $hasTrailingSeparator = !$isAbsolute || $numAtoms > 1; array_pop($atoms); } } return $this->createFromAtoms( array_filter($atoms, 'strlen'), $isAbsolute, $hasTrailingSeparator ); }
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); } return new RelativePath($atoms, $hasTrailingSeparator); }
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 newly created path instance. @throws InvalidPathAtomExceptionInterface If any of the supplied atoms are invalid. @throws InvalidPathStateException If the supplied arguments would produce an invalid path.
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 representing the new temporary path.
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::stripslashes($_COOKIE); Secure::stripslashes($_REQUEST); //在程序中对get post cookie的改变不影响 request的值 } //session保存方式自定义 if (Config::get('session_user')) { Session::init(); } else { ini_get('session.auto_start') || session_start(); //自动开启session } header('Cache-control: ' . Config::get('http_cache_control')); // 页面缓存控制 //如果有子类中有init()方法 执行Init() eg:做权限控制 if (method_exists($this, "init")) { $this->init(); } //根据动作去找对应的方法 if (method_exists($this, $method)) { $response = $this->$method(); if (is_array($response)) { if (Request::acceptJson()) { View::getEngine('Json') ->assign($response) ->display(); } else { $tpl = isset($this->htmlEngineRenderTplArray[$method]) ? $this->htmlEngineRenderTplArray[$method] : Cml::getContainer()->make('cml_route')->getControllerName() . '/' . $method; call_user_func_array([View::getEngine('Html')->assign($response), is_array($tpl) ? 'displayWithLayout' : 'display'], is_array($tpl) ? $tpl : [$tpl]); } } } elseif (Cml::$debug) { Cml::montFor404Page(); throw new \BadMethodCallException(Lang::get('_ACTION_NOT_FOUND_', $method)); } else { Cml::montFor404Page(); Response::show404Page(); } }
运行对应的控制器 @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->parentLocationId] : $menu; $menuItem->addChild( $location->id, array( 'label' => $this->translationHelper->getTranslatedContentNameByContentInfo($location->contentInfo), 'uri' => $this->router->generate($location), 'attributes' => array('id' => 'nav-location-' . $location->id), ) ); $menuItem->setChildrenAttribute('class', 'nav'); } }
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->getTopMenuContentTypeIdentifierList()), new Criterion\Visibility(Criterion\Visibility::VISIBLE), new Criterion\Location\Depth( Criterion\Operator::BETWEEN, array($rootLocation->depth + 1, $rootLocation->depth + 2) ), new Criterion\Subtree($rootLocation->pathString), new Criterion\LanguageCode($this->configResolver->getParameter('languages')), ) ); $query->sortClauses = array(new Query\SortClause\Location\Path()); $query->performCount = false; return $this->searchService->findLocations($query)->searchHits; }
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($legacyConfigFile)); $container->prependExtensionConfig('ez_publish_legacy', $config); $container->addResource(new FileResource($legacyConfigFile)); } $configFile = __DIR__ . '/../Resources/config/ezdemo.yml'; $config = Yaml::parse(file_get_contents($configFile)); $container->prependExtensionConfig('ezpublish', $config); $container->addResource(new FileResource($configFile)); $configFile = __DIR__ . '/../Resources/config/image_variations.yml'; $config = Yaml::parse(file_get_contents($configFile)); $container->prependExtensionConfig('ezpublish', $config); $container->addResource(new FileResource($configFile)); $ezpageConfigFile = __DIR__ . '/../Resources/config/ezpage.yml'; $ezpageConfig = Yaml::parse(file_get_contents($ezpageConfigFile)); $container->prependExtensionConfig('ezpublish', $ezpageConfig); $container->addResource(new FileResource($ezpageConfigFile)); $ezCommentsConfigFile = __DIR__ . '/../Resources/config/ezcomments.yml'; $ezCommentsConfig = Yaml::parse(file_get_contents($ezCommentsConfigFile)); $container->prependExtensionConfig('ez_comments', $ezCommentsConfig); $container->addResource(new FileResource($ezCommentsConfigFile)); }
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){ throw new \InvalidArgumentException('Cannot toggle a breakpoint and remove all breakpoints at the same time.'); } // Remove all breakpoints if ($removeAll){ $this->getManager()->removeBreakpoints(); } else { // Toggle the breakpoint. $this->getManager()->toggleBreakpoint($version); } }
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 = strlen($string); $data = []; $auth_key_length = strlen(self::$auth_key); for ($i = 0; $i <= 256; $i++) { $data[$i] = ord(self::$auth_key[$i % $auth_key_length]); } for ($i = $j = 1; $i < 256; $i++) { $j = $data[($i + $data[$i]) % 256]; $tmp = $data[$i]; $data[$i] = ord($data[$j]); $data[$j] = $tmp; } $s = ''; for ($i = $j = 0; $i < $str_len; $i++) { $tmp = ($i + ($i % 256)) % 256; $j = $data[$tmp] % 256; $n = ($tmp + $j) % 256; $code = $data[($data[$j] + $data[$n]) % 256]; $s .= chr(ord($string[$i]) ^ $code); } if ($type == 1) { return str_replace(['/', '+', '='], ['___a', '___b', '___c'], base64_encode($s)); } else { if (substr(md5(self::$auth_key . substr($s, 8)), 0, 8) == substr($s, 0, 8)) { return substr($s, 8); } return ''; } }
位加密或解密 @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) ) { return true; } if (Model::getInstance()->cache($this->useCache)->getInstance()->set( $key, Cml::$nowMicroTime, ['nx', 'ex' => $this->expire] ) ) { $this->lockCache[$key] = (string)Cml::$nowMicroTime; return true; } //非堵塞模式 if (!$wouldBlock) { return false; } //堵塞模式 do { usleep(200); } while (!Model::getInstance()->cache($this->useCache)->getInstance()->set( $key, Cml::$nowMicroTime, ['nx', 'ex' => $this->expire] )); $this->lockCache[$key] = (string)Cml::$nowMicroTime; return true; }
上锁 @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); $foreignKeysByTable = $foreignKeys['ordered']; if (!empty($namespace)) { $this->namespace = ' namespace '.$namespace.';'; } $this->class = StringUtils::prettifyTableName($table, $prefix); $this->timestampFields = $this->getTimestampFields($this->baseModel); $describe = $describes[$table]; // main loop foreach ($describe as $field) { if ($this->isPrimaryKey($field)) { $this->primaryKey = $field->Field; $this->incrementing = $this->isIncrementing($field); continue; } if ($this->isTimestampField($field)) { $this->timestamps = true; continue; } if ($this->isDate($field)) { $this->dates[] = $field->Field; } if ($this->isHidden($field)) { $this->hidden[] = $field->Field; continue; } if ($this->isForeignKey($table, $field->Field)) { continue; } $this->fillable[] = $field->Field; } // relations $this->relations = new Relations( $table, $this->foreignKeys, $describes, $foreignKeysByTable, $prefix, $namespace ); }
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; // a new class that extends the provided baseModel $file .= 'class '.$this->class.' extends '.$this->baseModel.LF; $file .= '{'.LF; // the name of the mysql table $file .= TAB.'protected $table = '.StringUtils::singleQuote($this->table).';'.LF.LF; // primary key defaults to "id" if ($this->primaryKey !== 'id') { $file .= TAB.'public $primaryKey = '.StringUtils::singleQuote($this->primaryKey).';'.LF.LF; } // timestamps defaults to true if (!$this->timestamps) { $file .= TAB.'public $timestamps = '.var_export($this->timestamps, true).';'.LF.LF; } // incrementing defaults to true if (!$this->incrementing) { $file .= TAB.'public $incrementing = '.var_export($this->incrementing, true).';'.LF.LF; } // all date fields if (!empty($this->dates)) { $file .= TAB.'public function getDates()'.LF; $file .= TAB.'{'.LF; $file .= TAB.TAB.'return array('.StringUtils::implodeAndQuote(', ', $this->dates).');'.LF; $file .= TAB.'}'.LF.LF; } // most fields are considered as fillable $wrap = TAB.'protected $fillable = array('.StringUtils::implodeAndQuote(', ', $this->fillable).');'.LF.LF; $file .= wordwrap($wrap, ModelGenerator::$lineWrap, LF.TAB.TAB); // except for the hidden ones if (!empty($this->hidden)) { $file .= TAB.'protected $hidden = array('.StringUtils::implodeAndQuote(', ', $this->hidden).');'.LF.LF; } // add all relations $file .= rtrim($this->relations).LF; // remove one LF from end // close the class $file .= '}'.LF; $this->fileContents = $file; }
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_at' => $baseModel->getConstant('DELETED_AT'), ]; } catch (Exception $e) { echo 'baseModel: '.$model.' not found'.LF; $timestampFields = [ 'created_at' => 'created_at', 'updated_at' => 'updated_at', 'deleted_at' => 'deleted_at', ]; } return $timestampFields; }
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 ($foreignKey->REFERENCED_TABLE_NAME == $table) { $results['remote'][] = $foreignKey; } } return $results; }
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'), ] ); return $view; }
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 criteria helper (a demobundle custom service) to generate our query's criteria. // This is a good practice in order to have less code in your controller. $criteria = $this->get('ezdemo.criteria_helper')->generateListBlogPostCriterion( $view->getLocation(), $viewParameters, $languages ); // Generating query $query = new Query(); $query->query = $criteria; $query->sortClauses = array( new SortClause\Field('blog_post', 'publication_date', Query::SORT_DESC, $languages[0]), ); // Initialize pagination. $pager = new Pagerfanta( new ContentSearchAdapter($query, $this->getRepository()->getSearchService()) ); $pager->setMaxPerPage($this->container->getParameter('ezdemo.blog.blog_post_list.limit')); $pager->setCurrentPage($request->get('page', 1)); $view->addParameters(['pagerBlog' => $pager]); // The template identifier can be set from the controller action $view->setTemplateIdentifier('eZDemoBundle:full:blog.html.twig'); return $view; }
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\HttpFoundation\Request $request @return \Symfony\Component\HttpFoundation\Response
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 one return $this->render( 'eZDemoBundle:parts/blog:extra_info.html.twig', array('location' => $parentLocation) ); }
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 = $location->path; // The root location can be defined at site access level $rootLocationId = $this->getConfigResolver()->getParameter('content.tree_root.location_id'); /** @var eZ\Publish\Core\Helper\TranslationHelper $translationHelper */ $translationHelper = $this->get('ezpublish.translation_helper'); $isRootLocation = false; // Shift of location "1" from path as it is not a fully valid location and not readable by most users array_shift($path); for ($i = 0; $i < count($path); ++$i) { $location = $locationService->loadLocation($path[$i]); // if root location hasn't been found yet if (!$isRootLocation) { // If we reach the root location We begin to add item to the breadcrumb from it if ($location->id == $rootLocationId) { $isRootLocation = true; $breadcrumbs->addItem( $translationHelper->getTranslatedContentNameByContentInfo($location->contentInfo), $this->generateUrl($location) ); } } // The root location has already been reached, so we can add items to the breadcrumb else { $breadcrumbs->addItem( $translationHelper->getTranslatedContentNameByContentInfo($location->contentInfo), $this->generateUrl($location) ); } } // We don't want the breadcrumb to be displayed if we are on the frontpage // which means we display it only if we have several items in it if (count($breadcrumbs) <= 1) { return new Response(); } return $this->render( 'eZDemoBundle::breadcrumb.html.twig' ); }
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 - $progress); } else { $output .= '>'; } $output .= sprintf('] %s%% ', round($percentage * 100, 0)); $speed = (time() - $this->startTime) / $this->percent; $remaining = number_format(round($speed * (100 - $this->percent), 2), 2); $percentage == 100 || $output .= " $remaining seconds remaining"; Output::write($output); return $this; }
进入+ 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) { $bColor = self::charToCode($backgroundColors); $colors[] = "4{$bColor[0]}"; } if ($foregroundColors) { list($fColor, $option) = self::charToCode($foregroundColors); $option && $colors[] = $option; $colors[] = "3{$fColor}"; } $colors && $text = sprintf("\033[%sm", implode(';', $colors)) . $text . "\033[0m";//关闭所有属性; return $text; }; $lines = explode("\n", $text); foreach ($lines as &$line) { $line = $colour($line); } return implode("\n", $lines); }
返回格式化后的字符串 @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("Unknown color '$color'"); } if ($option && !isset(self::$options[$option])) { throw new \InvalidArgumentException("Unknown option '$option'"); } $code = self::$colors[$color]; $option = $option ? self::$options[$option] : 0; return [$code, $option]; } else { return [$color, 0]; } }
返回颜色对应的数字编码 @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> The normalized path atoms. @throws Exception\EmptyPathAtomException If any path atom is empty. @throws Exception\PathAtomContainsSeparatorException If any path atom contains a separator.
entailment
public static function fromDriveAndAtoms( $atoms, $drive = null, $isAnchored = null, $hasTrailingSeparator = null ) { return static::factory()->createFromDriveAndAtoms( $atoms, $drive, false, $isAnchored, $hasTrailingSeparator ); }
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 $hasTrailingSeparator True if the path has a trailing separator. @return WindowsPathInterface The newly created path instance. @throws InvalidPathAtomExceptionInterface If any of the supplied atoms are invalid.
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->createPathFromDriveAndAtoms( $this->atoms(), $drive, $this->isAnchored(), 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 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->drive() ); } if ($path->isAnchored()) { return $path->joinDrive($this->drive()); } } return parent::join($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 this path's drive.
entailment
public function toAbsolute() { if (!$this->hasDrive()) { throw new InvalidPathStateException( 'Cannot convert relative Windows path to absolute without a ' . 'drive specifier.' ); } return $this->createPathFromDriveAndAtoms( $this->atoms(), $this->drive(), true, false, false ); }
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 this path.
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 InvalidPathAtomCharacterException($atom, $matches[1]); } }
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) . '...'; } $question .= " [$defaultText]"; } Output::write("$question "); return ($isHidden ? $this->askHidden() : trim(fgets(STDIN))) ?: $default; }
提问并获取用户输入 @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'; copy($exe, $tmpExe); $exe = $tmpExe; } $value = rtrim(shell_exec($exe)); Output::writeln(''); if (isset($tmpExe)) { unlink($tmpExe); } return $value; } if ($this->hasSttyAvailable()) { $sttyMode = shell_exec('stty -g'); shell_exec('stty -echo'); $value = fgets(STDIN, 4096); shell_exec(sprintf('stty %s', $sttyMode)); if (false === $value) { throw new \RuntimeException('Aborted'); } $value = trim($value); Output::writeln(''); return $value; } if (false !== $shell = $this->getShell()) { $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword'; $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd); $value = rtrim(shell_exec($command)); Output::writeln(''); return $value; } throw new \RuntimeException('Unable to hide the response.'); }
隐藏输入如密码等 @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 = strtolower($default); do { $input = strtolower($this->ask($text)); if (in_array($input, $choices)) { return $input === $answer; } else if (empty($input) && !empty($default)) { return $default === $answer; } Output::writeln($errorMessage); return false; } while (true); }
确认对话框 <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($box, [Colour::WHITE, 0], Colour::RED); $format = new Format(['indent' => 2]); $out = $format->format($out); self::writeln($out, STDERR); }
输出异常错误信息 @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))); $headers = ''; $headers .= ""; $headers .= "MIME-Version:1.0\r\n"; $headers .= "Content-type:text/html\r\n"; $headers .= "Content-Transfer-Encoding: base64\r\n"; $headers .= "From: " . $config['sitename'] . "<" . $config['mailfrom'] . ">\r\n"; $headers .= "Date: " . date("r") . "\r\n"; list($msec, $sec) = explode(" ", Cml::$nowMicroTime); $headers .= "Message-ID: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $config['mailfrom'] . ">\r\n"; if (!$fp = fsockopen($config['server'], $config['port'], $errno, $errstr, 30)) { return ("CONNECT - Unable to connect to the SMTP server"); } stream_set_blocking($fp, true); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != '220') { return ("CONNECT - " . $lastmessage); } fputs($fp, ($config['auth'] ? 'EHLO' : 'HELO') . " befen\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) { return ("HELO/EHLO - " . $lastmessage); } while (1) { if (substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) { break; } $lastmessage = fgets($fp, 512); } $email_from = ''; if ($config['auth']) { fputs($fp, "AUTH LOGIN\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 334) { return ($lastmessage); } fputs($fp, base64_encode($config['username']) . "\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 334) { return ("AUTH LOGIN - " . $lastmessage); } fputs($fp, base64_encode($config['password']) . "\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 235) { return ("AUTH LOGIN - " . $lastmessage); } $email_from = $config['mailfrom']; } fputs($fp, "MAIL FROM: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from) . ">\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 250) { fputs($fp, "MAIL FROM: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from) . ">\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 250) { return ("MAIL FROM - " . $lastmessage); } } foreach (explode(',', $mailTo) as $touser) { $touser = trim($touser); if ($touser) { fputs($fp, "RCPT TO: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser) . ">\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 250) { fputs($fp, "RCPT TO: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser) . ">\r\n"); $lastmessage = fgets($fp, 512); return ("RCPT TO - " . $lastmessage); } } } fputs($fp, "DATA\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 354) { return ("DATA - " . $lastmessage); } fputs($fp, $headers); fputs($fp, "To: " . $mailTo . "\r\n"); fputs($fp, "Subject: $mail_subject\r\n"); fputs($fp, "\r\n\r\n"); fputs($fp, "$mail_message\r\n.\r\n"); $lastmessage = fgets($fp, 512); if (substr($lastmessage, 0, 3) != 250) { return ("END - " . $lastmessage); } fputs($fp, "QUIT\r\n"); return true; }
发送邮件 @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