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, $maxPerPage); } else { $results = $this->queryExecutor->fetch($query, $page, $maxPerPage); } if ($filter) { return $this->filterManager->filter($results); } return $results; }
@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 $filter) { $collection = $filter->filter($collection); } return $collection; }
{@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; }); $this->sorted = true; }
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->timeFormat); }
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'; $c['filter.duplicate_key.class'] = 'Spy\Timeline\Filter\DuplicateKey'; $c['filter.data_hydrator.class'] = 'Spy\Timeline\Filter\DataHydrator'; $c['filter.data_hydrator.filter_unresolved'] = false; // notifications $c['unread_notifications.class'] = 'Spy\Timeline\Notification\Unread\UnreadNotificationManager'; // query builder $c['query_builder.factory.class'] = 'Spy\Timeline\Driver\QueryBuilder\QueryBuilderFactory'; $c['query_builder.class'] = 'Spy\Timeline\Driver\QueryBuilder\QueryBuilder'; $c['query_builder.asserter.class'] = 'Spy\Timeline\Driver\QueryBuilder\Criteria\Asserter'; $c['query_builder.operator.class'] = 'Spy\Timeline\Driver\QueryBuilder\Criteria\Operator'; // result builder $c['result_builder.class'] = 'Spy\Timeline\ResultBuilder\ResultBuilder'; // deployer $c['spread.deployer.class'] = 'Spy\Timeline\Spread\Deployer'; $c['spread.entry_collection.class'] = 'Spy\Timeline\Spread\Entry\EntryCollection'; $c['spread.on_subject'] = true; $c['spread.on_global_context'] = true; $c['spread.batch_size'] = 50; $c['spread.delivery'] = 'immediate'; // ---- services ---- // filters $c['filter.manager'] = $c->share(function ($c) { return new $c['filter.manager.class'](); }); $c['filter.duplicate_key'] = $c->share(function ($c) { return new $c['filter.duplicate_key.class'](); }); $c['filter.data_hydrator'] = $c->share(function ($c) { return new $c['filter.data_hydrator.class']( $c['filter.data_hydrator.filter_unresolved'] ); }); // notifications $c['unread_notifications'] = $c->share(function ($c) { return new $c['unread_notifications.class']( $c['timeline_manager'] ); }); // query_builder $c['query_builder.factory'] = $c->share(function ($c) { return new $c['query_builder.factory.class']( $c['query_builder.class'], $c['query_builder.asserter.class'], $c['query_builder.operator.class'] ); }); // result builder $c['result_builder'] = $c->share(function ($c) { $instance = new $c['result_builder.class']( $c['query_executor'], $c['filter.manager'] ); $instance->setPager($c['pager']); return $instance; }); // deployers $c['spread.deployer'] = $c->share(function ($c) { $instance = new $c['spread.deployer.class']( $c['timeline_manager'], $c['spread.entry_collection'], $c['spread.on_subject'], $c['spread.batch_size'] ); $instance->setDelivery($c['spread.delivery']); return $instance; }); $c['spread.entry_collection'] = $c->share(function ($c) { return new $c['spread.entry_collection.class']( $c['spread.on_global_context'], $c['spread.batch_size'] ); }); $this->container = $c; }
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); } return $this->_statement->execute($params); }
{@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) { if (array_key_exists($key, $this->_driver->autoShortenedIdentifiers)) { $translatedRow[$this->_driver->autoShortenedIdentifiers[$key]] = $val; } else { $translatedRow[$key] = $val; } } $row = $translatedRow; } return $row; }
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(400, 'wrong parameters'); } $result = $this->get('sonata.dashboard.block_interactor')->saveBlocksPosition($params, false); $status = 200; } catch (HttpException $e) { $status = $e->getStatusCode(); $result = [ 'exception' => \get_class($e), 'message' => $e->getMessage(), 'code' => $e->getCode(), ]; } catch (\Exception $e) { $status = 500; $result = [ 'exception' => \get_class($e), 'message' => $e->getMessage(), 'code' => $e->getCode(), ]; } $result = (true === $result) ? 'ok' : $result; return $this->renderJson(['result' => $result], $status); }
@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->setSubject($blockId); $this->admin->checkAccess('switchParent'); $parent = $this->admin->getObject($parentId); if (!$parent) { throw $this->createNotFoundException(sprintf('Unable to find parent block with id %d', $parentId)); } $parent->addChildren($block); $this->admin->update($parent); return $this->renderJson(['result' => 'ok']); }
@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 found'); } $blockServices = $this->get('sonata.block.manager')->getServicesByContext('sonata_dashboard_bundle', false); return $this->render('@SonataDashboard/BlockAdmin/compose_preview.html.twig', [ 'container' => $container, 'child' => $block, 'blockServices' => $blockServices, ]); }
@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); return $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); }, $datas ) ); }
@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->paginate($target, $page, $limit, array('distinct' => true)); $this->data = $this->pager->getPaginationData(); return $this; }
{@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; $replaceQuery = false; foreach ($v->values() as $k => $val) { $fillLength = count($cols) - count($val); if ($fillLength > 0) { $val = array_merge($val, array_fill(0, $fillLength, null)); } foreach ($val as $col => $attr) { if (!($attr instanceof ExpressionInterface)) { $val[$col] = sprintf(':c%d', $placeholder); $placeholder++; } } $select = array_combine($cols, $val); if ($k === 0) { $replaceQuery = true; $newQuery->select($select)->from('DUAL'); continue; } $q = $newQuery->getConnection()->newQuery(); $newQuery->unionAll($q->select($select)->from('DUAL')); } if ($replaceQuery) { $v->query($newQuery); } return $query; }
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\Query
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->autoShortenedIdentifiers) + 1); $this->autoShortenedIdentifiers[$key] = $identifier; } $identifier = $key; } return $this->origQuoteIdentifier($identifier); }
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 undo these auto-replacements {@inheritDoc}
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($subject); return $this->client->zCard($redisKey); }
{@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, )); $options = $resolver->resolve($options); $token = new Pager\PagerToken($this->getSubjectRedisKey($subject)); return $this->resultBuilder->fetchResults($token, $options['page'], $options['max_per_page'], $options['filter'], $options['paginate']); }
{@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}" . ' = ?', $value); } } return $query->findOne(); }
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 must be a ComponentInterface or an object'); } $components['subject'] = $subject; foreach ($components as $type => $component) { $this->addComponent($action, $type, $component); } return $action; }
{@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->setIdentifier($resolved->getIdentifier()); return $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('sonata.dashboard.admin.block.entity', $config['class']['block']); $container->setParameter('sonata.dashboard.admin.dashboard.entity', $config['class']['dashboard']); $container->setParameter( 'sonata.dashboard.admin.dashboard.templates.compose', $config['templates']['compose'] ); $container->setParameter( 'sonata.dashboard.admin.dashboard.templates.compose_container_show', $config['templates']['compose_container_show'] ); $container->setParameter( 'sonata.dashboard.admin.dashboard.templates.render', $config['templates']['render'] ); $container->setParameter('sonata.dashboard.default_container', $config['default_container']); }
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 = 'item'; } if (!is_array($val)) { if (is_string($val) && preg_match('/[&<>"\'\?]+/', $val)) { $str .= $space . "<$key><![CDATA[" . $val . ']]>' . "</$key>\r\n"; } else { $str .= $space . "<$key>" . $val . "</$key>\r\n"; } } else { $str .= $space . "<$key>\r\n" . self::array2xml($val, $level + 1) . $space . "</$key>\r\n"; } } if ($level == 1) { $str .= '</root>'; } return $str; }
数组转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) { $resultingAtoms[] = $atom; } } return $resultingAtoms; }
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]; $resultingAtomsCount++; } if ( $resultingAtomsCount > 1 && AbstractPath::PARENT_ATOM === $resultingAtoms[$resultingAtomsCount - 1] && AbstractPath::PARENT_ATOM !== $resultingAtoms[$resultingAtomsCount - 2] ) { array_splice($resultingAtoms, $resultingAtomsCount - 2, 2); $resultingAtomsCount -= 2; } } if (count($resultingAtoms) < 1) { $resultingAtoms = array(AbstractPath::SELF_ATOM); } return $resultingAtoms; }
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_SEPARATOR . Config::$isLocal . DIRECTORY_SEPARATOR . 'normal.php'; is_file($appConfig) ? $appConfig = Cml::requireFile($appConfig) : exit('Config File [' . Config::$isLocal . '/normal.php] Not Found Please Check!'); is_array($appConfig) || $appConfig = []; $commonConfig = Cml::getApplicationDir('global_config_path') . DIRECTORY_SEPARATOR . 'common.php'; $commonConfig = is_file($commonConfig) ? Cml::requireFile($commonConfig) : []; Config::set(array_merge($cmlConfig, $commonConfig, $appConfig));//合并配置 if (Config::get('debug')) { self::$debug = true; $GLOBALS['debug'] = true;//开启debug Debug::addTipInfo(CML_CORE_PATH . DIRECTORY_SEPARATOR . 'Config' . DIRECTORY_SEPARATOR . 'config.php', Debug::TIP_INFO_TYPE_INCLUDE_FILE); Debug::addTipInfo(Cml::getApplicationDir('global_config_path') . DIRECTORY_SEPARATOR . Config::$isLocal . DIRECTORY_SEPARATOR . 'normal.php', Debug::TIP_INFO_TYPE_INCLUDE_FILE); empty($commonConfig) || Debug::addTipInfo(Cml::getApplicationDir('global_config_path') . DIRECTORY_SEPARATOR . 'common.php', Debug::TIP_INFO_TYPE_INCLUDE_FILE); } //引入系统语言包 Lang::set(Cml::requireFile((CML_CORE_PATH . DIRECTORY_SEPARATOR . 'Lang' . DIRECTORY_SEPARATOR . Config::get('lang') . '.php'))); }
处理配置及语言包相关
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(); //后面自动载入的类都会自动收集到Debug类下 spl_autoload_register('Cml\Cml::autoloadComposerAdditional', true, true); //包含框架中的框架函数库文件 Cml::requireFile(CML_CORE_PATH . DIRECTORY_SEPARATOR . 'Tools' . DIRECTORY_SEPARATOR . 'functions.php'); //设置自定义捕获致命异常函数 //普通错误由Cml\Debug::catcher捕获 php默认在display_errors为On时致命错误直接输出 为off时 直接显示服务器错误或空白页,体验不好 register_shutdown_function(function () { if ($error = error_get_last()) {//获取最后一个发生的错误的信息。 包括提醒、警告、致命错误 if (in_array($error['type'], self::$fatalErrorLogLevel)) { //当捕获到的错误为致命错误时 报告 if (Plugin::hook('cml.before_fatal_error', $error) == 'jump') { return; } Cml::getContainer()->make('cml_error_or_exception')->fatalError($error); Plugin::hook('cml.after_fatal_error', $error); } } Plugin::hook('cml.before_cml_stop'); }); //捕获致命异常 //设置自定义的异常处理函数。 set_exception_handler(function ($e) { if (Plugin::hook('cml.before_throw_exception', $e) === 'resume') { return; } Cml::getContainer()->make('cml_error_or_exception')->appException($e); }); //手动抛出的异常由此函数捕获 ini_set('display_errors', 'off');//屏蔽系统自带的错误输出 //载入插件配置文件 $pluginConfig = Cml::getApplicationDir('global_config_path') . DIRECTORY_SEPARATOR . 'plugin.php'; is_file($pluginConfig) && Cml::requireFile($pluginConfig); Plugin::hook('cml.before_set_time_zone');//用于动态设置时区等。 date_default_timezone_set(Config::get('time_zone')); //设置时区 self::$nowTime = time(); self::$nowMicroTime = microtime(true); //全局的自定义语言包 $globalLang = Cml::getApplicationDir('global_lang_path') . DIRECTORY_SEPARATOR . Config::get('lang') . '.php'; is_file($globalLang) && Lang::set(Cml::requireFile($globalLang)); //设置调试模式 if (Cml::$debug) { Debug::start();//记录开始运行时间\内存初始使用 //设置捕获系统异常 使用set_error_handler()后,error_reporting将会失效。所有的错误都会交给set_error_handler。 set_error_handler('\Cml\Debug::catcher'); array_map(function ($class) { Debug::addTipInfo(Lang::get('_CML_DEBUG_ADD_CLASS_TIP_', $class), Debug::TIP_INFO_TYPE_INCLUDE_LIB); }, [ 'Cml\Cml', 'Cml\Config', 'Cml\Lang', 'Cml\Http\Request', 'Cml\Debug', 'Cml\Interfaces\Debug', 'Cml\Container', 'Cml\Interfaces\Environment', get_class(self::getContainer()->make('cml_environment')) ]); $runTimeClassList = null; } else { $GLOBALS['debug'] = false;//关闭debug //ini_set('error_reporting', E_ALL & ~E_NOTICE);//记录除了notice之外的错误 ini_set('log_errors', 'off'); //关闭php自带错误日志 //严重错误已经通过fatalError记录。为了防止日志过多,默认不记录致命错误以外的日志。有需要可以修改配置开启 if (Config::get('log_warn_log')) { set_error_handler('\Cml\Log::catcherPhpError'); } //线上模式包含runtime.php $runTimeFile = Cml::getApplicationDir('global_store_path') . DIRECTORY_SEPARATOR . '_runtime_.php'; if (!is_file($runTimeFile)) { //程序运行必须的类 $runTimeClassList = [ CML_CORE_PATH . DIRECTORY_SEPARATOR . 'Controller.php', CML_CORE_PATH . DIRECTORY_SEPARATOR . 'Http' . DIRECTORY_SEPARATOR . 'Response.php', CML_CORE_PATH . DIRECTORY_SEPARATOR . 'Route.php', CML_CORE_PATH . DIRECTORY_SEPARATOR . 'Secure.php', ]; Config::get('session_user') && $runTimeClassList[] = CML_CORE_PATH . DIRECTORY_SEPARATOR . 'Session.php'; $runTimeContent = '<?php'; foreach ($runTimeClassList as $file) { $runTimeContent .= str_replace(['<?php', '?>'], '', php_strip_whitespace($file)); } file_put_contents($runTimeFile, $runTimeContent, LOCK_EX); $runTimeContent = null; } Cml::requireFile($runTimeFile); } if (Request::isCli()) { //兼容旧版直接运行方法 if (self::$run && ($_SERVER['argc'] != 2 || strpos($_SERVER['argv'][1], '/') < 1)) { $console = Cml::getContainer()->make('cml_console'); $userCommand = Cml::getApplicationDir('global_config_path') . DIRECTORY_SEPARATOR . 'command.php'; if (is_file($userCommand)) { $commandList = Cml::requireFile($userCommand); if (is_array($commandList) && count($commandList) > 0) { $console->addCommands($commandList); } } if ($console->run() !== 'don_not_exit') { exit(0); } } } else { header('X-Powered-By:CmlPHP'); // 页面压缩输出支持 if (Config::get('output_encode')) { $zlib = ini_get('zlib.output_compression'); if (empty($zlib)) { ///@ob_end_clean () ; //防止在启动ob_start()之前程序已经有输出(比如配置文件尾多敲了换行)会导致服务器303错误 ob_start('ob_gzhandler') || ob_start(); define('CML_OB_START', true); } else { define('CML_OB_START', false); } } } Plugin::hook('cml.before_parse_url'); //载入路由 $routeConfigFile = Cml::getApplicationDir('global_config_path') . DIRECTORY_SEPARATOR . 'route.php'; is_file($routeConfigFile) && Cml::requireFile($routeConfigFile); Cml::getContainer()->make('cml_route')->parseUrl();//解析处理URL Plugin::hook('cml.after_parse_url'); //载入模块配置 $appConfig = Cml::getApplicationDir('apps_path') . '/' . Cml::getContainer()->make('cml_route')->getAppName() . '/' . Cml::getApplicationDir('app_config_path_name') . '/' . 'normal.php'; is_file($appConfig) && Config::set(Cml::requireFile($appConfig)); //载入模块语言包 $appLang = Cml::getApplicationDir('apps_path') . '/' . Cml::getContainer()->make('cml_route')->getAppName() . '/' . Cml::getApplicationDir('app_lang_path_name') . '/' . Config::get('lang') . '.php'; is_file($appLang) && Lang::set(Cml::requireFile($appLang)); //载入模块插件 $appPlugin = dirname($appConfig) . '/' . 'plugin.php'; is_file($appPlugin) && Config::set(Cml::requireFile($appPlugin)); }
初始化运行环境
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) { Cml::$debug && Debug::addTipInfo(Lang::get('_CML_EXECUTION_ROUTE_IS_', "{$controllerAction['route']}{ {$controllerAction['class']}::{$controllerAction['action']} }", Config::get('url_model'))); $controller = new $controllerAction['class'](); call_user_func([$controller, "runAppController"], $controllerAction['action']);//运行 } else { self::montFor404Page(); if (self::$debug) { throw new ControllerNotFoundException(Lang::get('_CONTROLLER_NOT_FOUND_')); } else { Response::show404Page(); } } //输出Debug模式的信息 self::cmlStop(); }
启动应用 @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], '/')); if ($pos = strpos($cmd, '/')) { $cmd = substr($cmd, 0, $pos); } if (isset($cmdLists[$cmd])) { call_user_func($cmdLists[$cmd]); } } ]); Plugin::hook('cml.before_show_404_page'); }
未找到控制器的时候设置勾子
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)) { Config::get('dump_use_php_console') ? dumpUsePHPConsole($deBugLogData) : Cml::requireFile(CML_CORE_PATH . DIRECTORY_SEPARATOR . 'ConsoleLog.php', ['deBugLogData' => $deBugLogData]); }; Plugin::hook('cml.before_ob_end_flush'); CML_OB_START && ob_end_flush(); } exit(); }
程序中并输出调试信息
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)) { if (isset($arr[$k])) { $tmp = $arr[$k]; } else { return $default; } } else { if (isset($tmp[$k])) { $tmp = $tmp[$k]; } else { return $default; } } } return $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($tpl), false, true, true); Config::set('html_template_suffix', $configSubFix); }
渲染显示系统模板 @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()->delete($key); $this->lockCache[$key] = null;//防止gc延迟,判断有误 unset($this->lockCache[$key]); } }
解锁 @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'; } else { return 'belongsTo'; } }
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; } } } return false; }
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; } return false; }
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 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 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) { $first = $value; break; } // skip all tables that are not the current prefix if (!empty($prefix)) { if (!starts_with($first, $prefix)) { continue; } } // separate views from tables if ($result->Table_type == 'VIEW') { $views[] = $first; } else { $tables[] = $first; } } return ['tables' => $tables, 'views' => $views]; }
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 (is_array($default)) { $keys = array_keys($default); $keys = array_map(function ($key) { return '{' . $key . '}'; }, $keys); return str_replace($keys, array_values($default), $val); } else { $replace = func_get_args(); $replace[0] = $val; return call_user_func_array('sprintf', array_values($replace)); } } }
获取语言 不区分大小写 获取值的时候可以动态传参转出语言值 如:\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; return null; } // 多维数组设置 A.B.C = 1 $key = explode('.', $key); $tmp = null; foreach ($key as $k) { if (is_null($tmp)) { if (isset(static::$lang[$k]) === false) { static::$lang[$k] = []; } $tmp = &static::$lang[$k]; } else { is_array($tmp) || $tmp = []; isset($tmp[$k]) || $tmp[$k] = []; $tmp = &$tmp[$k]; } } $tmp = $value; unset($tmp); } return null; }
设置配置【语言】 支持批量设置 /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); $criteria[] = new Criterion\LogicalNot(new Criterion\ContentTypeIdentifier($excludeContentTypeIdentifiers)); $criteria[] = new Criterion\LanguageCode($languages); return new Criterion\LogicalAnd($criteria); }
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\Values\Content\Query\Criterion
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($includedContentTypeIdentifiers); $criteria[] = new Criterion\LanguageCode($languages); $criteria[] = new Criterion\ParentLocationId($location->id); return new Criterion\LogicalAnd($criteria); }
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\Repository\Values\Content\Query\Criterion
entailment
public function generateContentTypeExcludeCriterion(array $excludeContentTypeIdentifiers) { $excludeCriterion = array(); foreach ($excludeContentTypeIdentifiers as $contentTypeIdentifier) { $excludeCriterion[] = new Criterion\LogicalNot( new Criterion\ContentTypeIdentifier($contentTypeIdentifier) ); } return new Criterion\LogicalAnd($excludeCriterion); }
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'); } $excludeCriterion[] = new Criterion\LogicalNot( new Criterion\LocationId($location->id) ); } return new Criterion\LogicalAnd($excludeCriterion); }
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[] = new Criterion\ContentTypeIdentifier(array('blog_post')); $criteria[] = new Criterion\LanguageCode($languages); if (!empty($viewParameters)) { if (!empty($viewParameters['month']) && !empty($viewParameters['year'])) { // Generating the criterion for the given month/year $month = (int)$viewParameters['month']; $year = (int)$viewParameters['year']; $date = new DateTime("$year-$month-01"); $date->setTime(00, 00, 00); $criteria[] = new Criterion\DateMetadata( Criterion\DateMetadata::CREATED, Criterion\Operator::BETWEEN, array( $date->getTimestamp(), $date->add(new DateInterval('P1M'))->getTimestamp(), ) ); } } return new Criterion\LogicalAnd($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->joinDrive($basePath->drive()); } if ($path->hasDrive() && !$path->matchesDrive($basePath->drive())) { return $path->toAbsolute(); } } 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 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); } if (preg_match('{^([a-zA-Z]):}', $atoms[0], $matches)) { $drive = $matches[1]; $atoms[0] = substr($atoms[0], 2); if (false === $atoms[0]) { $atoms[0] = ''; } } $numAtoms = count($atoms); if ($numAtoms > 1) { if ('' === $atoms[0]) { if (null === $drive) { $isAnchored = true; } else { $isAbsolute = true; } array_shift($atoms); --$numAtoms; } } else { $isAbsolute = null !== $drive && '' === $atoms[0]; } if ($numAtoms > 1) { if ('' === $atoms[$numAtoms - 1]) { $hasTrailingSeparator = true; array_pop($atoms); } } return $this->createFromDriveAndAtoms( array_filter($atoms, 'strlen'), $drive, $isAbsolute, $isAnchored, $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 ) { 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 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 createFromDriveAndAtoms( $atoms, $drive = null, $isAbsolute = null, $isAnchored = null, $hasTrailingSeparator = null ) { if (null === $isAnchored) { $isAnchored = false; } if (null === $isAbsolute) { $isAbsolute = null !== $drive && !$isAnchored; } if ($isAbsolute && $isAnchored) { throw new InvalidPathStateException( 'Absolute Windows paths cannot be anchored.' ); } if ($isAbsolute) { return new AbsoluteWindowsPath( $drive, $atoms, $hasTrailingSeparator ); } return new RelativeWindowsPath( $atoms, $drive, $isAnchored, $hasTrailingSeparator ); }
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 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. @throws InvalidPathStateException If the supplied arguments would produce an invalid path.
entailment
public function indexAction() { $footerContentId = $this->container->getParameter('ezdemo.footer.content_id'); $footerContent = $this->getRepository()->getContentService()->loadContent($footerContentId); $response = new Response(); $response->setPublic(); $response->setSharedMaxAge(86400); $response->headers->set('X-Location-Id', $footerContent->contentInfo->mainLocationId); $response->setVary('X-User-Hash'); return $this->render( 'eZDemoBundle::page_footer.html.twig', array('content' => $footerContent), $response ); }
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\LocaleConverterInterface $localeConverter */ $localeConverter = $this->container->get('ezpublish.locale.converter'); // get current eZ language $currentEzLanguage = $localeConverter->convertToEz($request->get('_locale')); $siteaccess = []; $availableLanguages = []; // create an array for corresponding siteaccesses names depending on the lang foreach ($translationHelper->getAvailableLanguages() as $lang) { if ($lang != null) { $siteaccess[$lang] = $translationHelper->getTranslationSiteAccess($lang); $availableLanguages[] = $lang; } } return $this->render( 'eZDemoBundle:parts:languages_switcher.html.twig', array( 'routeRef' => $routeReference, 'siteaccess' => $siteaccess, 'currentLanguage' => $currentEzLanguage, 'availableLanguages' => $availableLanguages, ) ); }
@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['timeout']); } else { $this->connection = fsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']); } if (!empty($errNum) || !empty($errStr)) { $this->error($errStr, $errNum); } $this->connected = is_resource($this->connection); return $this->connected; }
创建连接 @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) { $host = explode(':', $host); $host = $host[0]; } } switch ($host) { case $_SERVER['SERVER_ADDR'] : // no break case '127.0.0.1': //no break case 'localhost': return 'development'; } $domain = substr($host, strrpos($host, '.') + 1); if ($domain == 'dev' || $domain == 'loc' || $domain == 'test') { return 'development'; } if (substr($_SERVER['HTTP_HOST'], 0, 7) == '192.168') { return 'development'; } return 'product'; }
获取当前环境名称 @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'] = ''; isset($matches['query']) || $matches['query'] = ''; isset($matches['port']) || $matches['port'] = ''; $host = $matches['host']; $path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/'; $port = !empty($matches['port']) ? $matches['port'] : 80; $confArr = [ 'limit' => 0, 'post' => '', 'cookie' => '', 'ip' => '', 'timeout' => 15, 'block' => true, ]; foreach (array_merge($confArr, $conf) as $k => $v) ${$k} = $v; $post = ''; if ($conf['post']) { if (is_array($conf['post'])) { $post = http_build_query($conf['post']); } $out = "POST $path HTTP/1.0\r\n"; $out .= "Accept: */*\r\n"; //$out .= "Referer: $boardurl\r\n"; $out .= "Accept-Language: zh-cn\r\n"; $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n"; $out .= "Host: $host\r\n"; $out .= 'Content-Length: ' . strlen($conf['post']) . "\r\n"; $out .= "Connection: Close\r\n"; $out .= "Cache-Control: no-cache\r\n"; $out .= "Cookie: " . $conf['cookie'] . "\r\n\r\n"; $out .= $post; } else { $out = "GET $path HTTP/1.0\r\n"; $out .= "Accept: */*\r\n"; //$out .= "Referer: $boardurl\r\n"; $out .= "Accept-Language: zh-cn\r\n"; $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n"; $out .= "Host: $host\r\n"; $out .= "Connection: Close\r\n"; $out .= "Cookie: " . $conf['cookie'] . "\r\n\r\n"; } $fp = fsockopen(($conf['ip'] ? $conf['ip'] : $host), $port, $errno, $errstr, $timeout); if (!$fp) { return ''; } else { stream_set_blocking($fp, $conf['block']); stream_set_timeout($fp, $timeout); fwrite($fp, $out); $status = stream_get_meta_data($fp); if (!$status['timed_out']) { while (!feof($fp)) { if (($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) { break; } } $stop = false; while (!feof($fp) && !$stop) { $data = fread($fp, ($conf['limit'] == 0 || $conf['limit'] > 8192 ? 8192 : $conf['limit'])); $return .= $data; if ($conf['limit']) { $conf['limit'] -= strlen($data); $stop = $conf['limit'] <= 0; } } } fclose($fp); return $return; } }
使用 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 是否阻塞访问,默认为true @param int $timeout 超时时间 @return mixed
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("HTTP/1.1 404 Not Found"); return false; } if (empty($showName)) { $showName = $filename; } $showName = basename($showName); $contentType = self::mimeContentType($filename); $fileStat = stat($filename); $lastModified = $fileStat['mtime']; $md5 = md5($fileStat['mtime'] . '=' . $fileStat['ino'] . '=' . $fileStat['size']); $etag = '"' . $md5 . '-' . crc32($md5) . '"'; header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT'); header("ETag: $etag"); if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified) { header("HTTP/1.1 304 Not Modified"); return true; } if (isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_UNMODIFIED_SINCE']) < $lastModified) { header("HTTP/1.1 304 Not Modified"); return true; } if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) { header("HTTP/1.1 304 Not Modified"); return true; } $fileSize = $fileStat['size']; $contentLength = $fileSize; $isPartial = false; if (isset($_SERVER['HTTP_RANGE'])) { if (preg_match('/^bytes=(d*)-(d*)$/', $_SERVER['HTTP_RANGE'], $matches)) { $startPos = $matches[1]; $endPos = $matches[2]; if ($startPos == '' && $endPos == '') { return false; } if ($startPos == '') { $startPos = $fileSize - $endPos; $endPos = $fileSize - 1; } else if ($endPos == '') { $endPos = $fileSize - 1; } $startPos = $startPos < 0 ? 0 : $startPos; $endPos = $endPos > $fileSize - 1 ? $fileSize - 1 : $endPos; $length = $endPos - $startPos + 1; if ($length <= 0) { return false; } $contentLength = $length; $isPartial = true; } } if ($isPartial) { header('HTTP/1.1 206 Partial Content'); header("Content-Range: bytes {$startPos} - {$endPos} / {$fileSize}"); } else { header("HTTP/1.1 200 OK"); $startPos = 0; //$endPos = $contentLength - 1; } header('Pragma: cache'); header('Cache-Control: public, must-revalidate, max-age=0'); header('Accept-Ranges: bytes'); header('Content-type: ' . $contentType); header('Content-Length: ' . $contentLength); header('Content-Disposition: attachment; filename="' . rawurlencode($showName) . '"'); header("Content-Transfer-Encoding: binary"); $bufferSize = 2048; if ($speedLimit != 0) { $packetTime = floor($bufferSize * 1000000 / $speedLimit); } $bytesSent = 0; $fp = fopen($filename, "rb"); fseek($fp, $startPos); while ($bytesSent < $contentLength && !feof($fp) && connection_status() == 0) { if ($speedLimit != 0) { $outputTimeStart = microtime(true); } $readBufferSize = $contentLength - $bytesSent < $bufferSize ? $contentLength - $bytesSent : $bufferSize; $buffer = fread($fp, $readBufferSize); echo $buffer; $bytesSent += $readBufferSize; if ($speedLimit != 0) { $outputTimeEnd = microtime(true); $useTime = ((float)$outputTimeEnd - (float)$outputTimeStart) * 1000000; $sleepTime = round($packetTime - $useTime); if ($sleepTime > 0) { usleep($sleepTime); } } } return true; }
下载文件 可以指定下载显示的文件名,并自动发送相应的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) { echo("$key:$val\n"); } } $output = ob_get_clean(); if ($echo) { echo(nl2br($output)); } else { return $output; } return ''; }
显示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/plain 'asf' => 'video/x-ms-asf', 'asx' => 'video/x-ms-asf', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'bcpio' => 'application/x-bcpio', 'bin' => 'application/octet-stream', 'bmp' => 'image/bmp', 'c' => 'text/plain', // or 'text/x-csrc', //added by skwashd 'cc' => 'text/plain', // or 'text/x-c++src', //added by skwashd 'cs' => 'text/plain', //added by skwashd - for C# src 'cpp' => 'text/x-c++src', //added by skwashd 'cxx' => 'text/x-c++src', //added by skwashd 'cdf' => 'application/x-netcdf', 'class' => 'application/octet-stream',//secure but application/java-class is correct 'com' => 'application/octet-stream',//added by skwashd 'cpio' => 'application/x-cpio', 'cpt' => 'application/mac-compactpro', 'csh' => 'application/x-csh', 'css' => 'text/css', 'csv' => 'text/comma-separated-values',//added by skwashd 'dcr' => 'application/x-director', 'diff' => 'text/diff', 'dir' => 'application/x-director', 'dll' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'doc' => 'application/msword', 'dot' => 'application/msword',//added by skwashd 'dvi' => 'application/x-dvi', 'dxr' => 'application/x-director', 'eps' => 'application/postscript', 'etx' => 'text/x-setext', 'exe' => 'application/octet-stream', 'ez' => 'application/andrew-inset', 'gif' => 'image/gif', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'h' => 'text/plain', // or 'text/x-chdr',//added by skwashd 'h++' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd 'hh' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd 'hpp' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd 'hxx' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd 'hdf' => 'application/x-hdf', 'hqx' => 'application/mac-binhex40', 'htm' => 'text/html', 'html' => 'text/html', 'ice' => 'x-conference/x-cooltalk', 'ics' => 'text/calendar', 'ief' => 'image/ief', 'ifb' => 'text/calendar', 'iges' => 'model/iges', 'igs' => 'model/iges', 'jar' => 'application/x-jar', //added by skwashd - alternative mime type 'java' => 'text/x-java-source', //added by skwashd 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'js' => 'application/x-javascript', 'kar' => 'audio/midi', 'latex' => 'application/x-latex', 'lha' => 'application/octet-stream', 'log' => 'text/plain', 'lzh' => 'application/octet-stream', 'm3u' => 'audio/x-mpegurl', 'man' => 'application/x-troff-man', 'me' => 'application/x-troff-me', 'mesh' => 'model/mesh', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mif' => 'application/vnd.mif', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpga' => 'audio/mpeg', 'ms' => 'application/x-troff-ms', 'msh' => 'model/mesh', 'mxu' => 'video/vnd.mpegurl', 'nc' => 'application/x-netcdf', 'oda' => 'application/oda', 'patch' => 'text/diff', 'pbm' => 'image/x-portable-bitmap', 'pdb' => 'chemical/x-pdb', 'pdf' => 'application/pdf', 'pgm' => 'image/x-portable-graymap', 'pgn' => 'application/x-chess-pgn', 'pgp' => 'application/pgp',//added by skwashd 'php' => 'application/x-httpd-php', 'php3' => 'application/x-httpd-php3', 'pl' => 'application/x-perl', 'pm' => 'application/x-perl', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'po' => 'text/plain', 'ppm' => 'image/x-portable-pixmap', 'ppt' => 'application/vnd.ms-powerpoint', 'ps' => 'application/postscript', 'qt' => 'video/quicktime', 'ra' => 'audio/x-realaudio', 'rar' => 'application/octet-stream', 'ram' => 'audio/x-pn-realaudio', 'ras' => 'image/x-cmu-raster', 'rgb' => 'image/x-rgb', 'rm' => 'audio/x-pn-realaudio', 'roff' => 'application/x-troff', 'rpm' => 'audio/x-pn-realaudio-plugin', 'rtf' => 'text/rtf', 'rtx' => 'text/richtext', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'shtml' => 'text/html', 'silo' => 'model/mesh', 'sit' => 'application/x-stuffit', 'skd' => 'application/x-koan', 'skm' => 'application/x-koan', 'skp' => 'application/x-koan', 'skt' => 'application/x-koan', 'smi' => 'application/smil', 'smil' => 'application/smil', 'snd' => 'audio/basic', 'so' => 'application/octet-stream', 'spl' => 'application/x-futuresplash', 'src' => 'application/x-wais-source', 'stc' => 'application/vnd.sun.xml.calc.template', 'std' => 'application/vnd.sun.xml.draw.template', 'sti' => 'application/vnd.sun.xml.impress.template', 'stw' => 'application/vnd.sun.xml.writer.template', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'swf' => 'application/x-shockwave-flash', 'sxc' => 'application/vnd.sun.xml.calc', 'sxd' => 'application/vnd.sun.xml.draw', 'sxg' => 'application/vnd.sun.xml.writer.global', 'sxi' => 'application/vnd.sun.xml.impress', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 't' => 'application/x-troff', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'tgz' => 'application/x-gtar', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'tr' => 'application/x-troff', 'tsv' => 'text/tab-separated-values', 'txt' => 'text/plain', 'ustar' => 'application/x-ustar', 'vbs' => 'text/plain', //added by skwashd - for obvious reasons 'vcd' => 'application/x-cdlink', 'vcf' => 'text/x-vcard', 'vcs' => 'text/calendar', 'vfb' => 'text/calendar', 'vrml' => 'model/vrml', 'vsd' => 'application/vnd.visio', 'wav' => 'audio/x-wav', 'wax' => 'audio/x-ms-wax', 'wbmp' => 'image/vnd.wap.wbmp', 'wbxml' => 'application/vnd.wap.wbxml', 'wm' => 'video/x-ms-wm', 'wma' => 'audio/x-ms-wma', 'wmd' => 'application/x-ms-wmd', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wmz' => 'application/x-ms-wmz', 'wrl' => 'model/vrml', 'wvx' => 'video/x-ms-wvx', 'xbm' => 'image/x-xbitmap', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xls' => 'application/vnd.ms-excel', 'xlt' => 'application/vnd.ms-excel', 'xml' => 'application/xml', 'xpm' => 'image/x-xpixmap', 'xsl' => 'text/xml', 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-xyz', 'z' => 'application/x-compress', 'zip' => 'application/zip', ]; $type = strtolower(substr(strrchr($filename, '.'), 1)); if (isset($contentType[$type])) { $mime = $contentType[$type]; } else { $mime = 'application/octet-stream'; } return $mime; }
获取文件的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->getAllForeignKeysOrderedByTable(); foreach ($this->tables as $key => $table) { $this->describes[$table] = $this->dataBase->describeTable($table); if ($this->isManyToMany($table, true)) { $this->junctionTables[] = $table; unset($this->tables[$key]); } } unset($table); foreach ($this->tables as $table) { $model = new Model(); $model->buildModel( $table, $this->baseModel, $this->describes, $this->foreignKeys, $this->namespace, $this->prefix ); $model->createModel(); $result = $this->writeFile($table, $model); echo 'file written: '.$result['filename'].' - '.$result['result'].' bytes'.BR; flush(); } echo 'done'.BR; }
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'] == 'int' && $field->Key == 'PRI') { // should be a foreign key if ($checkForeignKey && $this->isForeignKey($table, $field->Field)) { $count++; } if (!$checkForeignKey) { $count++; } } } } if ($count == 2) { return true; } return false; }
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($oldUMask); if (!is_dir($this->path)) { throw new Exception('dir '.$this->path.' could not be created'); } } $result = file_put_contents($this->path.'/'.$filename, $model); return ['filename' => $this->path.'/'.$filename, 'result' => $result]; }
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 = varchar, $size = 255 $type = explode('(', $type[0]); $result['type'] = $type[0]; if (isset($type[1])) { $result['size'] = intval($type[1]); } return $result; }
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_FINISHED) return false; return true; }
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)) { if (!@ftp_mkdir($this->linkid, $dir[$i])) { $ret = false; break; } } @ftp_chdir($this->linkid, $path); } if (!$ret) return false; return true; }
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->dbInstance[$conf])) { return $this->dbInstance[$conf]; } else { $pos = strpos($config['driver'], '.'); $this->dbInstance[$conf] = Cml::getContainer()->make('db_' . strtolower($pos ? substr($config['driver'], 0, $pos) : $config['driver']), $config); return $this->dbInstance[$conf]; } }
获取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[$conf]; } else { if ($config['on']) { self::$cacheInstance[$conf] = Cml::getContainer()->make('cache_' . strtolower($config['driver']), $config); return self::$cacheInstance[$conf]; } else { throw new \InvalidArgumentException(Lang::get('_NOT_OPEN_', $conf)); } } }
获取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(); is_null($table) || $mInstance[$classKey]->table = $table; is_null($tablePrefix) || $mInstance[$classKey]->tablePrefix = $tablePrefix; is_null($db) || $mInstance[$classKey]->db = $db; } return $mInstance[$classKey]; }
初始化一个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.dbname') . '.' : ''; if ($addTablePrefix) { $tablePrefix = $this->tablePrefix; $tablePrefix || $tablePrefix = Config::get($this->getDbConf() . '.master.tableprefix'); return $dbName . $tablePrefix . $this->table; } return $dbName . $this->table; }
获取表名 @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, $tablePrefix); return $this->db($this->getDbConf())->table($tableName, $tablePrefix) ->where($column, $val) ->getOne($this->useMaster); }
通过某个字段获取单条数据-快捷方法 @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($tableName, $tablePrefix); return $this->db($this->getDbConf())->table($tableName, $tablePrefix) ->where($column, $val) ->select(null, null, $this->useMaster); }
通过某个字段获取多条数据-快捷方法 @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