sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function fetchResults($query, $page = 1, $maxPerPage = 10, $filter = false, $paginate = false) { if ($paginate) { if (!$this->pager) { throw new \Exception('Please inject a pager on ResultBuilder'); } $results = $this->pager->paginate($query, $page...
@param mixed $query target @param int $page page @param int $maxPerPage maxPerPage @param boolean $filter filter @param boolean $paginate paginate @throws \Exception @return \Traversable
entailment
public function filter($collection) { if (!$this->sorted) { $this->sortFilters(); } if (!is_array($collection) && !$collection instanceof \Traversable) { throw new \Exception('Collection must be an array or traversable'); } foreach ($this->filters as...
{@inheritdoc}
entailment
protected function sortFilters() { usort($this->filters, function (FilterInterface $a, FilterInterface $b) { $a = $a->getPriority(); $b = $b->getPriority(); if ($a == $b) { return 0; } return $a < $b ? -1 : 1; }); ...
Sort filters by priority.
entailment
public function get($namespace, $index) { if (!isset($this->storage[$namespace][$index])) { return null; } return $this->storage[$namespace][$index]; }
Returns key from local storage @param string $namespace @param int $index @return string|null
entailment
public function formatTime($time) { if ($this->timeFormat === null || $this->timeFormat === false) { return $time; } $dateTime = new \DateTime($time); if ($this->timeFormat === true) { return $dateTime; } return $dateTime->format($this->time...
Converts time to previously set format. @param string $time @return \DateTime|string
entailment
public function buildContainer() { if (!class_exists('\Pimple')) { throw new \Exception('Please install Pimple.'); } $c = new \Pimple(); // ---- classes ---- // filters $c['filter.manager.class'] = 'Spy\Timeline\Filter\FilterManager'; ...
Build default container.
entailment
public function accept() { /** * @var \SplFileInfo $file */ $file = $this->current(); if ($file->getType()==$this->getType()) { return true; } return false; }
filter iterator element @return bool
entailment
public function execute($params = null) { if ($this->_statement instanceof BufferedStatement) { $this->_statement = $this->_statement->getInnerStatement(); } if ($this->_bufferResults) { $this->_statement = new BufferedStatement($this->_statement, $this->_driver); ...
{@inheritDoc}
entailment
public function fetch($type = 'num') { $row = parent::fetch($type); if ($type == 'assoc' && is_array($row) && !empty($this->_driver->autoShortenedIdentifiers)) { //Need to preserve order of row results $translatedRow = []; foreach ($row as $key => $val) { ...
VERY HACKY: Override fetch to UN-auto-shorten identifiers, which is done in OracleDialectTrait "quoteIdentifier" {@inheritDoc}
entailment
public function savePositionAction(Request $request): Response { $this->setSubject($request->get('block_id')); $this->admin->checkAccess('savePosition'); try { $params = $request->get('disposition'); if (!\is_array($params)) { throw new HttpException...
@param Request $request @return Response
entailment
public function switchParentAction(Request $request): Response { $blockId = $request->get('block_id'); $parentId = $request->get('parent_id'); if (null === $blockId or null === $parentId) { throw new HttpException(400, 'wrong parameters'); } $block = $this->setSu...
@param Request $request @throws HttpException @throws NotFoundHttpException @return Response
entailment
public function composePreviewAction(Request $request): Response { $block = $this->setSubject($request->get('block_id')); $this->admin->checkAccess('composePreview'); $container = $block->getParent(); if (!$container) { throw $this->createNotFoundException('No parent fou...
@param Request $request @throws NotFoundHttpException @return Response
entailment
private function setSubject($blockId): BaseBlock { /** @var BaseBlock $block */ $block = $this->admin->getObject($blockId); if (!$block) { throw $this->createNotFoundException(sprintf('Unable to find block with id %d', $blockId)); } $this->admin->setSubject($block...
Initialize the admin subject, to contextualize checkAccess verification. @param mixed $blockId @throws NotFoundHttpException @return BaseBlock
entailment
public function findActionsForIds(array $ids) { if (empty($ids)) { return array(); } $datas = $this->client->hmget($this->getActionKey(), $ids); return array_values( array_map( function ($v) { return unserialize($v); ...
@param array $ids ids @return array
entailment
public function paginate($target, $page = 1, $limit = 10) { if (null === $this->paginator) { throw new \LogicException(sprintf('Knp\Component\Pager\Paginator not injected in constructor of %s', __CLASS__)); } $this->page = $page; $this->pager = $this->paginator->paginat...
{@inheritdoc}
entailment
protected function _insertQueryTranslator($query) { $v = $query->clause('values'); if (count($v->values()) === 1 || $v->query()) { return $query; } $newQuery = $query->getConnection()->newQuery(); $cols = $v->columns(); $placeholder = 0; $replaceQ...
Transforms an insert query that is meant to insert multiple rows at a time, otherwise it leaves the query untouched. The way Oracle works with multi insert is by having multiple "SELECT FROM DUAL" select statements joined with UNION. @param \Cake\Database\Query $query The query to translate @return \Cake\Database\Que...
entailment
public function quoteIdentifier($identifier) { if (preg_match('/^[\w-]+$/', $identifier) && strlen($identifier) > 30) { $key = array_search($identifier, $this->autoShortenedIdentifiers); if ($key === false) { $key = 'XXAUTO_SHORTENED_ID' . (count($this->autoShortenedI...
VERY HACKY: To avoid Oracle's "No identifiers > 30 characters" restriction, at this very low level we'll auto-replace Cake automagic aliases like 'SomeLongTableName__some_really_long_field_name' with 'XXAUTO_SHORTENED_ID[n]' where [n] is a simple incrementing integer. Then in OracleStatement's "fetch" function, we'll u...
entailment
protected function prepareParsedData(array $matches) { $result = parent::prepareParsedData($matches); // Convert time $result['time'] = $this->formatTime($result['time']); return $result; }
{@inheritdoc}
entailment
public function countActions(ComponentInterface $subject, $status = ActionInterface::STATUS_PUBLISHED) { if ($status != ActionInterface::STATUS_PUBLISHED) { throw new \Exception('Method '.__METHOD__.' can only retrieve action published'); } $redisKey = $this->getSubjectRedisKey(...
{@inheritdoc}
entailment
public function getSubjectActions(ComponentInterface $subject, array $options = array()) { $resolver = new OptionsResolver(); $resolver->setDefaults(array( 'page' => 1, 'max_per_page' => 10, 'filter' => true, 'paginate' => false, ...
{@inheritdoc}
entailment
public function updateAction(ActionInterface $action) { $action->setId($this->getNextId()); $this->client->hset($this->getActionKey(), $action->getId(), serialize($action)); $this->deployActionDependOnDelivery($action); }
{@inheritdoc}
entailment
public function findOrCreateComponent($model, $identifier = null, $flush = true) { return $this->createComponent($model, $identifier, $flush); }
{@inheritdoc}
entailment
public function createComponent($model, $identifier = null, $flush = true) { $resolvedComponentData = $this->resolveModelAndIdentifier($model, $identifier); // we do not persist component on redis driver. return $this->getComponentFromResolvedComponentData($resolvedComponentData); }
{@inheritdoc}
entailment
public function findComponents(array $concatIdents) { $components = array(); foreach ($concatIdents as $concatIdent) { $component = new $this->componentClass(); $components[] = $component->createFromHash($concatIdent); } return $components; }
{@inheritdoc}
entailment
public function findComponentWithHash($hash) { $component = new $this->componentClass(); $component = $component->createFromHash($hash); return $component; }
{@inheritdoc}
entailment
public function writeLine($string) { $string = rtrim($string, "\n\r") . PHP_EOL; if ($this->getFileObject()->fwrite($string) === false) { // return written bytes or null on error throw new FileWriterException('write line to file failed.'); } return $this; ...
add string to file @param string $string file content @return FileWriterInterface @throws FileWriterException
entailment
public function retrieveByToken($identifier, $token) { return $this->query->filterById($identifier) ->filterByRememberToken($token) ->findOne(); }
Retrieve a user by by their unique identifier and "remember me" token. @param mixed $identifier @param string $token @return \Illuminate\Contracts\Auth\Authenticatable|null
entailment
public function updateRememberToken(UserContract $user, $token) { $this->query->filterById($user->getAuthIdentifier()) ->update(['RememberToken' => $token]); }
Update the "remember me" token for the given user in storage. @param \Illuminate\Contracts\Auth\Authenticatable $user @param string $token @return void
entailment
public function retrieveByCredentials(array $credentials) { $query = $this->query; $user_class = \Config::get('auth.model'); foreach ($credentials as $key => $value) { if ( ! str_contains($key, 'password')) { $query->where("{$user_class}.{$key...
Retrieve a user by the given credentials. @param array $credentials @return \Illuminate\Contracts\Auth\Authenticatable|null
entailment
public function create($subject, $verb, array $components = array()) { /** @var $action ActionInterface */ $action = new $this->actionClass(); $action->setVerb($verb); if (!$subject instanceof ComponentInterface and !is_object($subject)) { throw new \Exception('Subject m...
{@inheritdoc}
entailment
protected function deployActionDependOnDelivery(ActionInterface $action) { if ($this->deployer && $this->deployer->isDeliveryImmediate()) { $this->deployer->deploy($action, $this); } }
@param ActionInterface $action action @return void
entailment
public function getComponentDataResolver() { if (empty($this->componentDataResolver) || !$this->componentDataResolver instanceof ComponentDataResolverInterface ) { throw new \Exception('Component data resolver not set'); } return $this->componentDataResolver; }
Gets the component data resolver. @return ComponentDataResolverInterface @throws \Exception When no component data resolver has been set
entailment
protected function resolveModelAndIdentifier($model, $identifier) { $resolve = new ResolveComponentModelIdentifier($model, $identifier); return $this->getComponentDataResolver()->resolveComponentData($resolve); }
Resolves the model and identifier. @param string|object $model @param null|string|array $identifier @return ResolvedComponentData
entailment
protected function getComponentFromResolvedComponentData(ResolvedComponentData $resolved) { /** @var $component ComponentInterface */ $component = new $this->componentClass(); $component->setModel($resolved->getModel()); $component->setData($resolved->getData()); $component->...
Creates a new component object from the resolved data. @param ResolvedComponentData $resolved The resolved component data @return ComponentInterface The newly created and populated component
entailment
public function registerParameters(ContainerBuilder $container, array $config): void { $container->setParameter('sonata.dashboard.block.class', $config['class']['block']); $container->setParameter('sonata.dashboard.dashboard.class', $config['class']['dashboard']); $container->setParameter('...
Registers service parameters from bundle configuration. @param ContainerBuilder $container Container builder @param array $config Array of configuration
entailment
private function array2xml($arr, $level = 1) { $str = ($level == 1) ? "<?xml version=\"1.0\" encoding=\"" . Config::get('default_charset') . "\"?>\r\n<root>\r\n" : ''; $space = str_repeat("\t", $level); foreach ($arr as $key => $val) { if (is_numeric($key)) { $key...
数组转xml @param array $arr 要转换的数组 @param int $level 层级 @return string
entailment
public function normalize(PathInterface $path) { if ($path instanceof AbsolutePathInterface) { return $this->normalizeAbsolutePath($path); } return $this->normalizeRelativePath($path); }
Normalize the supplied path to its most canonical form. @param PathInterface $path The path to normalize. @return PathInterface The normalized path.
entailment
protected function normalizeAbsolutePath(AbsolutePathInterface $path) { return $this->factory()->createFromAtoms( $this->normalizeAbsolutePathAtoms($path->atoms()), true, false ); }
Normalize the supplied absolute path. @param AbsolutePathInterface $path The path to normalize. @return AbsolutePathInterface The normalized path.
entailment
protected function normalizeRelativePath(RelativePathInterface $path) { return $this->factory()->createFromAtoms( $this->normalizeRelativePathAtoms($path->atoms()), false, false ); }
Normalize the supplied relative path. @param RelativePathInterface $path The path to normalize. @return RelativePathInterface The normalized path.
entailment
protected function normalizeAbsolutePathAtoms(array $atoms) { $resultingAtoms = array(); foreach ($atoms as $atom) { if (AbstractPath::PARENT_ATOM === $atom) { array_pop($resultingAtoms); } elseif (AbstractPath::SELF_ATOM !== $atom) { $resultin...
Normalize the supplied path atoms for an absolute path. @param array<string> $atoms The path atoms to normalize. @return array<string> The normalized path atoms.
entailment
protected function normalizeRelativePathAtoms(array $atoms) { $resultingAtoms = array(); $resultingAtomsCount = 0; $numAtoms = count($atoms); for ($i = 0; $i < $numAtoms; $i++) { if (AbstractPath::SELF_ATOM !== $atoms[$i]) { $resultingAtoms[] = $atoms[$i]...
Normalize the supplied path atoms for a relative path. @param array<string> $atoms The path atoms to normalize. @return array<string> The normalized path atoms.
entailment
public function log($level, $message, array $context = []) { return error_log($this->format($message, $context) . "\r\n", 3, $this->logDir . $level . '.log'); }
任意等级的日志记录 @param mixed $level 日志等级 @param string $message 要记录到log的信息 @param array $context 上下文信息 @return null
entailment
public static function autoloadComposerAdditional($className) { $className == 'Cml\Server' && class_alias('Cml\Service', 'Cml\Server');//兼容旧版本 self::$debug && Debug::addTipInfo(Lang::get('_CML_DEBUG_ADD_CLASS_TIP_', $className), Debug::TIP_INFO_TYPE_INCLUDE_LIB);//在debug中显示包含的类 }
自动加载类库 要注意的是 使用autoload的时候 不能手动抛出异常 因为在自动加载静态类时手动抛出异常会导致自定义的致命错误捕获机制和自定义异常处理机制失效 而 new Class 时自动加载不存在文件时,手动抛出的异常可以正常捕获 这边即使文件不存在时没有抛出自定义异常也没关系,因为自定义的致命错误捕获机制会捕获到错误 @param string $className
entailment
private static function handleConfigLang() { //引入框架惯例配置文件 $cmlConfig = Cml::requireFile(CML_CORE_PATH . DIRECTORY_SEPARATOR . 'Config' . DIRECTORY_SEPARATOR . 'config.php'); Config::init(); //应用正式配置文件 $appConfig = Cml::getApplicationDir('global_config_path') . DIRECTORY_SEPA...
处理配置及语言包相关
entailment
private static function init() { define('CML_PATH', dirname(__DIR__)); //框架的路径 define('CML_CORE_PATH', CML_PATH . DIRECTORY_SEPARATOR . 'Cml');// 系统核心类库目录 define('CML_EXTEND_PATH', CML_PATH . DIRECTORY_SEPARATOR . 'Vendor');// 系统扩展类库目录 self::handleConfigLang(); //后面自动载入的类都会...
初始化运行环境
entailment
public static function runApp(callable $initDi) { self::$run = true; self::onlyInitEnvironmentNotRunController($initDi); Plugin::hook('cml.before_run_controller'); $controllerAction = Cml::getContainer()->make('cml_route')->getControllerAndAction(); if ($controllerAction)...
启动应用 @param callable $initDi 注入依赖
entailment
public static function montFor404Page() { Plugin::mount('cml.before_show_404_page', [ function () { $cmdLists = Config::get('cmlframework_system_route'); $pathInfo = Route::getPathInfo(); $cmd = strtolower(trim($pathInfo[0], '/')); ...
未找到控制器的时候设置勾子
entailment
public static function cmlStop() { //输出Debug模式的信息 if (self::$debug) { header('Content-Type:text/html; charset=' . Config::get('default_charset')); Debug::stop(); } else { $deBugLogData = dump('', 1); if (!empty($deBugLogData)) { ...
程序中并输出调试信息
entailment
public static function doteToArr($key = '', &$arr = [], $default = null) { if (!strpos($key, '.')) { return isset($arr[$key]) ? $arr[$key] : $default; } // 获取多维数组 $key = explode('.', $key); $tmp = null; foreach ($key as $k) { if (is_null($tmp)...
以.的方式获取数组的值 @param string $key @param array $arr @param null $default @return null
entailment
public static function showSystemTemplate($tpl) { $configSubFix = Config::get('html_template_suffix'); Config::set('html_template_suffix', ''); echo View::getEngine('html') ->setHtmlEngineOptions('templateDir', dirname($tpl) . DIRECTORY_SEPARATOR) ->fetch(basename($tp...
渲染显示系统模板 @param string $tpl 要渲染的模板文件
entailment
public static function setApplicationDir(array $dir) { if (DIRECTORY_SEPARATOR == '\\') {//windows array_walk($dir, function (&$val) { $val = str_replace('/', DIRECTORY_SEPARATOR, $val); }); } self::$appDir = array_merge(self::$appDir, $dir); }
设置应用路径 @param array $dir
entailment
public static function requireFile($file, $args = []) { empty($args) || extract($args, EXTR_PREFIX_SAME, "xxx"); Cml::$debug && Debug::addTipInfo($file, Debug::TIP_INFO_TYPE_INCLUDE_FILE); return require $file; }
require 引入文件 @param string $file 要引入的文件 @param array $args 要释放的变量 @return mixed
entailment
public static function setWarningLogLevel($level) { if (is_array($level)) { self::$warningLogLevel = $level; } else { self::$warningLogLevel[] = $level; } }
设置警告日志的等级列表 @param array|int $level
entailment
public static function setFatalErrorLogLevel($level) { if (is_array($level)) { self::$fatalErrorLogLevel = $level; } else { self::$fatalErrorLogLevel[] = $level; } }
设置警告日志的等级列表 @param array|int $level
entailment
public function unlock($key) { $key = $this->getKey($key); if ( isset($this->lockCache[$key]) && $this->lockCache[$key] == Model::getInstance()->cache($this->useCache)->getInstance()->get($key) ) { Model::getInstance()->cache($this->useCache)->getInstance...
解锁 @param string $key @return void
entailment
protected function findType($foreignKey, $remote) { if ($remote) { if ($this->isBelongsToMany($foreignKey)) { return 'belongsToMany'; } if ($this->isHasOne($foreignKey)) { return 'hasOne'; } return 'hasMany'; ...
Try to determine the type of the relation. @param $foreignKey @param $remote @return string
entailment
protected function isHasOne($foreignKey) { $remote = $this->describes[$foreignKey->TABLE_NAME]; foreach ($remote as $field) { if ($field->Key == 'PRI') { if ($field->Field == $foreignKey->COLUMN_NAME) { return true; } } ...
One to one: The relationship is from a primary key to another primary key. @param $foreignKey @return bool
entailment
protected function isBelongsToMany($foreignKey) { $remote = $this->describes[$foreignKey->TABLE_NAME]; $count = 0; foreach ($remote as $field) { if ($field->Key == 'PRI') { $count++; } } if ($count == 2) { return true; ...
Many to many. @param $foreignKey @return bool
entailment
public function createFromAtoms( $atoms, $isAbsolute = null, $hasTrailingSeparator = null ) { return $this->factoryByPlatform()->createFromAtoms( $atoms, $isAbsolute, $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 ...
entailment
public static function showTables($prefix) { $results = static::select('SHOW FULL TABLES'); $tables = []; $views = []; $first = ''; foreach ($results as $result) { // get the first element (table name) foreach ($result as $value) { $fi...
Execute a SHOW TABLES query. @return array with 'tables' and 'views'
entailment
public static function get($key = null, $default = '') { if (empty($key)) { return ''; } $key = strtolower($key); $val = Cml::doteToArr($key, self::$lang); if (is_null($val)) { return is_array($default) ? '' : $default; } else { if...
获取语言 不区分大小写 获取值的时候可以动态传参转出语言值 如:\Cml\Lang::get('_CML_DEBUG_ADD_CLASS_TIP_', '\Cml\Base') 取出_CML_DEBUG_ADD_CLASS_TIP_语言变量且将\Cml\base替换语言中的%s @param string $key 支持.获取多维数组 @param string $default 不存在的时候默认值 @return string
entailment
public static function set($key, $value = null) { if (is_array($key)) { static::$lang = array_merge(static::$lang, array_change_key_case($key)); } else { $key = strtolower($key); if (!strpos($key, '.')) { static::$lang[$key] = $value; ...
设置配置【语言】 支持批量设置 /a.b.c方式设置 @param string|array $key 要设置的key,为数组时是批量设置 @param mixed $value 要设置的值 @return null
entailment
public function generateListFolderCriterion(Location $location, array $excludeContentTypeIdentifiers = array(), array $languages = array()) { $criteria = array(); $criteria[] = new Criterion\Visibility(Criterion\Visibility::VISIBLE); $criteria[] = new Criterion\ParentLocationId($location->id...
Generate criterion list to be used to list article. @param \eZ\Publish\API\Repository\Values\Content\Location $location Location of the folder @param string[] $excludeContentTypeIdentifiers Array of excluded contentType identifiers @param string[] $languages Array of languages @return \eZ\Publish\API\Repository\Value...
entailment
public function generateSubContentCriterion(Location $location, array $includedContentTypeIdentifiers = array(), array $languages = array()) { $criteria = array(); $criteria[] = new Criterion\Visibility(Criterion\Visibility::VISIBLE); $criteria[] = new Criterion\ContentTypeIdentifier($includ...
Generate criterion list to be used to list sub folder items. @param \eZ\Publish\API\Repository\Values\Content\Location $location Location of the folder @param string[] $includedContentTypeIdentifiers Array of included contentType identifiers @param string[] $languages Array of languages @return \eZ\Publish\API\Reposi...
entailment
public function generateContentTypeExcludeCriterion(array $excludeContentTypeIdentifiers) { $excludeCriterion = array(); foreach ($excludeContentTypeIdentifiers as $contentTypeIdentifier) { $excludeCriterion[] = new Criterion\LogicalNot( new Criterion\ContentTypeIdentifie...
Generates an exclude criterion based on contentType identifiers. @param array $excludeContentTypeIdentifiers @return \eZ\Publish\API\Repository\Values\Content\Query\Criterion\LogicalAnd
entailment
public function generateLocationIdExcludeCriterion(array $excludeLocations) { $excludeCriterion = array(); foreach ($excludeLocations as $location) { if (!$location instanceof Location) { throw new InvalidArgumentType('excludeLocations', 'array of Location objects'); ...
Generates an exclude criterion based on locationIds. @param \eZ\Publish\API\Repository\Values\Content\Location[] $excludeLocations @return \eZ\Publish\API\Repository\Values\Content\Query\Criterion\LogicalNot[] @throws \eZ\Publish\Core\Base\Exceptions\InvalidArgumentType
entailment
public function generateListBlogPostCriterion(Location $location, array $viewParameters, array $languages = array()) { $criteria = array(); $criteria[] = new Criterion\Visibility(Criterion\Visibility::VISIBLE); $criteria[] = new Criterion\Subtree($location->pathString); $criteria[] =...
Generate criterion list to be used to list blog_posts. @param \eZ\Publish\API\Repository\Values\Content\Location $location Location of the blog @param array $viewParameters: View parameters of the blog view @param string[] $languages Array of languages @return \eZ\Publish\API\Repository\Values\Content\Query\Criterion
entailment
public function resolve( AbsolutePathInterface $basePath, PathInterface $path ) { if ($path instanceof AbsolutePathInterface) { return $path; } if ($path instanceof RelativeWindowsPathInterface) { if ($path->isAnchored()) { return $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 format($message, array $context = []) { is_array($context) || $context = [$context]; return '[' . date('Y-m-d H:i:s') . '] ' . Config::get('log_prefix', 'cml_log') . ': ' . $message . ' ' . json_encode($context, JSON_UNESCAPED_UNICODE); }
格式化日志 @param string $message 要记录到log的信息 @param array $context 上下文信息 @return string
entailment
public function create($path) { $drive = null; $isAbsolute = false; $isAnchored = false; $hasTrailingSeparator = false; if ('' === $path) { $atoms = array(AbstractPath::SELF_ATOM); } else { $atoms = preg_split('{[/\\\\]}', $path); } ...
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 ) { return $this->createFromDriveAndAtoms( $atoms, null, $isAbsolute, false, $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 ...
entailment
public function createFromDriveAndAtoms( $atoms, $drive = null, $isAbsolute = null, $isAnchored = null, $hasTrailingSeparator = null ) { if (null === $isAnchored) { $isAnchored = false; } if (null === $isAbsolute) { $isAbsolute ...
Creates a new path instance 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 $isAbsolute True if the path is absolute. @param boolean|null $isAnchored True...
entailment
public function indexAction() { $footerContentId = $this->container->getParameter('ezdemo.footer.content_id'); $footerContent = $this->getRepository()->getContentService()->loadContent($footerContentId); $response = new Response(); $response->setPublic(); $response->setShare...
Footer main action. @return Response
entailment
public function showSwitcherAction(Request $request, RouteReference $routeReference) { /** @var \eZ\Publish\Core\Helper\TranslationHelper $translationHelper */ $translationHelper = $this->container->get('ezpublish.translation_helper'); /** @var \eZ\Publish\Core\MVC\Symfony\Locale\LocaleConve...
@param Request $request @param RouteReference $routeReference Displays the language switcher @return \Symfony\Component\HttpFoundation\Response
entailment
public function connect() { if ($this->connection != null) { $this->disconnect(); } if ($this->config['persistent'] == true) { $tmp = null; $this->connection = @pfsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['time...
创建连接 @return resource
entailment
public function write($data) { if (!$this->connected) { if (!$this->connect()) { return false; } } return fwrite($this->connection, $data, strlen($data)); }
向服务端写数据 @param mixed $data 发送给服务端的数据 @return bool|int
entailment
public function read($length = 1024) { if (!$this->connected) { if (!$this->connect()) { return false; } } if (!feof($this->connection)) { return fread($this->connection, $length); } else { return false; } }
从服务端读取数据 @param int $length 要读取的字节数 @return bool|string
entailment
public function getEnv() { if (Request::isCli()) { return 'cli'; } if (isset($_SERVER['SERVER_NAME'])) { $host = $_SERVER['SERVER_NAME']; } else { $host = $_SERVER['HTTP_HOST']; if ($_SERVER['SERVER_PORT'] != 80) { $hos...
获取当前环境名称 @return string
entailment
public static function fsockopenDownload($url, $conf = [], $timeout = 60) { $return = ''; if (!is_array($conf)) { return $return; } $matches = parse_url($url); isset($matches['host']) || $matches['host'] = ''; isset($matches['path']) || $matches['path'] =...
使用 fsockopen 通过 HTTP 协议直接访问(采集)远程文件 如果主机或服务器没有开启 CURL 扩展可考虑使用 fsockopen 比 CURL 稍慢,但性能稳定 @param string $url 远程URL @param array $conf 其他配置信息 int limit 分段读取字符个数 string post post的内容,字符串或数组,key=value&形式 string cookie 携带cookie访问,该参数是cookie内容 string ip 如果该参数传入,$url将不被使用,ip访问优先 int timeout 采集超时时间 bool block 是否阻塞访问,...
entailment
public static function download($filename, $showName = '', $speedLimit = 0, $dir = CML_PROJECT_PATH . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR) { if (!is_file($filename)) { $filename = $dir . $filename; } if (!is_file($filename)) { ...
下载文件 可以指定下载显示的文件名,并自动发送相应的Header信息 如果指定了content参数,则下载该参数的内容 @param string $filename 下载文件名/要下载的文件的绝对地址 @param string $showName 下载显示的文件名 @param int $speedLimit 是否限速 @param string $dir 当$filename不带路径时。使用本参数的目录做为基础目录 @return bool
entailment
public static function getHeaderInfo($header = '', $echo = true) { ob_start(); $headers = getallheaders(); if (!empty($header)) { $info = $headers[$header]; echo($header . ':' . $info . "\n");; } else { foreach ($headers as $key => $val) { ...
显示HTTP Header 信息 @param string $header @param bool $echo @return string
entailment
public static function mimeContentType($filename) { static $contentType = [ 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'asc' => 'application/pgp', //changed by skwashd - was text/p...
获取文件的mime_content类型 @param string $filename @return string
entailment
public function start() { $tablesAndViews = $this->dataBase->showTables($this->prefix); $this->tables = $tablesAndViews['tables']; $this->views = $tablesAndViews['views']; $this->foreignKeys['all'] = $this->dataBase->getAllForeignKeys(); $this->foreignKeys['ordered'] = $this...
This is where we start. @throws Exception
entailment
protected function isManyToMany($table, $checkForeignKey = true) { $describe = $this->dataBase->describeTable($table); $count = 0; foreach ($describe as $field) { if (count($describe) < 3) { $type = $this->parseType($field->Type); if ($type['type'...
Detect many to many tables. @param $table @param bool $checkForeignKey @return bool
entailment
protected function writeFile($table, $model) { $filename = StringUtils::prettifyTableName($table, $this->prefix).'.php'; if (!is_dir($this->path)) { $oldUMask = umask(0); echo 'creating path: '.$this->path.LF; mkdir($this->path, 0777, true); umask($ol...
Write the actual TableName.php file. @param $table @param Model $model @throws Exception @return array
entailment
protected function parseType($type) { $result = []; // get unsigned $result['unsigned'] = false; $type = explode(' ', $type); if (isset($type[1]) && $type[1] === 'unsigned') { $result['unsigned'] = true; } // int(11) + varchar(255) = $type = var...
Parse int(10) unsigned to something useful. @param string $type @return array
entailment
protected function getAllForeignKeysOrderedByTable() { $results = $this->dataBase->getAllForeignKeys(); $results = ArrayHelpers::orderArrayByValue($results, 'TABLE_NAME'); return $results; }
Return an array with tables, with arrays of foreign keys. @return array|mixed
entailment
protected function isForeignKey($table, $field) { foreach ($this->foreignKeys['all'] as $entry) { if ($entry->COLUMN_NAME == $field && $entry->TABLE_NAME == $table) { return true; } } return false; }
Check if a given field in a table is a foreign key. @param $table @param $field @return bool
entailment
protected function isPrefix($name) { if (empty($this->prefix)) { return true; } return starts_with($name, $this->prefix); }
Check if the given name starts with the current prefix. @param $name @return bool
entailment
public function download($local_file, $ftp_file) { if (empty($local_file) || empty($ftp_file)) return false; $ret = ftp_nb_get($this->linkid, $local_file, $ftp_file, FTP_BINARY); while ($ret == FTP_MOREDATA) { $ret = ftp_nb_continue ($this->linkid); } if ($ret != ...
FTP-文件下载 @param string $local_file 本地文件 @param string $ftp_file Ftp文件 @return bool
entailment
public function makeDir($path) { if (empty($path)) return false; $dir = explode("/", $path); $path = ftp_pwd($this->linkid) . '/'; $ret = true; for ($i=0; $i<count($dir); $i++) { $path = $path . $dir[$i] . '/'; if (!@ftp_chdir($this->linkid, $path)) { ...
FTP-创建目录 @param string $path 路径地址 @return bool
entailment
public function delDir($dir) { $dir = $this->checkpath($dir); if (@!ftp_rmdir($this->linkid, $dir)) { $this->close(); return false; } $this->close(); return true; }
FTP-删除文件目录 @param string $dir 删除文件目录 @return bool
entailment
public function delFile($file) { $file = $this->checkpath($file); if (@!ftp_delete($this->linkid, $file)) { $this->close(); return false; } $this->close(); return true; }
FTP-删除文件 @param string $file 删除文件 @return bool
entailment
public function db($conf = '') { $conf == '' && $conf = $this->getDbConf(); if (is_array($conf)) { $config = $conf; $conf = md5(json_encode($conf)); } else { $config = Config::get($conf); } $config['mark'] = $conf; if (isset($this-...
获取db实例 @param string $conf 使用的数据库配置; @return \Cml\Db\MySql\Pdo | \Cml\Db\MongoDB\MongoDB | \Cml\Db\Base
entailment
public function cache($conf = 'default_cache') { if (is_array($conf)) { $config = $conf; $conf = md5(json_encode($conf)); } else { $config = Config::get($conf); } if (isset(self::$cacheInstance[$conf])) { return self::$cacheInstance[$c...
获取cache实例 @param string $conf 使用的缓存配置; @return \Cml\Cache\Redis | \Cml\Cache\Apc | \Cml\Cache\File | \Cml\Cache\Memcache
entailment
public static function getInstance($table = null, $tablePrefix = null, $db = null) { static $mInstance = []; $class = get_called_class(); $classKey = $class . '-' . $tablePrefix . $table; if (!isset($mInstance[$classKey])) { $mInstance[$classKey] = new $class(); ...
初始化一个Model实例 @param null|string $table 表名 @param null|string $tablePrefix 表前缀 @param null|string|array $db db配置,默认default_db @return \Cml\Model | \Cml\Db\MySql\Pdo | \Cml\Db\MongoDB\MongoDB | \Cml\Db\Base | $this
entailment
public function getTableName($addTablePrefix = false, $addDbName = false) { if (is_null($this->table)) { $tmp = get_class($this); $this->table = strtolower(substr($tmp, strrpos($tmp, '\\') + 1, -5)); } $dbName = $addDbName ? Config::get($this->getDbConf() . '.master....
获取表名 @param bool $addTablePrefix 是否返回带表前缀的完整表名 @param bool $addDbName 是否带上dbname @return string
entailment
public function getByColumn($val, $column = null, $tableName = null, $tablePrefix = null) { is_null($tableName) && $tableName = $this->getTableName(); is_null($tablePrefix) && $tablePrefix = $this->tablePrefix; is_null($column) && $column = $this->db($this->getDbConf())->getPk($tableName, $t...
通过某个字段获取单条数据-快捷方法 @param mixed $val 值 @param string $column 字段名 不传会自动分析表结构获取主键 @param string $tableName 表名 不传会自动从当前Model中$table属性获取 @param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀 @return bool|array
entailment
public function getMultiByColumn($val, $column = null, $tableName = null, $tablePrefix = null) { is_null($tableName) && $tableName = $this->getTableName(); is_null($tablePrefix) && $tablePrefix = $this->tablePrefix; is_null($column) && $column = $this->db($this->getDbConf())->getPk($tableNam...
通过某个字段获取多条数据-快捷方法 @param mixed $val 值 @param string $column 字段名 不传会自动分析表结构获取主键 @param string $tableName 表名 不传会自动从当前Model中$table属性获取 @param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀 @return bool|array
entailment
public function set($data, $tableName = null, $tablePrefix = null) { is_null($tableName) && $tableName = $this->getTableName(); is_null($tablePrefix) && $tablePrefix = $this->tablePrefix; return $this->db($this->getDbConf())->set($tableName, $data, $tablePrefix); }
增加一条数据-快捷方法 @param array $data 要新增的数据 @param string $tableName 表名 不传会自动从当前Model中$table属性获取 @param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀 @return int
entailment