diff --git a/.gitignore b/.gitignore index 7e31ef510a6bcc8489b574342933f26db9954a98..f7775ba419fd23959b549ac5542de7a1d720f1e9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,8 @@ -/composer.lock /vendor -.idea +composer.phar +composer.lock .DS_Store +Thumbs.db +/phpunit.xml +/.idea +/.vscode \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 96a9dffc16809e3cf75dcd5beca37ee2c92f7856..0000000000000000000000000000000000000000 --- a/.travis.yml +++ /dev/null @@ -1,49 +0,0 @@ -sudo: false - -language: php - -services: - - memcached - - mongodb - - mysql - - postgresql - - redis-server - -matrix: - fast_finish: true - include: - - php: 5.4 - - php: 5.5 - - php: 5.6 - - php: 7.0 - - php: hhvm - allow_failures: - - php: hhvm - -cache: - directories: - - $HOME/.composer/cache - -before_install: - - composer self-update - - mysql -e "create database IF NOT EXISTS test;" -uroot - - psql -c 'DROP DATABASE IF EXISTS test;' -U postgres - - psql -c 'create database test;' -U postgres - -install: - - ./tests/script/install.sh - -script: - ## LINT - - find . -path ./vendor -prune -o -type f -name \*.php -exec php -l {} \; - ## PHP_CodeSniffer - - vendor/bin/phpcs --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 --standard=PSR2 --ignore="vendor/*" ./ - ## PHP Copy/Paste Detector - - vendor/bin/phpcpd --verbose --exclude vendor ./ || true - ## PHPLOC - - vendor/bin/phploc --exclude vendor ./ - ## PHPUNIT - - vendor/bin/phpunit --coverage-clover=coverage.xml --configuration=phpunit.xml - -after_success: - - bash <(curl -s https://codecov.io/bash) diff --git a/README.md b/README.md index ee0676a059bcaecfdb790245a9b1c6efebf29c03..52c34a4bf95d42c571e26faaf1f5870d321dfdfc 100644 --- a/README.md +++ b/README.md @@ -1,101 +1,49 @@ -ThinkPHP 5.0 +![](http://www.thinkphp.cn/Uploads/editor/2016-06-23/576b4732a6e04.png) + +ThinkPHP 5.1 —— 12载初心,你值得信赖的PHP框架 =============== [![Build Status](https://travis-ci.org/top-think/framework.svg?branch=master)](https://travis-ci.org/top-think/framework) -[![codecov.io](http://codecov.io/github/top-think/framework/coverage.svg?branch=master)](http://codecov.io/github/github/top-think/framework?branch=master) [![Total Downloads](https://poser.pugx.org/topthink/framework/downloads)](https://packagist.org/packages/topthink/framework) [![Latest Stable Version](https://poser.pugx.org/topthink/framework/v/stable)](https://packagist.org/packages/topthink/framework) -[![Latest Unstable Version](https://poser.pugx.org/topthink/framework/v/unstable)](https://packagist.org/packages/topthink/framework) [![License](https://poser.pugx.org/topthink/framework/license)](https://packagist.org/packages/topthink/framework) -ThinkPHP5在保持快速开发和大道至简的核心理念不变的同时,PHP版本要求提升到5.4,对已有的CBD模式做了更深的强化,优化核心,减少依赖,基于全新的架构思想和命名空间实现,是ThinkPHP突破原有框架思路的颠覆之作,其主要特性包括: - - + 基于命名空间和众多PHP新特性 - + 核心功能组件化 - + 强化路由功能 - + 更灵活的控制器 - + 重构的模型和数据库类 - + 配置文件可分离 - + 重写的自动验证和完成 - + 简化扩展机制 - + API支持完善 - + 改进的Log类 - + 命令行访问支持 - + REST支持 - + 引导文件支持 - + 方便的自动生成定义 - + 真正惰性加载 - + 分布式环境支持 - + 支持Composer - -> ThinkPHP5的运行环境要求PHP5.4以上。 - -详细开发文档参考 [ThinkPHP5完全开发手册](http://www.kancloud.cn/manual/thinkphp5) - -## 目录结构 - -初始的目录结构如下: - -~~~ -www WEB部署目录(或者子目录) -├─application 应用目录 -│ ├─common 公共模块目录(可以更改) -│ ├─module_name 模块目录 -│ │ ├─config.php 模块配置文件 -│ │ ├─common.php 模块函数文件 -│ │ ├─controller 控制器目录 -│ │ ├─model 模型目录 -│ │ ├─view 视图目录 -│ │ └─ ... 更多类库目录 -│ │ -│ ├─command.php 命令行工具配置文件 -│ ├─common.php 公共函数文件 -│ ├─config.php 公共配置文件 -│ ├─route.php 路由配置文件 -│ ├─tags.php 应用行为扩展定义文件 -│ └─database.php 数据库配置文件 -│ -├─public WEB目录(对外访问目录) -│ ├─index.php 入口文件 -│ ├─router.php 快速测试文件 -│ └─.htaccess 用于apache的重写 -│ -├─thinkphp 框架系统目录 -│ ├─lang 语言文件目录 -│ ├─library 框架类库目录 -│ │ ├─think Think类库包目录 -│ │ └─traits 系统Trait目录 -│ │ -│ ├─tpl 系统模板目录 -│ ├─base.php 基础定义文件 -│ ├─console.php 控制台入口文件 -│ ├─convention.php 框架惯例配置文件 -│ ├─helper.php 助手函数文件 -│ ├─phpunit.xml phpunit配置文件 -│ └─start.php 框架入口文件 -│ -├─extend 扩展类库目录 -├─runtime 应用的运行时目录(可写,可定制) -├─vendor 第三方类库目录(Composer依赖库) -├─build.php 自动生成定义文件(参考) -├─composer.json composer 定义文件 -├─LICENSE.txt 授权说明文件 -├─README.md README 文件 -├─think 命令行入口文件 -~~~ - -> router.php用于php自带webserver支持,可用于快速测试 -> 切换到public目录后,启动命令:php -S localhost:8888 router.php -> 上面的目录结构和名称是可以改变的,这取决于你的入口文件和配置参数。 +ThinkPHP5.1对底层架构做了进一步的改进,减少依赖,其主要特性包括: + + + 采用容器统一管理对象 + + 支持Facade + + 更易用的路由 + + 注解路由支持 + + 路由跨域请求支持 + + 验证类增强 + + 配置和路由目录独立 + + 取消系统常量 + + 类库别名机制 + + 模型和数据库增强 + + 依赖注入完善 + + 支持PSR-3日志规范 + +### 废除的功能: + + + 聚合模型 + + 内置控制器扩展类 + + 模型自动验证 + +> ThinkPHP5.1的运行环境要求PHP5.6+。 + + +## 在线手册 + ++ [完全开发手册](https://www.kancloud.cn/manual/thinkphp5_1/content) ++ [升级指导](https://www.kancloud.cn/manual/thinkphp5_1/354155) ## 命名规范 -ThinkPHP5的命名规范遵循PSR-2规范以及PSR-4自动加载规范。 +`ThinkPHP5`遵循PSR-2命名规范和PSR-4自动加载规范。 ## 参与开发 -注册并登录 Github 帐号, fork 本项目并进行改动。 -更多细节参阅 [CONTRIBUTING.md](CONTRIBUTING.md) +请参阅 [ThinkPHP5 核心框架包](https://github.com/top-think/framework)。 ## 版权信息 @@ -103,7 +51,7 @@ ThinkPHP遵循Apache2开源协议发布,并提供免费使用。 本项目包含的第三方源码和二进制文件之版权信息另行标注。 -版权所有Copyright © 2006-2016 by ThinkPHP (http://thinkphp.cn) +版权所有Copyright © 2006-2018 by ThinkPHP (http://thinkphp.cn) All rights reserved。 diff --git a/base.php b/base.php index 1184dc51f6034088dc1931df018c645ad7e180e4..084dd74dba3d99fdd6ed137d46762eb048eaf526 100644 --- a/base.php +++ b/base.php @@ -2,62 +2,73 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st // +---------------------------------------------------------------------- - -define('THINK_VERSION', '5.0.2dev'); -define('THINK_START_TIME', microtime(true)); -define('THINK_START_MEM', memory_get_usage()); -define('EXT', '.php'); -define('DS', DIRECTORY_SEPARATOR); -defined('THINK_PATH') or define('THINK_PATH', __DIR__ . DS); -define('LIB_PATH', THINK_PATH . 'library' . DS); -define('CORE_PATH', LIB_PATH . 'think' . DS); -define('TRAIT_PATH', LIB_PATH . 'traits' . DS); -defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']) . DS); -defined('ROOT_PATH') or define('ROOT_PATH', dirname(realpath(APP_PATH)) . DS); -defined('EXTEND_PATH') or define('EXTEND_PATH', ROOT_PATH . 'extend' . DS); -defined('VENDOR_PATH') or define('VENDOR_PATH', ROOT_PATH . 'vendor' . DS); -defined('RUNTIME_PATH') or define('RUNTIME_PATH', ROOT_PATH . 'runtime' . DS); -defined('LOG_PATH') or define('LOG_PATH', RUNTIME_PATH . 'log' . DS); -defined('CACHE_PATH') or define('CACHE_PATH', RUNTIME_PATH . 'cache' . DS); -defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH . 'temp' . DS); -defined('CONF_PATH') or define('CONF_PATH', APP_PATH); // 配置文件目录 -defined('CONF_EXT') or define('CONF_EXT', EXT); // 配置文件后缀 -defined('ENV_PREFIX') or define('ENV_PREFIX', 'PHP_'); // 环境变量的配置前缀 - -// 环境常量 -define('IS_CLI', PHP_SAPI == 'cli' ? true : false); -define('IS_WIN', strpos(PHP_OS, 'WIN') !== false); +namespace think; // 载入Loader类 -require CORE_PATH . 'Loader.php'; - -// 加载环境变量配置文件 -if (is_file(ROOT_PATH . '.env')) { - $env = parse_ini_file(ROOT_PATH . '.env', true); - foreach ($env as $key => $val) { - $name = ENV_PREFIX . strtoupper($key); - if (is_array($val)) { - foreach ($val as $k => $v) { - $item = $name . '_' . strtoupper($k); - putenv("$item=$v"); - } - } else { - putenv("$name=$val"); - } - } -} +require __DIR__ . '/library/think/Loader.php'; // 注册自动加载 -\think\Loader::register(); +Loader::register(); // 注册错误和异常处理机制 -\think\Error::register(); +Error::register(); + +// 实现日志接口 +if (interface_exists('Psr\Log\LoggerInterface')) { + interface LoggerInterface extends \Psr\Log\LoggerInterface + {} +} else { + interface LoggerInterface + {} +} + +// 注册核心类的静态代理 +Facade::bind([ + facade\App::class => App::class, + facade\Build::class => Build::class, + facade\Cache::class => Cache::class, + facade\Config::class => Config::class, + facade\Cookie::class => Cookie::class, + facade\Debug::class => Debug::class, + facade\Env::class => Env::class, + facade\Hook::class => Hook::class, + facade\Lang::class => Lang::class, + facade\Log::class => Log::class, + facade\Middleware::class => Middleware::class, + facade\Request::class => Request::class, + facade\Response::class => Response::class, + facade\Route::class => Route::class, + facade\Session::class => Session::class, + facade\Url::class => Url::class, + facade\Validate::class => Validate::class, + facade\View::class => View::class, +]); -// 加载惯例配置文件 -\think\Config::set(include THINK_PATH . 'convention' . EXT); +// 注册类库别名 +Loader::addClassAlias([ + 'App' => facade\App::class, + 'Build' => facade\Build::class, + 'Cache' => facade\Cache::class, + 'Config' => facade\Config::class, + 'Cookie' => facade\Cookie::class, + 'Db' => Db::class, + 'Debug' => facade\Debug::class, + 'Env' => facade\Env::class, + 'Facade' => Facade::class, + 'Hook' => facade\Hook::class, + 'Lang' => facade\Lang::class, + 'Log' => facade\Log::class, + 'Request' => facade\Request::class, + 'Response' => facade\Response::class, + 'Route' => facade\Route::class, + 'Session' => facade\Session::class, + 'Url' => facade\Url::class, + 'Validate' => facade\Validate::class, + 'View' => facade\View::class, +]); diff --git a/codecov.yml b/codecov.yml deleted file mode 100644 index bef9d643ad8d5794e593d67ac6f5078ef6ac6d06..0000000000000000000000000000000000000000 --- a/codecov.yml +++ /dev/null @@ -1,12 +0,0 @@ -comment: - layout: header, changes, diff -coverage: - ignore: - - base.php - - helper.php - - convention.php - - lang/zh-cn.php - - start.php - - console.php - status: - patch: false diff --git a/composer.json b/composer.json index 444d6889aea6fb341d19ecb31b39c974267c5b40..cc4fca9121543c469c53686b5c4d466e48afdf3f 100644 --- a/composer.json +++ b/composer.json @@ -13,14 +13,18 @@ { "name": "liu21st", "email": "liu21st@gmail.com" + }, + { + "name": "yunwuxin", + "email": "448901948@qq.com" } ], "require": { - "php": ">=5.4.0", - "topthink/think-installer": "~1.0" + "php": ">=5.6.0", + "topthink/think-installer": "2.*" }, "require-dev": { - "phpunit/phpunit": "4.8.*", + "phpunit/phpunit": "^5.0|^6.0", "johnkary/phpunit-speedtrap": "^1.0", "mikey179/vfsStream": "~1.6", "phploc/phploc": "2.*", diff --git a/convention.php b/convention.php index f7486a4805bf72b38d90d6edef562068874eeac4..6675a57a9cc0f2c9fe40845a1b7f1173c8e97534 100644 --- a/convention.php +++ b/convention.php @@ -4,115 +4,165 @@ return [ // +---------------------------------------------------------------------- // | 应用设置 // +---------------------------------------------------------------------- + 'app' => [ + // 应用名称 + 'app_name' => '', + // 应用地址 + 'app_host' => '', + // 应用调试模式 + 'app_debug' => false, + // 应用Trace + 'app_trace' => false, + // 应用模式状态 + 'app_status' => '', + // 是否HTTPS + 'is_https' => false, + // 入口自动绑定模块 + 'auto_bind_module' => false, + // 注册的根命名空间 + 'root_namespace' => [], + // 默认输出类型 + 'default_return_type' => 'html', + // 默认AJAX 数据返回格式,可选json xml ... + 'default_ajax_return' => 'json', + // 默认JSONP格式返回的处理方法 + 'default_jsonp_handler' => 'jsonpReturn', + // 默认JSONP处理方法 + 'var_jsonp_handler' => 'callback', + // 默认时区 + 'default_timezone' => 'Asia/Shanghai', + // 是否开启多语言 + 'lang_switch_on' => false, + // 默认验证器 + 'default_validate' => '', + // 默认语言 + 'default_lang' => 'zh-cn', - // 应用命名空间 - 'app_namespace' => 'app', - // 应用调试模式 - 'app_debug' => true, - // 应用Trace - 'app_trace' => false, - // 应用模式状态 - 'app_status' => '', - // 是否支持多模块 - 'app_multi_module' => true, - // 入口自动绑定模块 - 'auto_bind_module' => false, - // 注册的根命名空间 - 'root_namespace' => [], - // 扩展函数文件 - 'extra_file_list' => [THINK_PATH . 'helper' . EXT], - // 默认输出类型 - 'default_return_type' => 'html', - // 默认AJAX 数据返回格式,可选json xml ... - 'default_ajax_return' => 'json', - // 默认JSONP格式返回的处理方法 - 'default_jsonp_handler' => 'jsonpReturn', - // 默认JSONP处理方法 - 'var_jsonp_handler' => 'callback', - // 默认时区 - 'default_timezone' => 'PRC', - // 是否开启多语言 - 'lang_switch_on' => false, - // 默认全局过滤方法 用逗号分隔多个 - 'default_filter' => '', - // 默认语言 - 'default_lang' => 'zh-cn', - // 应用类库后缀 - 'class_suffix' => false, - // 控制器类后缀 - 'controller_suffix' => false, + // +---------------------------------------------------------------------- + // | 模块设置 + // +---------------------------------------------------------------------- - // +---------------------------------------------------------------------- - // | 模块设置 - // +---------------------------------------------------------------------- + // 自动搜索控制器 + 'controller_auto_search' => false, + // 操作方法前缀 + 'use_action_prefix' => false, + // 操作方法后缀 + 'action_suffix' => '', + // 默认的空控制器名 + 'empty_controller' => 'Error', + // 默认的空模块名 + 'empty_module' => '', + // 默认模块名 + 'default_module' => 'index', + // 是否支持多模块 + 'app_multi_module' => true, + // 禁止访问模块 + 'deny_module_list' => ['common'], + // 默认控制器名 + 'default_controller' => 'Index', + // 默认操作名 + 'default_action' => 'index', + // 是否自动转换URL中的控制器和操作名 + 'url_convert' => true, + // 默认的访问控制器层 + 'url_controller_layer' => 'controller', + // 应用类库后缀 + 'class_suffix' => false, + // 控制器类后缀 + 'controller_suffix' => false, - // 默认模块名 - 'default_module' => 'index', - // 禁止访问模块 - 'deny_module_list' => ['common'], - // 默认控制器名 - 'default_controller' => 'Index', - // 默认操作名 - 'default_action' => 'index', - // 默认验证器 - 'default_validate' => '', - // 默认的空控制器名 - 'empty_controller' => 'Error', - // 操作方法后缀 - 'action_suffix' => '', - // 自动搜索控制器 - 'controller_auto_search' => false, + // +---------------------------------------------------------------------- + // | URL请求设置 + // +---------------------------------------------------------------------- - // +---------------------------------------------------------------------- - // | URL设置 - // +---------------------------------------------------------------------- + // 默认全局过滤方法 用逗号分隔多个 + 'default_filter' => '', + // PATHINFO变量名 用于兼容模式 + 'var_pathinfo' => 's', + // 兼容PATH_INFO获取 + 'pathinfo_fetch' => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'], + // HTTPS代理标识 + 'https_agent_name' => '', + // IP代理获取标识 + 'http_agent_ip' => 'HTTP_X_REAL_IP', + // URL伪静态后缀 + 'url_html_suffix' => 'html', + // 域名根,如thinkphp.cn + 'url_domain_root' => '', + // 表单请求类型伪装变量 + 'var_method' => '_method', + // 表单ajax伪装变量 + 'var_ajax' => '_ajax', + // 表单pjax伪装变量 + 'var_pjax' => '_pjax', + // 是否开启请求缓存 true自动缓存 支持设置请求缓存规则 + 'request_cache' => false, + // 请求缓存有效期 + 'request_cache_expire' => null, + // 全局请求缓存排除规则 + 'request_cache_except' => [], + + // +---------------------------------------------------------------------- + // | 路由设置 + // +---------------------------------------------------------------------- - // PATHINFO变量名 用于兼容模式 - 'var_pathinfo' => 's', - // 兼容PATH_INFO获取 - 'pathinfo_fetch' => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'], - // pathinfo分隔符 - 'pathinfo_depr' => '/', - // URL伪静态后缀 - 'url_html_suffix' => 'html', - // URL普通方式参数 用于自动生成 - 'url_common_param' => false, - // URL参数方式 0 按名称成对解析 1 按顺序解析 - 'url_param_type' => 0, - // 是否开启路由 - 'url_route_on' => true, - // 路由配置文件(支持配置多个) - 'route_config_file' => ['route'], - // 是否强制使用路由 - 'url_route_must' => false, - // 域名部署 - 'url_domain_deploy' => false, - // 域名根,如thinkphp.cn - 'url_domain_root' => '', - // 是否自动转换URL中的控制器和操作名 - 'url_convert' => true, - // 默认的访问控制器层 - 'url_controller_layer' => 'controller', - // 表单请求类型伪装变量 - 'var_method' => '_method', - // 表单ajax伪装变量 - 'var_ajax' => '_ajax', - // 表单pjax伪装变量 - 'var_pjax' => '_pjax', + // pathinfo分隔符 + 'pathinfo_depr' => '/', + // URL普通方式参数 用于自动生成 + 'url_common_param' => false, + // URL参数方式 0 按名称成对解析 1 按顺序解析 + 'url_param_type' => 0, + // 是否开启路由延迟解析 + 'url_lazy_route' => false, + // 是否强制使用路由 + 'url_route_must' => false, + // 合并路由规则 + 'route_rule_merge' => false, + // 路由是否完全匹配 + 'route_complete_match' => false, + // 使用注解路由 + 'route_annotation' => false, + // 默认的路由变量规则 + 'default_route_pattern' => '\w+', + // 是否开启路由缓存 + 'route_check_cache' => false, + // 路由缓存的Key自定义设置(闭包),默认为当前URL和请求类型的md5 + 'route_check_cache_key' => '', + + // +---------------------------------------------------------------------- + // | 异常及错误设置 + // +---------------------------------------------------------------------- + + // 默认跳转页面对应的模板文件 + 'dispatch_success_tmpl' => __DIR__ . '/tpl/dispatch_jump.tpl', + 'dispatch_error_tmpl' => __DIR__ . '/tpl/dispatch_jump.tpl', + // 异常页面的模板文件 + 'exception_tmpl' => __DIR__ . '/tpl/think_exception.tpl', + // 错误显示信息,非调试模式有效 + 'error_message' => '页面错误!请稍后再试~', + // 显示错误信息 + 'show_error_msg' => false, + // 异常处理handle类 留空使用 \think\exception\Handle + 'exception_handle' => '', + ], // +---------------------------------------------------------------------- // | 模板设置 // +---------------------------------------------------------------------- - 'template' => [ + 'template' => [ + // 默认模板渲染规则 1 解析为小写+下划线 2 全部转换小写 + 'auto_rule' => 1, // 模板引擎类型 支持 php think 支持扩展 'type' => 'Think', - // 模板路径 + // 视图基础目录,配置目录为所有模块的视图起始目录 + 'view_base' => '', + // 当前模板的视图目录 留空为自动获取 'view_path' => '', // 模板后缀 'view_suffix' => 'html', // 模板文件名分隔符 - 'view_depr' => DS, + 'view_depr' => DIRECTORY_SEPARATOR, // 模板引擎普通标签开始标记 'tpl_begin' => '{', // 模板引擎普通标签结束标记 @@ -123,56 +173,42 @@ return [ 'taglib_end' => '}', ], - // 视图输出字符串内容替换 - 'view_replace_str' => [], - // 默认跳转页面对应的模板文件 - 'dispatch_success_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl', - 'dispatch_error_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl', - - // +---------------------------------------------------------------------- - // | 异常及错误设置 - // +---------------------------------------------------------------------- - - // 异常页面的模板文件 - 'exception_tmpl' => THINK_PATH . 'tpl' . DS . 'think_exception.tpl', - - // 错误显示信息,非调试模式有效 - 'error_message' => '页面错误!请稍后再试~', - // 显示错误信息 - 'show_error_msg' => false, - // 异常处理handle类 留空使用 \think\exception\Handle - 'exception_handle' => '', - // +---------------------------------------------------------------------- // | 日志设置 // +---------------------------------------------------------------------- - 'log' => [ + 'log' => [ // 日志记录方式,内置 file socket 支持扩展 - 'type' => 'File', + 'type' => 'File', // 日志保存目录 - 'path' => LOG_PATH, + //'path' => LOG_PATH, // 日志记录级别 - 'level' => [], + 'level' => [], + // 是否记录trace信息到日志 + 'record_trace' => false, + // 是否JSON格式记录 + 'json' => false, ], // +---------------------------------------------------------------------- // | Trace设置 开启 app_trace 后 有效 // +---------------------------------------------------------------------- - 'trace' => [ + + 'trace' => [ // 内置Html Console 支持扩展 'type' => 'Html', + 'file' => __DIR__ . '/tpl/page_trace.tpl', ], // +---------------------------------------------------------------------- // | 缓存设置 // +---------------------------------------------------------------------- - 'cache' => [ + 'cache' => [ // 驱动方式 'type' => 'File', // 缓存保存目录 - 'path' => CACHE_PATH, + //'path' => CACHE_PATH, // 缓存前缀 'prefix' => '', // 缓存有效期 0表示永久缓存 @@ -183,7 +219,7 @@ return [ // | 会话设置 // +---------------------------------------------------------------------- - 'session' => [ + 'session' => [ 'id' => '', // SESSION_ID的提交变量,解决flash上传跨域 'var_session_id' => '', @@ -193,12 +229,15 @@ return [ 'type' => '', // 是否自动开启 SESSION 'auto_start' => true, + 'httponly' => true, + 'secure' => false, ], // +---------------------------------------------------------------------- // | Cookie设置 // +---------------------------------------------------------------------- - 'cookie' => [ + + 'cookie' => [ // cookie 名称前缀 'prefix' => '', // cookie 保存时间 @@ -219,48 +258,67 @@ return [ // | 数据库设置 // +---------------------------------------------------------------------- - 'database' => [ + 'database' => [ // 数据库类型 - 'type' => 'mysql', + 'type' => 'mysql', // 数据库连接DSN配置 - 'dsn' => '', + 'dsn' => '', // 服务器地址 - 'hostname' => 'localhost', + 'hostname' => '127.0.0.1', // 数据库名 - 'database' => '', + 'database' => '', // 数据库用户名 - 'username' => 'root', + 'username' => 'root', // 数据库密码 - 'password' => '', + 'password' => '', // 数据库连接端口 - 'hostport' => '', + 'hostport' => '', // 数据库连接参数 - 'params' => [], + 'params' => [], // 数据库编码默认采用utf8 - 'charset' => 'utf8', + 'charset' => 'utf8', // 数据库表前缀 - 'prefix' => '', + 'prefix' => '', // 数据库调试模式 - 'debug' => false, + 'debug' => false, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) - 'deploy' => 0, + 'deploy' => 0, // 数据库读写是否分离 主从式有效 - 'rw_separate' => false, + 'rw_separate' => false, // 读写分离后 主服务器数量 - 'master_num' => 1, + 'master_num' => 1, // 指定从服务器序号 - 'slave_no' => '', + 'slave_no' => '', // 是否严格检查字段是否存在 - 'fields_strict' => true, + 'fields_strict' => true, + // 数据集返回类型 + 'resultset_type' => 'array', // 自动写入时间戳字段 - 'auto_timestamp' => false, + 'auto_timestamp' => false, + // 时间字段取出后的默认时间格式 + 'datetime_format' => 'Y-m-d H:i:s', + // 是否需要进行SQL性能分析 + 'sql_explain' => false, + // 查询对象 + 'query' => '\\think\\db\\Query', ], //分页配置 - 'paginate' => [ + 'paginate' => [ 'type' => 'bootstrap', 'var_page' => 'page', 'list_rows' => 15, ], + //控制台配置 + 'console' => [ + 'name' => 'Think Console', + 'version' => '0.1', + 'user' => null, + ], + + // 中间件配置 + 'middleware' => [ + 'default_namespace' => 'app\\http\\middleware\\', + ], ]; diff --git a/helper.php b/helper.php index 6ab2cb348c361536350164a24e3976477bca654f..372357f1284fe44f7b1d1a3419dc852ae1122a85 100644 --- a/helper.php +++ b/helper.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,49 +13,276 @@ // ThinkPHP 助手函数 //------------------------- -use think\Cache; -use think\Config; -use think\Cookie; +use think\Container; use think\Db; -use think\Debug; use think\exception\HttpException; use think\exception\HttpResponseException; -use think\Lang; -use think\Loader; -use think\Log; -use think\Request; +use think\facade\Cache; +use think\facade\Config; +use think\facade\Cookie; +use think\facade\Debug; +use think\facade\Env; +use think\facade\Hook; +use think\facade\Lang; +use think\facade\Log; +use think\facade\Request; +use think\facade\Route; +use think\facade\Session; +use think\facade\Url; use think\Response; -use think\Session; -use think\Url; -use think\View; +use think\route\RuleItem; -if (!function_exists('load_trait')) { +if (!function_exists('abort')) { /** - * 快速导入Traits PHP5.5以上无需调用 - * @param string $class trait库 - * @param string $ext 类库后缀 - * @return boolean + * 抛出HTTP异常 + * @param integer|Response $code 状态码 或者 Response对象实例 + * @param string $message 错误信息 + * @param array $header 参数 */ - function load_trait($class, $ext = EXT) + function abort($code, $message = null, $header = []) { - return Loader::import($class, TRAIT_PATH, $ext); + if ($code instanceof Response) { + throw new HttpResponseException($code); + } else { + throw new HttpException($code, $message, null, $header); + } } } -if (!function_exists('exception')) { +if (!function_exists('action')) { /** - * 抛出异常处理 + * 调用模块的操作方法 参数格式 [模块/控制器/]操作 + * @param string $url 调用地址 + * @param string|array $vars 调用参数 支持字符串和数组 + * @param string $layer 要调用的控制层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @return mixed + */ + function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) + { + return app()->action($url, $vars, $layer, $appendSuffix); + } +} + +if (!function_exists('app')) { + /** + * 快速获取容器中的实例 支持依赖注入 + * @param string $name 类名或标识 默认获取当前应用实例 + * @param array $args 参数 + * @param bool $newInstance 是否每次创建新的实例 + * @return mixed|\think\App + */ + function app($name = 'think\App', $args = [], $newInstance = false) + { + return Container::get($name, $args, $newInstance); + } +} + +if (!function_exists('behavior')) { + /** + * 执行某个行为(run方法) 支持依赖注入 + * @param mixed $behavior 行为类名或者别名 + * @param mixed $args 参数 + * @return mixed + */ + function behavior($behavior, $args = null) + { + return Hook::exec($behavior, $args); + } +} + +if (!function_exists('bind')) { + /** + * 绑定一个类到容器 + * @access public + * @param string $abstract 类标识、接口 + * @param mixed $concrete 要绑定的类、闭包或者实例 + * @return Container + */ + function bind($abstract, $concrete = null) + { + return Container::getInstance()->bindTo($abstract, $concrete); + } +} + +if (!function_exists('cache')) { + /** + * 缓存管理 + * @param mixed $name 缓存名称,如果为数组表示进行缓存设置 + * @param mixed $value 缓存值 + * @param mixed $options 缓存参数 + * @param string $tag 缓存标签 + * @return mixed + */ + function cache($name, $value = '', $options = null, $tag = null) + { + if (is_array($options)) { + // 缓存操作的同时初始化 + Cache::connect($options); + } elseif (is_array($name)) { + // 缓存初始化 + return Cache::connect($name); + } + + if ('' === $value) { + // 获取缓存 + return 0 === strpos($name, '?') ? Cache::has(substr($name, 1)) : Cache::get($name); + } elseif (is_null($value)) { + // 删除缓存 + return Cache::rm($name); + } else { + // 缓存数据 + if (is_array($options)) { + $expire = isset($options['expire']) ? $options['expire'] : null; //修复查询缓存无法设置过期时间 + } else { + $expire = is_numeric($options) ? $options : null; //默认快捷缓存设置过期时间 + } + + if (is_null($tag)) { + return Cache::set($name, $value, $expire); + } else { + return Cache::tag($tag)->set($name, $value, $expire); + } + } + } +} + +if (!function_exists('call')) { + /** + * 调用反射执行callable 支持依赖注入 + * @param mixed $callable 支持闭包等callable写法 + * @param array $args 参数 + * @return mixed + */ + function call($callable, $args = []) + { + return Container::getInstance()->invoke($callable, $args); + } +} + +if (!function_exists('class_basename')) { + /** + * 获取类名(不包含命名空间) * - * @param string $msg 异常消息 - * @param integer $code 异常代码 默认为0 - * @param string $exception 异常类 + * @param string|object $class + * @return string + */ + function class_basename($class) + { + $class = is_object($class) ? get_class($class) : $class; + return basename(str_replace('\\', '/', $class)); + } +} + +if (!function_exists('class_uses_recursive')) { + /** + *获取一个类里所有用到的trait,包括父类的 * - * @throws Exception + * @param $class + * @return array */ - function exception($msg, $code = 0, $exception = '') + function class_uses_recursive($class) { - $e = $exception ?: '\think\Exception'; - throw new $e($msg, $code); + if (is_object($class)) { + $class = get_class($class); + } + + $results = []; + $classes = array_merge([$class => $class], class_parents($class)); + foreach ($classes as $class) { + $results += trait_uses_recursive($class); + } + + return array_unique($results); + } +} + +if (!function_exists('config')) { + /** + * 获取和设置配置参数 + * @param string|array $name 参数名 + * @param mixed $value 参数值 + * @return mixed + */ + function config($name = '', $value = null) + { + if (is_null($value) && is_string($name)) { + if ('.' == substr($name, -1)) { + return Config::pull(substr($name, 0, -1)); + } + + return 0 === strpos($name, '?') ? Config::has(substr($name, 1)) : Config::get($name); + } else { + return Config::set($name, $value); + } + } +} + +if (!function_exists('container')) { + /** + * 获取容器对象实例 + * @return Container + */ + function container() + { + return Container::getInstance(); + } +} + +if (!function_exists('controller')) { + /** + * 实例化控制器 格式:[模块/]控制器 + * @param string $name 资源地址 + * @param string $layer 控制层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @return \think\Controller + */ + function controller($name, $layer = 'controller', $appendSuffix = false) + { + return app()->controller($name, $layer, $appendSuffix); + } +} + +if (!function_exists('cookie')) { + /** + * Cookie管理 + * @param string|array $name cookie名称,如果为数组表示进行cookie设置 + * @param mixed $value cookie值 + * @param mixed $option 参数 + * @return mixed + */ + function cookie($name, $value = '', $option = null) + { + if (is_array($name)) { + // 初始化 + Cookie::init($name); + } elseif (is_null($name)) { + // 清除 + Cookie::clear($value); + } elseif ('' === $value) { + // 获取 + return 0 === strpos($name, '?') ? Cookie::has(substr($name, 1), $option) : Cookie::get($name); + } elseif (is_null($value)) { + // 删除 + return Cookie::delete($name); + } else { + // 设置 + return Cookie::set($name, $value, $option); + } + } +} + +if (!function_exists('db')) { + /** + * 实例化数据库类 + * @param string $name 操作的数据表名称(不含前缀) + * @param array|string $config 数据库配置参数 + * @param bool $force 是否强制重新连接 + * @return \think\db\Query + */ + function db($name = '', $config = [], $force = true) + { + return Db::connect($config, $force)->name($name); } } @@ -77,35 +304,61 @@ if (!function_exists('debug')) { } } -if (!function_exists('lang')) { +if (!function_exists('dump')) { /** - * 获取语言变量值 - * @param string $name 语言变量名 - * @param array $vars 动态变量值 - * @param string $lang 语言 - * @return mixed + * 浏览器友好的变量输出 + * @param mixed $var 变量 + * @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串 + * @param string $label 标签 默认为空 + * @return void|string */ - function lang($name, $vars = [], $lang = '') + function dump($var, $echo = true, $label = null) { - return Lang::get($name, $vars, $lang); + return Debug::dump($var, $echo, $label); } } -if (!function_exists('config')) { +if (!function_exists('env')) { /** - * 获取和设置配置参数 - * @param string|array $name 参数名 - * @param mixed $value 参数值 - * @param string $range 作用域 + * 获取环境变量值 + * @access public + * @param string $name 环境变量名(支持二级 .号分割) + * @param string $default 默认值 * @return mixed */ - function config($name = '', $value = null, $range = '') + function env($name = null, $default = null) { - if (is_null($value) && is_string($name)) { - return 0 === strpos($name, '?') ? Config::has(substr($name, 1), $range) : Config::get($name, $range); - } else { - return Config::set($name, $value, $range); - } + return Env::get($name, $default); + } +} + +if (!function_exists('exception')) { + /** + * 抛出异常处理 + * + * @param string $msg 异常消息 + * @param integer $code 异常代码 默认为0 + * @param string $exception 异常类 + * + * @throws Exception + */ + function exception($msg, $code = 0, $exception = '') + { + $e = $exception ?: '\think\Exception'; + throw new $e($msg, $code); + } +} + +if (!function_exists('halt')) { + /** + * 调试变量并且中断输出 + * @param mixed $var 调试变量或者信息 + */ + function halt($var) + { + dump($var); + + throw new HttpResponseException(new Response); } } @@ -117,16 +370,17 @@ if (!function_exists('input')) { * @param string $filter 过滤方法 * @return mixed */ - function input($key = '', $default = null, $filter = null) + function input($key = '', $default = null, $filter = '') { if (0 === strpos($key, '?')) { $key = substr($key, 1); $has = true; } + if ($pos = strpos($key, '.')) { // 指定参数来源 $method = substr($key, 0, $pos); - if (in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) { + if (in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'route', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) { $key = substr($key, $pos + 1); } else { $method = 'param'; @@ -135,6 +389,7 @@ if (!function_exists('input')) { // 默认为自动判断 $method = 'param'; } + if (isset($has)) { return request()->has($key, $method, $default); } else { @@ -143,143 +398,144 @@ if (!function_exists('input')) { } } -if (!function_exists('widget')) { - /** - * 渲染输出Widget - * @param string $name Widget名称 - * @param array $data 传入的参数 - * @return mixed - */ - function widget($name, $data = []) - { - return Loader::action($name, $data, 'widget'); - } -} - -if (!function_exists('model')) { +if (!function_exists('json')) { /** - * 实例化Model - * @param string $name Model名称 - * @param string $layer 业务层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @return \think\Model + * 获取\think\response\Json对象实例 + * @param mixed $data 返回的数据 + * @param integer $code 状态码 + * @param array $header 头部 + * @param array $options 参数 + * @return \think\response\Json */ - function model($name = '', $layer = 'model', $appendSuffix = false) + function json($data = [], $code = 200, $header = [], $options = []) { - return Loader::model($name, $layer, $appendSuffix); + return Response::create($data, 'json', $code, $header, $options); } } -if (!function_exists('validate')) { +if (!function_exists('jsonp')) { /** - * 实例化验证器 - * @param string $name 验证器名称 - * @param string $layer 业务层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @return \think\Validate + * 获取\think\response\Jsonp对象实例 + * @param mixed $data 返回的数据 + * @param integer $code 状态码 + * @param array $header 头部 + * @param array $options 参数 + * @return \think\response\Jsonp */ - function validate($name = '', $layer = 'validate', $appendSuffix = false) + function jsonp($data = [], $code = 200, $header = [], $options = []) { - return Loader::validate($name, $layer, $appendSuffix); + return Response::create($data, 'jsonp', $code, $header, $options); } } -if (!function_exists('db')) { +if (!function_exists('lang')) { /** - * 实例化数据库类 - * @param string $name 操作的数据表名称(不含前缀) - * @param array|string $config 数据库配置参数 - * @param bool $force 是否强制重新连接 - * @return \think\db\Query + * 获取语言变量值 + * @param string $name 语言变量名 + * @param array $vars 动态变量值 + * @param string $lang 语言 + * @return mixed */ - function db($name = '', $config = [], $force = true) + function lang($name, $vars = [], $lang = '') { - return Db::connect($config, $force)->name($name); + return Lang::get($name, $vars, $lang); } } -if (!function_exists('controller')) { +if (!function_exists('model')) { /** - * 实例化控制器 格式:[模块/]控制器 - * @param string $name 资源地址 - * @param string $layer 控制层名称 + * 实例化Model + * @param string $name Model名称 + * @param string $layer 业务层名称 * @param bool $appendSuffix 是否添加类名后缀 - * @return \think\Controller + * @return \think\Model */ - function controller($name, $layer = 'controller', $appendSuffix = false) + function model($name = '', $layer = 'model', $appendSuffix = false) { - return Loader::controller($name, $layer, $appendSuffix); + return app()->model($name, $layer, $appendSuffix); } } -if (!function_exists('action')) { +if (!function_exists('parse_name')) { /** - * 调用模块的操作方法 参数格式 [模块/控制器/]操作 - * @param string $url 调用地址 - * @param string|array $vars 调用参数 支持字符串和数组 - * @param string $layer 要调用的控制层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @return mixed + * 字符串命名风格转换 + * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格 + * @param string $name 字符串 + * @param integer $type 转换类型 + * @param bool $ucfirst 首字母是否大写(驼峰规则) + * @return string */ - function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) + function parse_name($name, $type = 0, $ucfirst = true) { - return Loader::action($url, $vars, $layer, $appendSuffix); + if ($type) { + $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) { + return strtoupper($match[1]); + }, $name); + + return $ucfirst ? ucfirst($name) : lcfirst($name); + } else { + return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); + } } } -if (!function_exists('import')) { +if (!function_exists('redirect')) { /** - * 导入所需的类库 同java的Import 本函数有缓存功能 - * @param string $class 类库命名空间字符串 - * @param string $baseUrl 起始路径 - * @param string $ext 导入的文件扩展名 - * @return boolean + * 获取\think\response\Redirect对象实例 + * @param mixed $url 重定向地址 支持Url::build方法的地址 + * @param array|integer $params 额外参数 + * @param integer $code 状态码 + * @return \think\response\Redirect */ - function import($class, $baseUrl = '', $ext = EXT) + function redirect($url = [], $params = [], $code = 302) { - return Loader::import($class, $baseUrl, $ext); + if (is_integer($params)) { + $code = $params; + $params = []; + } + + return Response::create($url, 'redirect', $code)->params($params); } } -if (!function_exists('vendor')) { +if (!function_exists('request')) { /** - * 快速导入第三方框架类库 所有第三方框架的类库文件统一放到 系统的Vendor目录下面 - * @param string $class 类库 - * @param string $ext 类库后缀 - * @return boolean + * 获取当前Request对象实例 + * @return Request */ - function vendor($class, $ext = EXT) + function request() { - return Loader::import($class, VENDOR_PATH, $ext); + return app('request'); } } -if (!function_exists('dump')) { +if (!function_exists('response')) { /** - * 浏览器友好的变量输出 - * @param mixed $var 变量 - * @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串 - * @param string $label 标签 默认为空 - * @return void|string + * 创建普通 Response 对象实例 + * @param mixed $data 输出数据 + * @param int|string $code 状态码 + * @param array $header 头信息 + * @param string $type + * @return Response */ - function dump($var, $echo = true, $label = null) + function response($data = [], $code = 200, $header = [], $type = 'html') { - return Debug::dump($var, $echo, $label); + return Response::create($data, $type, $code, $header); } } -if (!function_exists('url')) { +if (!function_exists('route')) { /** - * Url生成 - * @param string $url 路由地址 - * @param string|array $vars 变量 - * @param bool|string $suffix 生成的URL后缀 - * @param bool|string $domain 域名 - * @return string + * 路由注册 + * @param string $rule 路由规则 + * @param mixed $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem */ - function url($url = '', $vars = '', $suffix = true, $domain = false) + function route($rule, $route, $option = [], $pattern = []) { - return Url::build($url, $vars, $suffix, $domain); + return Route::rule($rule, $route, '*', $option, $pattern); } } @@ -312,72 +568,18 @@ if (!function_exists('session')) { } } -if (!function_exists('cookie')) { +if (!function_exists('token')) { /** - * Cookie管理 - * @param string|array $name cookie名称,如果为数组表示进行cookie设置 - * @param mixed $value cookie值 - * @param mixed $option 参数 - * @return mixed + * 生成表单令牌 + * @param string $name 令牌名称 + * @param mixed $type 令牌生成方法 + * @return string */ - function cookie($name, $value = '', $option = null) + function token($name = '__token__', $type = 'md5') { - if (is_array($name)) { - // 初始化 - Cookie::init($name); - } elseif (is_null($name)) { - // 清除 - Cookie::clear($value); - } elseif ('' === $value) { - // 获取 - return 0 === strpos($name, '?') ? Cookie::has(substr($name, 1), $option) : Cookie::get($name); - } elseif (is_null($value)) { - // 删除 - return Cookie::delete($name); - } else { - // 设置 - return Cookie::set($name, $value, $option); - } - } -} + $token = Request::token($name, $type); -if (!function_exists('cache')) { - /** - * 缓存管理 - * @param mixed $name 缓存名称,如果为数组表示进行缓存设置 - * @param mixed $value 缓存值 - * @param mixed $options 缓存参数 - * @param string $tag 缓存标签 - * @return mixed - */ - function cache($name, $value = '', $options = null, $tag = null) - { - if (is_array($options)) { - // 缓存操作的同时初始化 - Cache::connect($options); - } elseif (is_array($name)) { - // 缓存初始化 - return Cache::connect($name); - } - if ('' === $value) { - // 获取缓存 - return 0 === strpos($name, '?') ? Cache::has(substr($name, 1)) : Cache::get($name); - } elseif (is_null($value)) { - // 删除缓存 - return Cache::rm($name); - } else { - // 缓存数据 - if (is_array($options)) { - $expire = isset($options['expire']) ? $options['expire'] : null; //修复查询缓存无法设置过期时间 - } else { - $expire = is_numeric($options) ? $options : null; //默认快捷缓存设置过期时间 - } - if (is_null($tag)) { - return Cache::set($name, $value, $expire); - } else { - return Cache::tag($tag)->set($name, $value, $expire); - } - } + return ''; } } @@ -386,7 +588,7 @@ if (!function_exists('trace')) { * 记录日志信息 * @param mixed $log log信息 支持字符串和数组 * @param string $level 日志级别 - * @return void|array + * @return array|void */ function trace($log = '[think]', $level = 'log') { @@ -398,74 +600,78 @@ if (!function_exists('trace')) { } } -if (!function_exists('request')) { +if (!function_exists('trait_uses_recursive')) { /** - * 获取当前Request对象实例 - * @return Request + * 获取一个trait里所有引用到的trait + * + * @param string $trait + * @return array */ - function request() + function trait_uses_recursive($trait) { - return Request::instance(); + $traits = class_uses($trait); + foreach ($traits as $trait) { + $traits += trait_uses_recursive($trait); + } + + return $traits; } } -if (!function_exists('response')) { +if (!function_exists('url')) { /** - * 创建普通 Response 对象实例 - * @param mixed $data 输出数据 - * @param int|string $code 状态码 - * @param array $header 头信息 - * @param string $type - * @return Response + * Url生成 + * @param string $url 路由地址 + * @param string|array $vars 变量 + * @param bool|string $suffix 生成的URL后缀 + * @param bool|string $domain 域名 + * @return string */ - function response($data = [], $code = 200, $header = [], $type = 'html') + function url($url = '', $vars = '', $suffix = true, $domain = false) { - return Response::create($data, $type, $code, $header); + return Url::build($url, $vars, $suffix, $domain); } } -if (!function_exists('view')) { +if (!function_exists('validate')) { /** - * 渲染模板输出 - * @param string $template 模板文件 - * @param array $vars 模板变量 - * @param array $replace 模板替换 - * @param integer $code 状态码 - * @return \think\response\View + * 实例化验证器 + * @param string $name 验证器名称 + * @param string $layer 业务层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @return \think\Validate */ - function view($template = '', $vars = [], $replace = [], $code = 200) + function validate($name = '', $layer = 'validate', $appendSuffix = false) { - return Response::create($template, 'view', $code)->replace($replace)->assign($vars); + return app()->validate($name, $layer, $appendSuffix); } } -if (!function_exists('json')) { +if (!function_exists('view')) { /** - * 获取\think\response\Json对象实例 - * @param mixed $data 返回的数据 - * @param integer $code 状态码 - * @param array $header 头部 - * @param array $options 参数 - * @return \think\response\Json + * 渲染模板输出 + * @param string $template 模板文件 + * @param array $vars 模板变量 + * @param integer $code 状态码 + * @param callable $filter 内容过滤 + * @return \think\response\View */ - function json($data = [], $code = 200, $header = [], $options = []) + function view($template = '', $vars = [], $code = 200, $filter = null) { - return Response::create($data, 'json', $code, $header, $options); + return Response::create($template, 'view', $code)->assign($vars)->filter($filter); } } -if (!function_exists('jsonp')) { +if (!function_exists('widget')) { /** - * 获取\think\response\Jsonp对象实例 - * @param mixed $data 返回的数据 - * @param integer $code 状态码 - * @param array $header 头部 - * @param array $options 参数 - * @return \think\response\Jsonp + * 渲染输出Widget + * @param string $name Widget名称 + * @param array $data 传入的参数 + * @return mixed */ - function jsonp($data = [], $code = 200, $header = [], $options = []) + function widget($name, $data = []) { - return Response::create($data, 'jsonp', $code, $header, $options); + return app()->action($name, $data, 'widget'); } } @@ -483,64 +689,3 @@ if (!function_exists('xml')) { return Response::create($data, 'xml', $code, $header, $options); } } - -if (!function_exists('redirect')) { - /** - * 获取\think\response\Redirect对象实例 - * @param mixed $url 重定向地址 支持Url::build方法的地址 - * @param array|integer $params 额外参数 - * @param integer $code 状态码 - * @return \think\response\Redirect - */ - function redirect($url = [], $params = [], $code = 302) - { - if (is_integer($params)) { - $code = $params; - $params = []; - } - return Response::create($url, 'redirect', $code)->params($params); - } -} - -if (!function_exists('abort')) { - /** - * 抛出HTTP异常 - * @param integer|Response $code 状态码 或者 Response对象实例 - * @param string $message 错误信息 - * @param array $header 参数 - */ - function abort($code, $message = null, $header = []) - { - if ($code instanceof Response) { - throw new HttpResponseException($code); - } else { - throw new HttpException($code, $message, null, $header); - } - } -} - -if (!function_exists('halt')) { - /** - * 调试变量并且中断输出 - * @param mixed $var 调试变量或者信息 - */ - function halt($var) - { - dump($var); - throw new HttpResponseException(new Response); - } -} - -if (!function_exists('token')) { - /** - * 生成表单令牌 - * @param string $name 令牌名称 - * @param mixed $type 令牌生成方法 - * @return string - */ - function token($name = '__token__', $type = 'md5') - { - $token = Request::instance()->token($name, $type); - return ''; - } -} diff --git a/lang/zh-cn.php b/lang/zh-cn.php index db43a1c418b68d9596e680caed00eaa9b2919ab1..d7c82f0c19a913c9e532de64a7a34faf6c5dc8c5 100644 --- a/lang/zh-cn.php +++ b/lang/zh-cn.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,54 +12,131 @@ // 核心中文语言包 return [ // 系统错误提示 - 'Undefined variable' => '未定义变量', - 'Undefined index' => '未定义数组索引', - 'Undefined offset' => '未定义数组下标', - 'Parse error' => '语法解析错误', - 'Type error' => '类型错误', - 'Fatal error' => '致命错误', - 'syntax error' => '语法错误', + 'Undefined variable' => '未定义变量', + 'Undefined index' => '未定义数组索引', + 'Undefined offset' => '未定义数组下标', + 'Parse error' => '语法解析错误', + 'Type error' => '类型错误', + 'Fatal error' => '致命错误', + 'syntax error' => '语法错误', // 框架核心错误提示 - 'dispatch type not support' => '不支持的调度类型', - 'method param miss' => '方法参数错误', - 'method not exists' => '方法不存在', - 'module not exists' => '模块不存在', - 'controller not exists' => '控制器不存在', - 'class not exists' => '类不存在', - 'property not exists' => '类的属性不存在', - 'template not exists' => '模板文件不存在', - 'illegal controller name' => '非法的控制器名称', - 'illegal action name' => '非法的操作名称', - 'url suffix deny' => '禁止的URL后缀访问', - 'Route Not Found' => '当前访问路由未定义', - 'Underfined db type' => '未定义数据库类型', - 'variable type error' => '变量类型错误', - 'PSR-4 error' => 'PSR-4 规范错误', - 'not support total' => '简洁模式下不能获取数据总数', - 'not support last' => '简洁模式下不能获取最后一页', - 'error session handler' => '错误的SESSION处理器类', - 'not allow php tag' => '模板不允许使用PHP语法', - 'not support' => '不支持', - 'redisd master' => 'Redisd 主服务器错误', - 'redisd slave' => 'Redisd 从服务器错误', - 'must run at sae' => '必须在SAE运行', - 'memcache init error' => '未开通Memcache服务,请在SAE管理平台初始化Memcache服务', - 'KVDB init error' => '没有初始化KVDB,请在SAE管理平台初始化KVDB服务', - 'fields not exists' => '数据表字段不存在', - 'where express error' => '查询表达式错误', - 'no data to update' => '没有任何数据需要更新', - 'miss data to insert' => '缺少需要写入的数据', - 'miss complex primary data' => '缺少复合主键数据', - 'miss update condition' => '缺少更新条件', - 'model data Not Found' => '模型数据不存在', - 'table data not Found' => '表数据不存在', - 'delete without condition' => '没有条件不会执行删除操作', - 'miss relation data' => '缺少关联表数据', - 'tag attr must' => '模板标签属性必须', - 'tag error' => '模板标签错误', - 'cache write error' => '缓存写入失败', - 'sae mc write error' => 'SAE mc 写入错误', - 'route name not exists' => '路由标识不存在(或参数不够)', - 'invalid request' => '非法请求', + 'dispatch type not support' => '不支持的调度类型', + 'method param miss' => '方法参数错误', + 'method not exists' => '方法不存在', + 'function not exists' => '函数不存在', + 'module not exists' => '模块不存在', + 'controller not exists' => '控制器不存在', + 'class not exists' => '类不存在', + 'property not exists' => '类的属性不存在', + 'template not exists' => '模板文件不存在', + 'illegal controller name' => '非法的控制器名称', + 'illegal action name' => '非法的操作名称', + 'url suffix deny' => '禁止的URL后缀访问', + 'Route Not Found' => '当前访问路由未定义或不匹配', + 'Undefined db type' => '未定义数据库类型', + 'variable type error' => '变量类型错误', + 'PSR-4 error' => 'PSR-4 规范错误', + 'not support total' => '简洁模式下不能获取数据总数', + 'not support last' => '简洁模式下不能获取最后一页', + 'error session handler' => '错误的SESSION处理器类', + 'not allow php tag' => '模板不允许使用PHP语法', + 'not support' => '不支持', + 'redisd master' => 'Redisd 主服务器错误', + 'redisd slave' => 'Redisd 从服务器错误', + 'must run at sae' => '必须在SAE运行', + 'memcache init error' => '未开通Memcache服务,请在SAE管理平台初始化Memcache服务', + 'KVDB init error' => '没有初始化KVDB,请在SAE管理平台初始化KVDB服务', + 'fields not exists' => '数据表字段不存在', + 'where express error' => '查询表达式错误', + 'no data to update' => '没有任何数据需要更新', + 'miss data to insert' => '缺少需要写入的数据', + 'not support data' => '不支持的数据表达式', + 'miss complex primary data' => '缺少复合主键数据', + 'miss update condition' => '缺少更新条件', + 'model data Not Found' => '模型数据不存在', + 'table data not Found' => '表数据不存在', + 'delete without condition' => '没有条件不会执行删除操作', + 'miss relation data' => '缺少关联表数据', + 'tag attr must' => '模板标签属性必须', + 'tag error' => '模板标签错误', + 'cache write error' => '缓存写入失败', + 'sae mc write error' => 'SAE mc 写入错误', + 'route name not exists' => '路由标识不存在(或参数不够)', + 'invalid request' => '非法请求', + 'bind attr has exists' => '模型的属性已经存在', + 'relation data not exists' => '关联数据不存在', + 'relation not support' => '关联不支持', + 'chunk not support order' => 'Chunk不支持调用order方法', + 'route pattern error' => '路由变量规则定义错误', + 'route behavior will not support' => '路由行为废弃(使用中间件替代)', + 'closure not support cache(true)' => '使用闭包查询不支持cache(true),请指定缓存Key', + + // 上传错误信息 + 'unknown upload error' => '未知上传错误!', + 'file write error' => '文件写入失败!', + 'upload temp dir not found' => '找不到临时文件夹!', + 'no file to uploaded' => '没有文件被上传!', + 'only the portion of file is uploaded' => '文件只有部分被上传!', + 'upload File size exceeds the maximum value' => '上传文件大小超过了最大值!', + 'upload write error' => '文件上传保存错误!', + 'has the same filename: {:filename}' => '存在同名文件:{:filename}', + 'upload illegal files' => '非法上传文件', + 'illegal image files' => '非法图片文件', + 'extensions to upload is not allowed' => '上传文件后缀不允许', + 'mimetype to upload is not allowed' => '上传文件MIME类型不允许!', + 'filesize not match' => '上传文件大小不符!', + 'directory {:path} creation failed' => '目录 {:path} 创建失败!', + + 'The middleware must return Response instance' => '中间件方法必须返回Response对象实例', + 'The queue was exhausted, with no response returned' => '中间件队列为空', + // Validate Error Message + ':attribute require' => ':attribute不能为空', + ':attribute must' => ':attribute必须', + ':attribute must be numeric' => ':attribute必须是数字', + ':attribute must be integer' => ':attribute必须是整数', + ':attribute must be float' => ':attribute必须是浮点数', + ':attribute must be bool' => ':attribute必须是布尔值', + ':attribute not a valid email address' => ':attribute格式不符', + ':attribute not a valid mobile' => ':attribute格式不符', + ':attribute must be a array' => ':attribute必须是数组', + ':attribute must be yes,on or 1' => ':attribute必须是yes、on或者1', + ':attribute not a valid datetime' => ':attribute不是一个有效的日期或时间格式', + ':attribute not a valid file' => ':attribute不是有效的上传文件', + ':attribute not a valid image' => ':attribute不是有效的图像文件', + ':attribute must be alpha' => ':attribute只能是字母', + ':attribute must be alpha-numeric' => ':attribute只能是字母和数字', + ':attribute must be alpha-numeric, dash, underscore' => ':attribute只能是字母、数字和下划线_及破折号-', + ':attribute not a valid domain or ip' => ':attribute不是有效的域名或者IP', + ':attribute must be chinese' => ':attribute只能是汉字', + ':attribute must be chinese or alpha' => ':attribute只能是汉字、字母', + ':attribute must be chinese,alpha-numeric' => ':attribute只能是汉字、字母和数字', + ':attribute must be chinese,alpha-numeric,underscore, dash' => ':attribute只能是汉字、字母、数字和下划线_及破折号-', + ':attribute not a valid url' => ':attribute不是有效的URL地址', + ':attribute not a valid ip' => ':attribute不是有效的IP地址', + ':attribute must be dateFormat of :rule' => ':attribute必须使用日期格式 :rule', + ':attribute must be in :rule' => ':attribute必须在 :rule 范围内', + ':attribute be notin :rule' => ':attribute不能在 :rule 范围内', + ':attribute must between :1 - :2' => ':attribute只能在 :1 - :2 之间', + ':attribute not between :1 - :2' => ':attribute不能在 :1 - :2 之间', + 'size of :attribute must be :rule' => ':attribute长度不符合要求 :rule', + 'max size of :attribute must be :rule' => ':attribute长度不能超过 :rule', + 'min size of :attribute must be :rule' => ':attribute长度不能小于 :rule', + ':attribute cannot be less than :rule' => ':attribute日期不能小于 :rule', + ':attribute cannot exceed :rule' => ':attribute日期不能超过 :rule', + ':attribute not within :rule' => '不在有效期内 :rule', + 'access IP is not allowed' => '不允许的IP访问', + 'access IP denied' => '禁止的IP访问', + ':attribute out of accord with :2' => ':attribute和确认字段:2不一致', + ':attribute cannot be same with :2' => ':attribute和比较字段:2不能相同', + ':attribute must greater than or equal :rule' => ':attribute必须大于等于 :rule', + ':attribute must greater than :rule' => ':attribute必须大于 :rule', + ':attribute must less than or equal :rule' => ':attribute必须小于等于 :rule', + ':attribute must less than :rule' => ':attribute必须小于 :rule', + ':attribute must equal :rule' => ':attribute必须等于 :rule', + ':attribute has exists' => ':attribute已存在', + ':attribute not conform to the rules' => ':attribute不符合指定规则', + 'invalid Request method' => '无效的请求类型', + 'invalid token' => '令牌数据无效', + 'not conform to the rules' => '规则错误', ]; diff --git a/library/think/App.php b/library/think/App.php index 7e140ca96c0081ee49b7b464b43ab3dc3d5f7703..145036652dd7130458b3431753dbed817f349d48 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,562 +11,950 @@ namespace think; -use think\Config; -use think\Env; -use think\Exception; -use think\exception\HttpException; +use think\exception\ClassNotFoundException; use think\exception\HttpResponseException; -use think\Hook; -use think\Lang; -use think\Loader; -use think\Log; -use think\Request; -use think\Response; -use think\Route; +use think\route\Dispatch; /** * App 应用管理 - * @author liu21st */ -class App +class App extends Container { + const VERSION = '5.1.16'; + + /** + * 当前模块路径 + * @var string + */ + protected $modulePath; + + /** + * 应用调试模式 + * @var bool + */ + protected $appDebug = true; + + /** + * 应用开始时间 + * @var float + */ + protected $beginTime; + /** - * @var bool 是否初始化过 + * 应用内存初始占用 + * @var integer */ - protected static $init = false; + protected $beginMem; /** - * @var string 当前模块路径 + * 应用类库命名空间 + * @var string */ - public static $modulePath; + protected $namespace = 'app'; /** - * @var bool 应用调试模式 + * 应用类库后缀 + * @var bool */ - public static $debug = true; + protected $suffix = false; /** - * @var string 应用类库命名空间 + * 严格路由检测 + * @var bool */ - public static $namespace = 'app'; + protected $routeMust; /** - * @var bool 应用类库后缀 + * 应用类库目录 + * @var string */ - public static $suffix = false; + protected $appPath; /** - * @var bool 应用路由检测 + * 框架目录 + * @var string */ - protected static $routeCheck; + protected $thinkPath; /** - * @var bool 严格路由检测 + * 应用根目录 + * @var string */ - protected static $routeMust; + protected $rootPath; - protected static $dispatch; - protected static $file = []; + /** + * 运行时目录 + * @var string + */ + protected $runtimePath; + + /** + * 配置目录 + * @var string + */ + protected $configPath; + + /** + * 路由目录 + * @var string + */ + protected $routePath; + + /** + * 配置后缀 + * @var string + */ + protected $configExt; + + /** + * 应用调度实例 + * @var Dispatch + */ + protected $dispatch; + + /** + * 绑定模块(控制器) + * @var string + */ + protected $bindModule; + + /** + * 初始化 + * @var bool + */ + protected $initialized = false; + + public function __construct($appPath = '') + { + $this->appPath = $appPath ? realpath($appPath) . DIRECTORY_SEPARATOR : $this->getAppPath(); + + $this->thinkPath = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR; + $this->rootPath = dirname($this->appPath) . DIRECTORY_SEPARATOR; + $this->runtimePath = $this->rootPath . 'runtime' . DIRECTORY_SEPARATOR; + $this->routePath = $this->rootPath . 'route' . DIRECTORY_SEPARATOR; + $this->configPath = $this->rootPath . 'config' . DIRECTORY_SEPARATOR; + } + + /** + * 绑定模块或者控制器 + * @access public + * @param string $bind + * @return $this + */ + public function bind($bind) + { + $this->bindModule = $bind; + return $this; + } + + /** + * 设置应用类库目录 + * @access public + * @param string $path 路径 + * @return $this + */ + public function path($path) + { + $this->appPath = $path; + return $this; + } + + /** + * 初始化应用 + * @access public + * @return void + */ + public function initialize() + { + if ($this->initialized) { + return; + } + + $this->initialized = true; + $this->beginTime = microtime(true); + $this->beginMem = memory_get_usage(); + + static::setInstance($this); + + $this->instance('app', $this); + + // 加载惯例配置文件 + $this->config->set(include $this->thinkPath . 'convention.php'); + + // 设置路径环境变量 + $this->env->set([ + 'think_path' => $this->thinkPath, + 'root_path' => $this->rootPath, + 'app_path' => $this->appPath, + 'config_path' => $this->configPath, + 'route_path' => $this->routePath, + 'runtime_path' => $this->runtimePath, + 'extend_path' => $this->rootPath . 'extend' . DIRECTORY_SEPARATOR, + 'vendor_path' => $this->rootPath . 'vendor' . DIRECTORY_SEPARATOR, + ]); + + // 加载环境变量配置文件 + if (is_file($this->rootPath . '.env')) { + $this->env->load($this->rootPath . '.env'); + } + + $this->namespace = $this->env->get('app_namespace', $this->namespace); + $this->env->set('app_namespace', $this->namespace); + + // 注册应用命名空间 + Loader::addNamespace($this->namespace, $this->appPath); + + $this->configExt = $this->env->get('config_ext', '.php'); + + // 初始化应用 + $this->init(); + + // 开启类名后缀 + $this->suffix = $this->config('app.class_suffix'); + + // 应用调试模式 + $this->appDebug = $this->env->get('app_debug', $this->config('app.app_debug')); + $this->env->set('app_debug', $this->appDebug); + + if (!$this->appDebug) { + ini_set('display_errors', 'Off'); + } elseif (PHP_SAPI != 'cli') { + //重新申请一块比较大的buffer + if (ob_get_level() > 0) { + $output = ob_get_clean(); + } + ob_start(); + if (!empty($output)) { + echo $output; + } + } + + // 注册异常处理类 + if ($this->config('app.exception_handle')) { + Error::setExceptionHandler($this->config('app.exception_handle')); + } + + // 注册根命名空间 + if (!empty($this->config('app.root_namespace'))) { + Loader::addNamespace($this->config('app.root_namespace')); + } + + // 加载composer autofile文件 + Loader::loadComposerAutoloadFiles(); + + // 注册类库别名 + Loader::addClassAlias($this->config->pull('alias')); + + // 数据库配置初始化 + Db::init($this->config->pull('database')); + + // 设置系统时区 + date_default_timezone_set($this->config('app.default_timezone')); + + // 读取语言包 + $this->loadLangPack(); + + // 监听app_init + $this->hook->listen('app_init'); + } + + /** + * 初始化应用或模块 + * @access public + * @param string $module 模块名 + * @return void + */ + public function init($module = '') + { + // 定位模块目录 + $module = $module ? $module . DIRECTORY_SEPARATOR : ''; + $path = $this->appPath . $module; + + // 加载初始化文件 + if (is_file($path . 'init.php')) { + include $path . 'init.php'; + } elseif (is_file($this->runtimePath . $module . 'init.php')) { + include $this->runtimePath . $module . 'init.php'; + } else { + // 加载行为扩展文件 + if (is_file($path . 'tags.php')) { + $tags = include $path . 'tags.php'; + if (is_array($tags)) { + $this->hook->import($tags); + } + } + + // 加载公共文件 + if (is_file($path . 'common.php')) { + include $path . 'common.php'; + } + + if ('' == $module) { + // 加载系统助手函数 + include $this->thinkPath . 'helper.php'; + } + + // 加载中间件 + if (is_file($path . 'middleware.php')) { + $middleware = include $path . 'middleware.php'; + if (is_array($middleware)) { + $this->middleware->import($middleware); + } + } + + // 注册服务的容器对象实例 + if (is_file($path . 'provider.php')) { + $provider = include $path . 'provider.php'; + if (is_array($provider)) { + $this->bindTo($provider); + } + } + + // 自动读取配置文件 + if (is_dir($path . 'config')) { + $dir = $path . 'config'; + } elseif (is_dir($this->configPath . $module)) { + $dir = $this->configPath . $module; + } + + $files = isset($dir) ? scandir($dir) : []; + + foreach ($files as $file) { + if ('.' . pathinfo($file, PATHINFO_EXTENSION) === $this->configExt) { + $filename = $dir . DIRECTORY_SEPARATOR . $file; + $this->config->load($filename, pathinfo($file, PATHINFO_FILENAME)); + } + } + } + + $this->setModulePath($path); + + if ($module) { + // 对容器中的对象实例进行配置更新 + $this->containerConfigUpdate($module); + } + } + + protected function containerConfigUpdate($module) + { + $config = $this->config->get(); + + // 注册异常处理类 + if ($config['app']['exception_handle']) { + Error::setExceptionHandler($config['app']['exception_handle']); + } + + Db::init($config['database']); + $this->middleware->setConfig($config['middleware']); + $this->route->setConfig($config['app']); + $this->request->init($config['app']); + $this->cookie->init($config['cookie']); + $this->view->init($config['template']); + $this->log->init($config['log']); + $this->session->setConfig($config['session']); + $this->debug->setConfig($config['trace']); + $this->cache->init($config['cache'], true); + + // 加载当前模块语言包 + $this->lang->load($this->appPath . $module . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . $this->request->langset() . '.php'); + + // 模块请求缓存检查 + $this->checkRequestCache( + $config['app']['request_cache'], + $config['app']['request_cache_expire'], + $config['app']['request_cache_except'] + ); + } /** * 执行应用程序 * @access public - * @param Request $request Request对象 * @return Response * @throws Exception */ - public static function run(Request $request = null) + public function run() { - is_null($request) && $request = Request::instance(); - try { - $config = self::initCommon(); - if (defined('BIND_MODULE')) { + // 初始化应用 + $this->initialize(); + + if ($this->bindModule) { // 模块/控制器绑定 - BIND_MODULE && Route::bind(BIND_MODULE); - } elseif ($config['auto_bind_module']) { + $this->route->bind($this->bindModule); + } elseif ($this->config('app.auto_bind_module')) { // 入口自动绑定 - $name = pathinfo($request->baseFile(), PATHINFO_FILENAME); - if ($name && 'index' != $name && is_dir(APP_PATH . $name)) { - Route::bind($name); + $name = pathinfo($this->request->baseFile(), PATHINFO_FILENAME); + if ($name && 'index' != $name && is_dir($this->appPath . $name)) { + $this->route->bind($name); } } - $request->filter($config['default_filter']); + // 监听app_dispatch + $this->hook->listen('app_dispatch'); + + $dispatch = $this->dispatch; - if ($config['lang_switch_on']) { - // 开启多语言机制 检测当前语言 - Lang::detect(); - } else { - // 读取默认语言 - Lang::range($config['default_lang']); - } - $request->langset(Lang::range()); - // 加载系统语言包 - Lang::load([ - THINK_PATH . 'lang' . DS . $request->langset() . EXT, - APP_PATH . 'lang' . DS . $request->langset() . EXT, - ]); - - // 获取应用调度信息 - $dispatch = self::$dispatch; if (empty($dispatch)) { - // 进行URL路由检测 - $dispatch = self::routeCheck($request, $config); + // 路由检测 + $dispatch = $this->routeCheck()->init(); } + // 记录当前调度信息 - $request->dispatch($dispatch); + $this->request->dispatch($dispatch); // 记录路由和请求信息 - if (self::$debug) { - Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info'); - Log::record('[ HEADER ] ' . var_export($request->header(), true), 'info'); - Log::record('[ PARAM ] ' . var_export($request->param(), true), 'info'); + if ($this->appDebug) { + $this->log('[ ROUTE ] ' . var_export($this->request->routeInfo(), true)); + $this->log('[ HEADER ] ' . var_export($this->request->header(), true)); + $this->log('[ PARAM ] ' . var_export($this->request->param(), true)); } // 监听app_begin - Hook::listen('app_begin', $dispatch); - - switch ($dispatch['type']) { - case 'redirect': - // 执行重定向跳转 - $data = Response::create($dispatch['url'], 'redirect')->code($dispatch['status']); - break; - case 'module': - // 模块/控制器/操作 - $data = self::module($dispatch['module'], $config, isset($dispatch['convert']) ? $dispatch['convert'] : null); - break; - case 'controller': - // 执行控制器操作 - $data = Loader::action($dispatch['controller']); - break; - case 'method': - // 执行回调方法 - $data = self::invokeMethod($dispatch['method']); - break; - case 'function': - // 执行闭包 - $data = self::invokeFunction($dispatch['function']); - break; - case 'response': - $data = $dispatch['response']; - break; - default: - throw new \InvalidArgumentException('dispatch type not support'); - } + $this->hook->listen('app_begin'); + + // 请求缓存检查 + $this->checkRequestCache( + $this->config('request_cache'), + $this->config('request_cache_expire'), + $this->config('request_cache_except') + ); + + $data = null; } catch (HttpResponseException $exception) { - $data = $exception->getResponse(); + $dispatch = null; + $data = $exception->getResponse(); } - // 清空类的实例化 - Loader::clearInstance(); - - // 输出数据到客户端 - if ($data instanceof Response) { - $response = $data; - } elseif (!is_null($data)) { - // 默认自动识别响应输出类型 - $isAjax = $request->isAjax(); - $type = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type'); - $response = Response::create($data, $type); - } else { - $response = Response::create(); - } + $this->middleware->add(function (Request $request, $next) use ($dispatch, $data) { + return is_null($data) ? $dispatch->run() : $data; + }); + + $response = $this->middleware->dispatch($this->request); // 监听app_end - Hook::listen('app_end', $response); + $this->hook->listen('app_end', $response); return $response; } + protected function getRouteCacheKey() + { + if ($this->config->get('route_check_cache_key')) { + $closure = $this->config->get('route_check_cache_key'); + $routeKey = $closure($this->request); + } else { + $routeKey = md5($this->request->baseUrl(true) . ':' . $this->request->method()); + } + + return $routeKey; + } + + protected function loadLangPack() + { + // 读取默认语言 + $this->lang->range($this->config('app.default_lang')); + + if ($this->config('app.lang_switch_on')) { + // 开启多语言机制 检测当前语言 + $this->lang->detect(); + } + + $this->request->setLangset($this->lang->range()); + + // 加载系统语言包 + $this->lang->load([ + $this->thinkPath . 'lang' . DIRECTORY_SEPARATOR . $this->request->langset() . '.php', + $this->appPath . 'lang' . DIRECTORY_SEPARATOR . $this->request->langset() . '.php', + ]); + } + /** - * 设置当前请求的调度信息 + * 设置当前地址的请求缓存 * @access public - * @param array|string $dispatch 调度信息 - * @param string $type 调度类型 + * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id + * @param mixed $expire 缓存有效期 + * @param array $except 缓存排除 + * @param string $tag 缓存标签 * @return void */ - public static function dispatch($dispatch, $type = 'module') + public function checkRequestCache($key, $expire = null, $except = [], $tag = null) { - self::$dispatch = ['type' => $type, $type => $dispatch]; + $cache = $this->request->cache($key, $expire, $except, $tag); + + if ($cache) { + list($key, $expire, $tag) = $cache; + if (strtotime($this->request->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $this->request->server('REQUEST_TIME')) { + // 读取缓存 + $response = Response::create()->code(304); + throw new HttpResponseException($response); + } elseif ($this->cache->has($key)) { + list($content, $header) = $this->cache->get($key); + + $response = Response::create($content)->header($header); + throw new HttpResponseException($response); + } + } } /** - * 执行函数或者闭包方法 支持参数调用 + * 设置当前请求的调度信息 * @access public - * @param string|array|\Closure $function 函数或者闭包 - * @param array $vars 变量 - * @return mixed + * @param Dispatch $dispatch 调度信息 + * @return $this */ - public static function invokeFunction($function, $vars = []) + public function dispatch(Dispatch $dispatch) { - $reflect = new \ReflectionFunction($function); - $args = self::bindParams($reflect, $vars); - // 记录执行信息 - self::$debug && Log::record('[ RUN ] ' . $reflect->__toString(), 'info'); - return $reflect->invokeArgs($args); + $this->dispatch = $dispatch; + return $this; } /** - * 调用反射执行类的方法 支持参数绑定 + * 记录调试信息 * @access public - * @param string|array $method 方法 - * @param array $vars 变量 - * @return mixed + * @param mixed $msg 调试信息 + * @param string $type 信息类型 + * @return void */ - public static function invokeMethod($method, $vars = []) + public function log($msg, $type = 'info') { - if (is_array($method)) { - $class = is_object($method[0]) ? $method[0] : new $method[0](Request::instance()); - $reflect = new \ReflectionMethod($class, $method[1]); - } else { - // 静态方法 - $reflect = new \ReflectionMethod($method); - } - $args = self::bindParams($reflect, $vars); - - self::$debug && Log::record('[ RUN ] ' . $reflect->__toString(), 'info'); - return $reflect->invokeArgs(isset($class) ? $class : null, $args); + $this->appDebug && $this->log->record($msg, $type); } /** - * 调用反射执行类的实例化 支持依赖注入 + * 获取配置参数 为空则获取所有配置 * @access public - * @param string $class 类名 - * @param array $vars 变量 + * @param string $name 配置参数名(支持二级配置 .号分割) * @return mixed */ - public static function invokeClass($class, $vars = []) + public function config($name = '') { - $reflect = new \ReflectionClass($class); - $constructor = $reflect->getConstructor(); - if ($constructor) { - $args = self::bindParams($constructor, $vars); - } else { - $args = []; + return $this->config->get($name); + } + + /** + * URL路由检测(根据PATH_INFO) + * @access public + * @return Dispatch + */ + public function routeCheck() + { + // 检测路由缓存 + if (!$this->appDebug && $this->config->get('route_check_cache')) { + $routeKey = $this->getRouteCacheKey(); + $option = $this->config->get('route_cache_option') ?: $this->cache->getConfig(); + + if ($this->cache->connect($option)->has($routeKey)) { + return $this->cache->connect($option)->get($routeKey); + } + } + + // 获取应用调度信息 + $path = $this->request->path(); + + // 路由检测 + $files = scandir($this->routePath); + foreach ($files as $file) { + if (strpos($file, '.php')) { + $filename = $this->routePath . $file; + // 导入路由配置 + $rules = include $filename; + if (is_array($rules)) { + $this->route->import($rules); + } + } } - self::$debug && Log::record('[ RUN ] ' . $reflect->__toString(), 'info'); - return $reflect->newInstanceArgs($args); + if ($this->config('route.route_annotation')) { + // 自动生成路由定义 + if ($this->appDebug) { + $this->build->buildRoute($this->config('route.controller_suffix')); + } + + $filename = $this->runtimePath . 'build_route.php'; + + if (is_file($filename)) { + include $filename; + } + } + + // 是否强制路由模式 + $must = !is_null($this->routeMust) ? $this->routeMust : $this->route->config('url_route_must'); + + // 路由检测 返回一个Dispatch对象 + $dispatch = $this->route->check($path, $must); + + if (!empty($routeKey)) { + try { + $this->cache + ->connect($option) + ->tag('route_cache') + ->set($routeKey, $dispatch); + } catch (\Exception $e) { + // 存在闭包的时候缓存无效 + } + } + + return $dispatch; } /** - * 绑定参数 + * 设置应用的路由检测机制 * @access public - * @param \ReflectionMethod|\ReflectionFunction $reflect 反射类 - * @param array $vars 变量 + * @param bool $must 是否强制检测路由 + * @return $this + */ + public function routeMust($must = false) + { + $this->routeMust = $must; + return $this; + } + + /** + * 解析模块和类名 + * @access protected + * @param string $name 资源地址 + * @param string $layer 验证层名称 + * @param bool $appendSuffix 是否添加类名后缀 * @return array */ - private static function bindParams($reflect, $vars = []) + protected function parseModuleAndClass($name, $layer, $appendSuffix) { - if (empty($vars)) { - // 自动获取请求变量 - if (Config::get('url_param_type')) { - $vars = Request::instance()->route(); + if (false !== strpos($name, '\\')) { + $class = $name; + $module = $this->request->module(); + } else { + if (strpos($name, '/')) { + list($module, $name) = explode('/', $name, 2); } else { - $vars = Request::instance()->param(); - } - } - $args = []; - // 判断数组类型 数字数组时按顺序绑定参数 - reset($vars); - $type = key($vars) === 0 ? 1 : 0; - if ($reflect->getNumberOfParameters() > 0) { - $params = $reflect->getParameters(); - foreach ($params as $param) { - $name = $param->getName(); - $class = $param->getClass(); - if ($class) { - $className = $class->getName(); - $bind = Request::instance()->$name; - if ($bind instanceof $className) { - $args[] = $bind; - } else { - $args[] = method_exists($className, 'instance') ? $className::instance() : new $className(); - } - } elseif (1 == $type && !empty($vars)) { - $args[] = array_shift($vars); - } elseif (0 == $type && isset($vars[$name])) { - $args[] = $vars[$name]; - } elseif ($param->isDefaultValueAvailable()) { - $args[] = $param->getDefaultValue(); - } else { - throw new \InvalidArgumentException('method param miss:' . $name); - } + $module = $this->request->module(); } - // 全局过滤 - array_walk_recursive($args, [Request::instance(), 'filterExp']); + + $class = $this->parseClass($module, $layer, $name, $appendSuffix); } - return $args; + + return [$module, $class]; } /** - * 执行模块 + * 实例化应用类库 * @access public - * @param array $result 模块/控制器/操作 - * @param array $config 配置参数 - * @param bool $convert 是否自动转换控制器和操作名 - * @return mixed + * @param string $name 类名称 + * @param string $layer 业务层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @param string $common 公共模块名 + * @return object + * @throws ClassNotFoundException */ - public static function module($result, $config, $convert = null) + public function create($name, $layer, $appendSuffix = false, $common = 'common') { - if (is_string($result)) { - $result = explode('/', $result); + $guid = $name . $layer; + + if ($this->__isset($guid)) { + return $this->__get($guid); } - $request = Request::instance(); - if ($config['app_multi_module']) { - // 多模块部署 - $module = strip_tags(strtolower($result[0] ?: $config['default_module'])); - $bind = Route::getBind('module'); - $available = false; - if ($bind) { - // 绑定模块 - list($bindModule) = explode('/', $bind); - if (empty($result[0])) { - $module = $bindModule; - $available = true; - } elseif ($module == $bindModule) { - $available = true; - } - } elseif (!in_array($module, $config['deny_module_list']) && is_dir(APP_PATH . $module)) { - $available = true; - } - // 模块初始化 - if ($module && $available) { - // 初始化模块 - $request->module($module); - $config = self::init($module); + list($module, $class) = $this->parseModuleAndClass($name, $layer, $appendSuffix); + + if (class_exists($class)) { + $object = $this->__get($class); + } else { + $class = str_replace('\\' . $module . '\\', '\\' . $common . '\\', $class); + if (class_exists($class)) { + $object = $this->__get($class); } else { - throw new HttpException(404, 'module not exists:' . $module); + throw new ClassNotFoundException('class not exists:' . $class, $class); } - } else { - // 单一模块部署 - $module = ''; - $request->module($module); } - // 当前模块路径 - App::$modulePath = APP_PATH . ($module ? $module . DS : ''); - // 是否自动转换控制器和操作名 - $convert = is_bool($convert) ? $convert : $config['url_convert']; - // 获取控制器名 - $controller = strip_tags($result[1] ?: $config['default_controller']); - $controller = $convert ? strtolower($controller) : $controller; + $this->__set($guid, $class); - // 获取操作名 - $actionName = strip_tags($result[2] ?: $config['default_action']); - $actionName = $convert ? strtolower($actionName) : $actionName; + return $object; + } - // 设置当前请求的控制器、操作 - $request->controller(Loader::parseName($controller, 1))->action($actionName); + /** + * 实例化(分层)模型 + * @access public + * @param string $name Model名称 + * @param string $layer 业务层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @param string $common 公共模块名 + * @return Model + * @throws ClassNotFoundException + */ + public function model($name = '', $layer = 'model', $appendSuffix = false, $common = 'common') + { + return $this->create($name, $layer, $appendSuffix, $common); + } - // 监听module_init - Hook::listen('module_init', $request); + /** + * 实例化(分层)控制器 格式:[模块名/]控制器名 + * @access public + * @param string $name 资源地址 + * @param string $layer 控制层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @param string $empty 空控制器名称 + * @return object + * @throws ClassNotFoundException + */ + public function controller($name, $layer = 'controller', $appendSuffix = false, $empty = '') + { + list($module, $class) = $this->parseModuleAndClass($name, $layer, $appendSuffix); - try { - $instance = Loader::controller($controller, $config['url_controller_layer'], $config['controller_suffix'], $config['empty_controller']); - if (is_null($instance)) { - throw new HttpException(404, 'controller not exists:' . Loader::parseName($controller, 1)); - } - // 获取当前操作名 - $action = $actionName . $config['action_suffix']; - if (!preg_match('/^[A-Za-z](\w)*$/', $action)) { - // 非法操作 - throw new \ReflectionException('illegal action name:' . $actionName); - } + if (class_exists($class)) { + return $this->__get($class); + } elseif ($empty && class_exists($emptyClass = $this->parseClass($module, $layer, $empty, $appendSuffix))) { + return $this->__get($emptyClass); + } + + throw new ClassNotFoundException('class not exists:' . $class, $class); + } + + /** + * 实例化验证类 格式:[模块名/]验证器名 + * @access public + * @param string $name 资源地址 + * @param string $layer 验证层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @param string $common 公共模块名 + * @return Validate + * @throws ClassNotFoundException + */ + public function validate($name = '', $layer = 'validate', $appendSuffix = false, $common = 'common') + { + $name = $name ?: $this->config('default_validate'); + + if (empty($name)) { + return new Validate; + } + + return $this->create($name, $layer, $appendSuffix, $common); + } - // 执行操作方法 - $call = [$instance, $action]; - Hook::listen('action_begin', $call); - - $data = self::invokeMethod($call); - } catch (\ReflectionException $e) { - // 操作不存在 - if (method_exists($instance, '_empty')) { - $reflect = new \ReflectionMethod($instance, '_empty'); - $data = $reflect->invokeArgs($instance, [$action]); - self::$debug && Log::record('[ RUN ] ' . $reflect->__toString(), 'info'); + /** + * 数据库初始化 + * @access public + * @param mixed $config 数据库配置 + * @param bool|string $name 连接标识 true 强制重新连接 + * @return \think\db\Query + */ + public function db($config = [], $name = false) + { + return Db::connect($config, $name); + } + + /** + * 远程调用模块的操作方法 参数格式 [模块/控制器/]操作 + * @access public + * @param string $url 调用地址 + * @param string|array $vars 调用参数 支持字符串和数组 + * @param string $layer 要调用的控制层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @return mixed + * @throws ClassNotFoundException + */ + public function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) + { + $info = pathinfo($url); + $action = $info['basename']; + $module = '.' != $info['dirname'] ? $info['dirname'] : $this->request->controller(); + $class = $this->controller($module, $layer, $appendSuffix); + + if (is_scalar($vars)) { + if (strpos($vars, '=')) { + parse_str($vars, $vars); } else { - throw new HttpException(404, 'method not exists:' . (new \ReflectionClass($instance))->getName() . '->' . $action); + $vars = [$vars]; } } - return $data; + + return $this->invokeMethod([$class, $action . $this->config('action_suffix')], $vars); } /** - * 初始化应用 + * 解析应用类的类名 + * @access public + * @param string $module 模块名 + * @param string $layer 层名 controller model ... + * @param string $name 类名 + * @param bool $appendSuffix + * @return string */ - public static function initCommon() + public function parseClass($module, $layer, $name, $appendSuffix = false) { - if (empty(self::$init)) { - // 初始化应用 - $config = self::init(); - self::$suffix = $config['class_suffix']; - - // 应用调试模式 - self::$debug = Env::get('app_debug', Config::get('app_debug')); - if (!self::$debug) { - ini_set('display_errors', 'Off'); - } elseif (!IS_CLI) { - //重新申请一块比较大的buffer - if (ob_get_level() > 0) { - $output = ob_get_clean(); - } - ob_start(); - if (!empty($output)) { - echo $output; - } - } + $name = str_replace(['/', '.'], '\\', $name); + $array = explode('\\', $name); + $class = Loader::parseName(array_pop($array), 1) . ($this->suffix || $appendSuffix ? ucfirst($layer) : ''); + $path = $array ? implode('\\', $array) . '\\' : ''; - // 注册应用命名空间 - self::$namespace = $config['app_namespace']; - Loader::addNamespace($config['app_namespace'], APP_PATH); - if (!empty($config['root_namespace'])) { - Loader::addNamespace($config['root_namespace']); - } + return $this->namespace . '\\' . ($module ? $module . '\\' : '') . $layer . '\\' . $path . $class; + } - // 加载额外文件 - if (!empty($config['extra_file_list'])) { - foreach ($config['extra_file_list'] as $file) { - $file = strpos($file, '.') ? $file : APP_PATH . $file . EXT; - if (is_file($file) && !isset(self::$file[$file])) { - include $file; - self::$file[$file] = true; - } - } - } + /** + * 获取框架版本 + * @access public + * @return string + */ + public function version() + { + return static::VERSION; + } + + /** + * 是否为调试模式 + * @access public + * @return bool + */ + public function isDebug() + { + return $this->appDebug; + } - // 设置系统时区 - date_default_timezone_set($config['default_timezone']); + /** + * 获取模块路径 + * @access public + * @return string + */ + public function getModulePath() + { + return $this->modulePath; + } + + /** + * 设置模块路径 + * @access public + * @param string $path 路径 + * @return void + */ + public function setModulePath($path) + { + $this->modulePath = $path; + $this->env->set('module_path', $path); + } - // 监听app_init - Hook::listen('app_init'); + /** + * 获取应用根目录 + * @access public + * @return string + */ + public function getRootPath() + { + return $this->rootPath; + } - self::$init = $config; + /** + * 获取应用类库目录 + * @access public + * @return string + */ + public function getAppPath() + { + if (is_null($this->appPath)) { + $this->appPath = Loader::getRootPath() . 'application' . DIRECTORY_SEPARATOR; } - return self::$init; + + return $this->appPath; } /** - * 初始化应用或模块 + * 获取应用运行时目录 * @access public - * @param string $module 模块名 - * @return array + * @return string */ - private static function init($module = '') + public function getRuntimePath() { - // 定位模块目录 - $module = $module ? $module . DS : ''; + return $this->runtimePath; + } - // 加载初始化文件 - if (is_file(APP_PATH . $module . 'init' . EXT)) { - include APP_PATH . $module . 'init' . EXT; - } elseif (is_file(RUNTIME_PATH . $module . 'init' . EXT)) { - include RUNTIME_PATH . $module . 'init' . EXT; - } else { - $path = APP_PATH . $module; - // 加载模块配置 - $config = Config::load(CONF_PATH . $module . 'config' . CONF_EXT); - // 读取数据库配置文件 - $filename = CONF_PATH . $module . 'database' . CONF_EXT; - Config::load($filename, 'database'); - // 读取扩展配置文件 - if (is_dir(CONF_PATH . $module . 'extra')) { - $dir = CONF_PATH . $module . 'extra'; - $files = scandir($dir); - foreach ($files as $file) { - if (strpos($file, CONF_EXT)) { - $filename = $dir . DS . $file; - Config::load($filename, pathinfo($file, PATHINFO_FILENAME)); - } - } - } + /** + * 获取核心框架目录 + * @access public + * @return string + */ + public function getThinkPath() + { + return $this->thinkPath; + } - // 加载应用状态配置 - if ($config['app_status']) { - $config = Config::load(CONF_PATH . $module . $config['app_status'] . CONF_EXT); - } + /** + * 获取路由目录 + * @access public + * @return string + */ + public function getRoutePath() + { + return $this->routePath; + } - // 加载行为扩展文件 - if (is_file(CONF_PATH . $module . 'tags' . EXT)) { - Hook::import(include CONF_PATH . $module . 'tags' . EXT); - } + /** + * 获取应用配置目录 + * @access public + * @return string + */ + public function getConfigPath() + { + return $this->configPath; + } - // 加载公共文件 - if (is_file($path . 'common' . EXT)) { - include $path . 'common' . EXT; - } + /** + * 获取配置后缀 + * @access public + * @return string + */ + public function getConfigExt() + { + return $this->configExt; + } - // 加载当前模块语言包 - if ($module) { - Lang::load($path . 'lang' . DS . Request::instance()->langset() . EXT); - } - } - return Config::get(); + /** + * 获取应用类库命名空间 + * @access public + * @return string + */ + public function getNamespace() + { + return $this->namespace; } /** - * URL路由检测(根据PATH_INFO) + * 设置应用类库命名空间 * @access public - * @param \think\Request $request - * @param array $config - * @return array - * @throws \think\Exception + * @param string $namespace 命名空间名称 + * @return $this */ - public static function routeCheck($request, array $config) + public function setNamespace($namespace) { - $path = $request->path(); - $depr = $config['pathinfo_depr']; - $result = false; - // 路由检测 - $check = !is_null(self::$routeCheck) ? self::$routeCheck : $config['url_route_on']; - if ($check) { - // 开启路由 - if (is_file(RUNTIME_PATH . 'route.php')) { - // 读取路由缓存 - $rules = include RUNTIME_PATH . 'route.php'; - if (is_array($rules)) { - Route::rules($rules); - } - } else { - $files = $config['route_config_file']; - foreach ($files as $file) { - if (is_file(CONF_PATH . $file . CONF_EXT)) { - // 导入路由配置 - $rules = include CONF_PATH . $file . CONF_EXT; - if (is_array($rules)) { - Route::import($rules); - } - } - } - } + $this->namespace = $namespace; + return $this; + } - // 路由检测(根据路由定义返回不同的URL调度) - $result = Route::check($request, $path, $depr, $config['url_domain_deploy']); - $must = !is_null(self::$routeMust) ? self::$routeMust : $config['url_route_must']; - if ($must && false === $result) { - // 路由无效 - throw new HttpException(404, 'Route Not Found'); - } - } - if (false === $result) { - // 路由无效 解析模块/控制器/操作/参数... 支持控制器自动搜索 - $result = Route::parseUrl($path, $depr, $config['controller_auto_search']); - } - return $result; + /** + * 是否启用类库后缀 + * @access public + * @return bool + */ + public function getSuffix() + { + return $this->suffix; } /** - * 设置应用的路由检测机制 + * 获取应用开启时间 * @access public - * @param bool $route 是否需要检测路由 - * @param bool $must 是否强制检测路由 - * @return void + * @return float */ - public static function route($route, $must = false) + public function getBeginTime() { - self::$routeCheck = $route; - self::$routeMust = $must; + return $this->beginTime; } + + /** + * 获取应用初始内存占用 + * @access public + * @return integer + */ + public function getBeginMem() + { + return $this->beginMem; + } + } diff --git a/library/think/Build.php b/library/think/Build.php index dd2bd550fac2f97a2bc52e43780724c1788e5dbf..0c3244da8bb41eaa01b75a7a1365580d843c812e 100644 --- a/library/think/Build.php +++ b/library/think/Build.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,35 +13,56 @@ namespace think; class Build { + /** + * 应用对象 + * @var App + */ + protected $app; + + /** + * 应用目录 + * @var string + */ + protected $basePath; + + public function __construct(App $app) + { + $this->app = $app; + $this->basePath = $this->app->getAppPath(); + } + /** * 根据传入的build资料创建目录和文件 - * @access protected + * @access public * @param array $build build列表 * @param string $namespace 应用类库命名空间 * @param bool $suffix 类库后缀 * @return void */ - public static function run(array $build = [], $namespace = 'app', $suffix = false) + public function run(array $build = [], $namespace = 'app', $suffix = false) { // 锁定 - $lockfile = APP_PATH . 'build.lock'; + $lockfile = $this->basePath . 'build.lock'; + if (is_writable($lockfile)) { return; } elseif (!touch($lockfile)) { - throw new Exception('应用目录[' . APP_PATH . ']不可写,目录无法自动生成!
请手动生成项目目录~', 10006); + throw new Exception('应用目录[' . $this->basePath . ']不可写,目录无法自动生成!
请手动生成项目目录~', 10006); } + foreach ($build as $module => $list) { if ('__dir__' == $module) { // 创建目录列表 - self::buildDir($list); + $this->buildDir($list); } elseif ('__file__' == $module) { // 创建文件列表 - self::buildFile($list); + $this->buildFile($list); } else { // 创建模块 - self::module($module, $list, $namespace, $suffix); + $this->module($module, $list, $namespace, $suffix); } } + // 解除锁定 unlink($lockfile); } @@ -52,13 +73,10 @@ class Build * @param array $list 目录列表 * @return void */ - protected static function buildDir($list) + protected function buildDir($list) { foreach ($list as $dir) { - if (!is_dir(APP_PATH . $dir)) { - // 创建目录 - mkdir(APP_PATH . $dir, 0755, true); - } + $this->checkDirBuild($this->basePath . $dir); } } @@ -68,15 +86,16 @@ class Build * @param array $list 文件列表 * @return void */ - protected static function buildFile($list) + protected function buildFile($list) { foreach ($list as $file) { - if (!is_dir(APP_PATH . dirname($file))) { + if (!is_dir($this->basePath . dirname($file))) { // 创建目录 - mkdir(APP_PATH . dirname($file), 0755, true); + mkdir($this->basePath . dirname($file), 0755, true); } - if (!is_file(APP_PATH . $file)) { - file_put_contents(APP_PATH . $file, 'php' == pathinfo($file, PATHINFO_EXTENSION) ? "basePath . $file)) { + file_put_contents($this->basePath . $file, 'php' == pathinfo($file, PATHINFO_EXTENSION) ? "basePath . $module)) { // 创建模块目录 - mkdir(APP_PATH . $module); + mkdir($this->basePath . $module); } - if (basename(RUNTIME_PATH) != $module) { + + if (basename($this->app->getRuntimePath()) != $module) { // 创建配置文件和公共文件 - self::buildCommon($module); + $this->buildCommon($module); // 创建模块的默认页面 - self::buildHello($module, $namespace, $suffix); + $this->buildHello($module, $namespace, $suffix); } + if (empty($list)) { // 创建默认的模块目录和文件 $list = [ - '__file__' => ['config.php', 'common.php'], - '__dir__' => ['controller', 'model', 'view'], + '__file__' => ['common.php'], + '__dir__' => ['controller', 'model', 'view', 'config'], ]; } + // 创建子目录和文件 foreach ($list as $path => $file) { - $modulePath = APP_PATH . $module . DS; + $modulePath = $this->basePath . $module . DIRECTORY_SEPARATOR; if ('__dir__' == $path) { // 生成子目录 foreach ($file as $dir) { - if (!is_dir($modulePath . $dir)) { - // 创建目录 - mkdir($modulePath . $dir, 0755, true); - } + $this->checkDirBuild($modulePath . $dir); } } elseif ('__file__' == $path) { // 生成(空白)文件 @@ -132,7 +152,7 @@ class Build // 生成相关MVC文件 foreach ($file as $val) { $val = trim($val); - $filename = $modulePath . $path . DS . $val . ($suffix ? ucfirst($path) : '') . EXT; + $filename = $modulePath . $path . DIRECTORY_SEPARATOR . $val . ($suffix ? ucfirst($path) : '') . '.php'; $space = $namespace . '\\' . ($module ? $module . '\\' : '') . $path; $class = $val . ($suffix ? ucfirst($path) : ''); switch ($path) { @@ -143,11 +163,8 @@ class Build $content = "checkDirBuild(dirname($filename)); $content = ''; break; default: @@ -164,41 +181,227 @@ class Build } /** - * 创建模块的欢迎页面 + * 根据注释自动生成路由规则 * @access public + * @param bool $suffix 类库后缀 + * @param string $layer 控制器层目录名 + * @return string + */ + public function buildRoute($suffix = false, $layer = '') + { + $namespace = $this->app->getNameSpace(); + $modules = glob($this->basePath . '*', GLOB_ONLYDIR); + $content = 'app->config('app.url_controller_layer'); + } + + foreach ($modules as $module) { + $module = basename($module); + + if (in_array($module, $this->app->config('app.deny_module_list'))) { + continue; + } + + $path = $this->basePath . $module . DIRECTORY_SEPARATOR . $layer . DIRECTORY_SEPARATOR; + $content .= $this->buildDirRoute($path, $namespace, $module, $suffix, $layer); + } + + $filename = $this->app->getRuntimePath() . 'build_route.php'; + file_put_contents($filename, $content); + + return $filename; + } + + /** + * 生成子目录控制器类的路由规则 + * @access protected + * @param string $path 控制器目录 + * @param string $namespace 应用命名空间 + * @param string $module 模块 + * @param bool $suffix 类库后缀 + * @param string $layer 控制器层目录名 + * @return string + */ + protected function buildDirRoute($path, $namespace, $module, $suffix, $layer) + { + $content = ''; + $controllers = glob($path . '*.php'); + + foreach ($controllers as $controller) { + $controller = basename($controller, '.php'); + + if ($suffix) { + // 控制器后缀 + $controller = substr($controller, 0, -10); + } + + $class = new \ReflectionClass($namespace . '\\' . $module . '\\' . $layer . '\\' . $controller); + + if (strpos($layer, '\\')) { + // 多级控制器 + $level = str_replace(DIRECTORY_SEPARATOR, '.', substr($layer, 11)); + $controller = $level . '.' . $controller; + } + + $content .= $this->getControllerRoute($class, $module, $controller); + } + + $subDir = glob($path . '*', GLOB_ONLYDIR); + + foreach ($subDir as $dir) { + $content .= $this->buildDirRoute($dir . DIRECTORY_SEPARATOR, $namespace, $module, $suffix, $layer . '\\' . basename($dir)); + } + + return $content; + } + + /** + * 生成控制器类的路由规则 + * @access protected + * @param string $class 控制器完整类名 + * @param string $module 模块名 + * @param string $controller 控制器名 + * @return string + */ + protected function getControllerRoute($class, $module, $controller) + { + $content = ''; + $comment = $class->getDocComment(); + + if (false !== strpos($comment, '@route(')) { + $comment = $this->parseRouteComment($comment); + $route = $module . '/' . $controller; + $comment = preg_replace('/route\(\s?([\'\"][\-\_\/\:\<\>\?\$\[\]\w]+[\'\"])\s?\)/is', 'Route::resourece(\1,\'' . $route . '\')', $comment); + $content .= PHP_EOL . $comment; + } elseif (false !== strpos($comment, '@alias(')) { + $comment = $this->parseRouteComment($comment, '@alias('); + $route = $module . '/' . $controller; + $comment = preg_replace('/alias\(\s?([\'\"][\-\_\/\w]+[\'\"])\s?\)/is', 'Route::alias(\1,\'' . $route . '\')', $comment); + $content .= PHP_EOL . $comment; + } + + $methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC); + + foreach ($methods as $method) { + $comment = $this->getMethodRouteComment($module, $controller, $method); + if ($comment) { + $content .= PHP_EOL . $comment; + } + } + + return $content; + } + + /** + * 解析路由注释 + * @access protected + * @param string $comment + * @param string $tag + * @return string + */ + protected function parseRouteComment($comment, $tag = '@route(') + { + $comment = substr($comment, 3, -2); + $comment = explode(PHP_EOL, substr(strstr(trim($comment), $tag), 1)); + $comment = array_map(function ($item) {return trim(trim($item), ' \t*');}, $comment); + + if (count($comment) > 1) { + $key = array_search('', $comment); + $comment = array_slice($comment, 0, false === $key ? 1 : $key); + } + + $comment = implode(PHP_EOL . "\t", $comment) . ';'; + + if (strpos($comment, '{')) { + $comment = preg_replace_callback('/\{\s?.*?\s?\}/s', function ($matches) { + return false !== strpos($matches[0], '"') ? '[' . substr(var_export(json_decode($matches[0], true), true), 7, -1) . ']' : $matches[0]; + }, $comment); + } + return $comment; + } + + /** + * 获取方法的路由注释 + * @access protected + * @param string $module 模块 + * @param string $controller 控制器名 + * @param \ReflectMethod $reflectMethod + * @return string|void + */ + protected function getMethodRouteComment($module, $controller, $reflectMethod) + { + $comment = $reflectMethod->getDocComment(); + + if (false !== strpos($comment, '@route(')) { + $comment = $this->parseRouteComment($comment); + $action = $reflectMethod->getName(); + + if ($suffix = $this->app->config('app.action_suffix')) { + $action = substr($action, 0, -strlen($suffix)); + } + + $route = $module . '/' . $controller . '/' . $action; + $comment = preg_replace('/route\s?\(\s?([\'\"][\-\_\/\:\<\>\?\$\[\]\w]+[\'\"])\s?\,?\s?[\'\"]?(\w+?)[\'\"]?\s?\)/is', 'Route::\2(\1,\'' . $route . '\')', $comment); + $comment = preg_replace('/route\s?\(\s?([\'\"][\-\_\/\:\<\>\?\$\[\]\w]+[\'\"])\s?\)/is', 'Route::rule(\1,\'' . $route . '\')', $comment); + + return $comment; + } + } + + /** + * 创建模块的欢迎页面 + * @access protected * @param string $module 模块名 * @param string $namespace 应用类库命名空间 * @param bool $suffix 类库后缀 * @return void */ - protected static function buildHello($module, $namespace, $suffix = false) + protected function buildHello($module, $namespace, $suffix = false) { - $filename = APP_PATH . ($module ? $module . DS : '') . 'controller' . DS . 'Index' . ($suffix ? 'Controller' : '') . EXT; + $filename = $this->basePath . ($module ? $module . DIRECTORY_SEPARATOR : '') . 'controller' . DIRECTORY_SEPARATOR . 'Index' . ($suffix ? 'Controller' : '') . '.php'; if (!is_file($filename)) { - $content = file_get_contents(THINK_PATH . 'tpl' . DS . 'default_index.tpl'); + $content = file_get_contents($this->app->getThinkPath() . 'tpl' . DIRECTORY_SEPARATOR . 'default_index.tpl'); $content = str_replace(['{$app}', '{$module}', '{layer}', '{$suffix}'], [$namespace, $module ? $module . '\\' : '', 'controller', $suffix ? 'Controller' : ''], $content); - if (!is_dir(dirname($filename))) { - mkdir(dirname($filename), 0755, true); - } + $this->checkDirBuild(dirname($filename)); + file_put_contents($filename, $content); } } /** * 创建模块的公共文件 - * @access public + * @access protected * @param string $module 模块名 * @return void */ - protected static function buildCommon($module) + protected function buildCommon($module) { - $filename = CONF_PATH . ($module ? $module . DS : '') . 'config.php'; + $filename = $this->app->getConfigPath() . ($module ? $module . DIRECTORY_SEPARATOR : '') . 'app.php'; + $this->checkDirBuild(dirname($filename)); + if (!is_file($filename)) { file_put_contents($filename, "basePath . ($module ? $module . DIRECTORY_SEPARATOR : '') . 'common.php'; + if (!is_file($filename)) { file_put_contents($filename, "config = $config; + $this->init($config); + } /** * 连接缓存 * @access public - * @param array $options 配置数组 - * @param bool|string $name 缓存连接标识 true 强制重新连接 - * @return \think\cache\Driver + * @param array $options 配置数组 + * @param bool|string $name 缓存连接标识 true 强制重新连接 + * @return Driver */ - public static function connect(array $options = [], $name = false) + public function connect(array $options = [], $name = false) { - $type = !empty($options['type']) ? $options['type'] : 'File'; if (false === $name) { $name = md5(serialize($options)); } - if (true === $name || !isset(self::$instance[$name])) { - $class = false !== strpos($type, '\\') ? $type : '\\think\\cache\\driver\\' . ucwords($type); + if (true === $name || !isset($this->instance[$name])) { + $type = !empty($options['type']) ? $options['type'] : 'File'; - // 记录初始化信息 - App::$debug && Log::record('[ CACHE ] INIT ' . $type, 'info'); if (true === $name) { - return new $class($options); - } else { - self::$instance[$name] = new $class($options); + $name = md5(serialize($options)); } + + $this->instance[$name] = Loader::factory($type, '\\think\\cache\\driver\\', $options); } - self::$handler = self::$instance[$name]; - return self::$handler; + + return $this->instance[$name]; } /** * 自动初始化缓存 * @access public - * @param array $options 配置数组 - * @return void + * @param array $options 配置数组 + * @param bool $force 强制更新 + * @return Driver */ - public static function init(array $options = []) + public function init(array $options = [], $force = false) { - if (is_null(self::$handler)) { - // 自动初始化缓存 - if (!empty($options)) { - self::connect($options); - } elseif ('complex' == Config::get('cache.type')) { - self::connect(Config::get('cache.default')); - } else { - self::connect(Config::get('cache')); + if (is_null($this->handler) || $force) { + + if ('complex' == $options['type']) { + $default = $options['default']; + $options = isset($options[$default['type']]) ? $options[$default['type']] : $default; } - } - } - /** - * 切换缓存类型 需要配置 cache.type 为 complex - * @access public - * @param string $name 缓存标识 - * @return \think\cache\Driver - */ - public static function store($name) - { - if ('complex' == Config::get('cache.type')) { - self::connect(Config::get('cache.' . $name), strtolower($name)); + $this->handler = $this->connect($options); } - return self::$handler; - } - - /** - * 判断缓存是否存在 - * @access public - * @param string $name 缓存变量名 - * @return bool - */ - public static function has($name) - { - self::init(); - self::$readTimes++; - return self::$handler->has($name); - } - /** - * 读取缓存 - * @access public - * @param string $name 缓存标识 - * @param mixed $default 默认值 - * @return mixed - */ - public static function get($name, $default = false) - { - self::init(); - self::$readTimes++; - return self::$handler->get($name, $default); + return $this->handler; } - /** - * 写入缓存 - * @access public - * @param string $name 缓存标识 - * @param mixed $value 存储数据 - * @param int|null $expire 有效时间 0为永久 - * @return boolean - */ - public static function set($name, $value, $expire = null) + public static function __make(Config $config) { - self::init(); - self::$writeTimes++; - return self::$handler->set($name, $value, $expire); + return new static($config->pull('cache')); } - /** - * 自增缓存(针对数值缓存) - * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 - * @return false|int - */ - public static function inc($name, $step = 1) + public function getConfig() { - self::init(); - self::$writeTimes++; - return self::$handler->inc($name, $step); + return $this->config; } - /** - * 自减缓存(针对数值缓存) - * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 - * @return false|int - */ - public static function dec($name, $step = 1) + public function setConfig(array $config) { - self::init(); - self::$writeTimes++; - return self::$handler->dec($name, $step); + $this->config = array_merge($this->config, $config); } /** - * 删除缓存 + * 切换缓存类型 需要配置 cache.type 为 complex * @access public - * @param string $name 缓存标识 - * @return boolean + * @param string $name 缓存标识 + * @return Driver */ - public static function rm($name) + public function store($name = '') { - self::init(); - self::$writeTimes++; - return self::$handler->rm($name); - } + if ('' !== $name && 'complex' == $this->config['type']) { + return $this->connect($this->config[$name], strtolower($name)); + } - /** - * 清除缓存 - * @access public - * @param string $tag 标签名 - * @return boolean - */ - public static function clear($tag = null) - { - self::init(); - self::$writeTimes++; - return self::$handler->clear($tag); + return $this->init(); } - /** - * 缓存标签 - * @access public - * @param string $name 标签名 - * @param string|array $keys 缓存标识 - * @param bool $overlay 是否覆盖 - * @return \think\cache\Driver - */ - public static function tag($name, $keys = null, $overlay = false) + public function __call($method, $args) { - self::init(); - return self::$handler->tag($name, $keys, $overlay); + return call_user_func_array([$this->init(), $method], $args); } } diff --git a/library/think/Collection.php b/library/think/Collection.php index 8315268a9d6b925e9c289db82763344bcd4ea650..929b51939dd73985c592763b6226056f4c9e7559 100644 --- a/library/think/Collection.php +++ b/library/think/Collection.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -19,6 +19,10 @@ use JsonSerializable; class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable { + /** + * 数据集数据 + * @var array + */ protected $items = []; public function __construct($items = []) @@ -33,6 +37,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 是否为空 + * @access public * @return bool */ public function isEmpty() @@ -55,6 +60,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 合并数组 * + * @access public * @param mixed $items * @return static */ @@ -66,6 +72,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 比较数组,返回差集 * + * @access public * @param mixed $items * @return static */ @@ -77,6 +84,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 交换数组中的键和值 * + * @access public * @return static */ public function flip() @@ -87,6 +95,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 比较数组,返回交集 * + * @access public * @param mixed $items * @return static */ @@ -98,6 +107,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 返回数组中所有的键名 * + * @access public * @return static */ public function keys() @@ -108,6 +118,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 删除数组的最后一个元素(出栈) * + * @access public * @return mixed */ public function pop() @@ -118,6 +129,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 通过使用用户自定义函数,以字符串返回数组 * + * @access public * @param callable $callback * @param mixed $initial * @return mixed @@ -130,6 +142,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 以相反的顺序返回数组。 * + * @access public * @return static */ public function reverse() @@ -140,6 +153,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 删除数组中首个元素,并返回被删除元素的值 * + * @access public * @return mixed */ public function shift() @@ -147,9 +161,26 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria return array_shift($this->items); } + /** + * 在数组结尾插入一个元素 + * @access public + * @param mixed $value + * @param mixed $key + * @return void + */ + public function push($value, $key = null) + { + if (is_null($key)) { + $this->items[] = $value; + } else { + $this->items[$key] = $value; + } + } + /** * 把一个数组分割为新的数组块. * + * @access public * @param int $size * @param bool $preserveKeys * @return static @@ -167,9 +198,10 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 在数组开头插入一个元素 - * @param mixed $value - * @param null $key - * @return int + * @access public + * @param mixed $value + * @param mixed $key + * @return void */ public function unshift($value, $key = null) { @@ -183,14 +215,19 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 给每个元素执行个回调 * + * @access public * @param callable $callback * @return $this */ public function each(callable $callback) { foreach ($this->items as $key => $item) { - if ($callback($item, $key) === false) { + $result = $callback($item, $key); + + if (false === $result) { break; + } elseif (!is_object($item)) { + $this->items[$key] = $result; } } @@ -199,7 +236,8 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 用回调函数过滤数组中的元素 - * @param callable|null $callback + * @access public + * @param callable|null $callback * @return static */ public function filter(callable $callback = null) @@ -212,46 +250,21 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria } /** - * 返回数组中指定的一列 - * @param $column_key - * @param null $index_key + * 返回数据中指定的一列 + * @access public + * @param mixed $columnKey 键名 + * @param mixed $indexKey 作为索引值的列 * @return array */ - public function column($column_key, $index_key = null) + public function column($columnKey, $indexKey = null) { - if (function_exists('array_column')) { - return array_column($this->items, $column_key, $index_key); - } - - $result = []; - foreach ($this->items as $row) { - $key = $value = null; - $keySet = $valueSet = false; - if (null !== $index_key && array_key_exists($index_key, $row)) { - $keySet = true; - $key = (string)$row[$index_key]; - } - if (null === $column_key) { - $valueSet = true; - $value = $row; - } elseif (is_array($row) && array_key_exists($column_key, $row)) { - $valueSet = true; - $value = $row[$column_key]; - } - if ($valueSet) { - if ($keySet) { - $result[$key] = $value; - } else { - $result[] = $value; - } - } - } - return $result; + return array_column($this->items, $columnKey, $indexKey); } /** * 对数组排序 * + * @access public * @param callable|null $callback * @return static */ @@ -259,14 +272,12 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria { $items = $this->items; - $callback ? uasort($items, $callback) : uasort($items, function ($a, $b) { + $callback = $callback ?: function ($a, $b) { + return $a == $b ? 0 : (($a < $b) ? -1 : 1); - if ($a == $b) { - return 0; - } + }; - return ($a < $b) ? -1 : 1; - }); + uasort($items, $callback); return new static($items); } @@ -274,6 +285,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 将数组打乱 * + * @access public * @return static */ public function shuffle() @@ -288,6 +300,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 截取数组 * + * @access public * @param int $offset * @param int $length * @param bool $preserveKeys @@ -344,7 +357,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 转换当前数据集为JSON字符串 * @access public - * @param integer $options json参数 + * @param integer $options json参数 * @return string */ public function toJson($options = JSON_UNESCAPED_UNICODE) @@ -360,6 +373,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria /** * 转换成数组 * + * @access public * @param mixed $items * @return array */ @@ -368,6 +382,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria if ($items instanceof self) { return $items->all(); } - return (array)$items; + + return (array) $items; } } diff --git a/library/think/Config.php b/library/think/Config.php index 5ab032fd4d1840c9f0370c11d466a7bd4759f1f3..1e60ac9d0317fc586a4e4baa20b69feb0701c46d 100644 --- a/library/think/Config.php +++ b/library/think/Config.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,157 +11,269 @@ namespace think; -class Config +class Config implements \ArrayAccess { - // 配置参数 - private static $config = []; - // 参数作用域 - private static $range = '_sys_'; + /** + * 配置参数 + * @var array + */ + private $config = []; + + /** + * 配置前缀 + * @var string + */ + private $prefix = 'app'; - // 设定配置参数的作用域 - public static function range($range) + /** + * 设置配置参数默认前缀 + * @access public + * @param string $prefix 前缀 + * @return void + */ + public function setDefaultPrefix($prefix) { - self::$range = $range; - if (!isset(self::$config[$range])) { - self::$config[$range] = []; - } + $this->prefix = $prefix; } /** * 解析配置文件或内容 - * @param string $config 配置文件路径或内容 - * @param string $type 配置解析类型 - * @param string $name 配置名(如设置即表示二级配置) - * @param string $range 作用域 + * @access public + * @param string $config 配置文件路径或内容 + * @param string $type 配置解析类型 + * @param string $name 配置名(如设置即表示二级配置) * @return mixed */ - public static function parse($config, $type = '', $name = '', $range = '') + public function parse($config, $type = '', $name = '') { - $range = $range ?: self::$range; if (empty($type)) { $type = pathinfo($config, PATHINFO_EXTENSION); } - $class = false !== strpos($type, '\\') ? $type : '\\think\\config\\driver\\' . ucwords($type); - return self::set((new $class())->parse($config), $name, $range); + + $object = Loader::factory($type, '\\think\\config\\driver\\', $config); + + return $this->set($object->parse(), $name); } /** - * 加载配置文件(PHP格式) - * @param string $file 配置文件名 - * @param string $name 配置名(如设置即表示二级配置) - * @param string $range 作用域 + * 加载配置文件(多种格式) + * @access public + * @param string $file 配置文件名 + * @param string $name 一级配置名 * @return mixed */ - public static function load($file, $name = '', $range = '') + public function load($file, $name = '') { - $range = $range ?: self::$range; - if (!isset(self::$config[$range])) { - self::$config[$range] = []; - } if (is_file($file)) { + $name = strtolower($name); $type = pathinfo($file, PATHINFO_EXTENSION); - if ('php' != $type) { - return self::parse($file, $type, $name, $range); - } else { - return self::set(include $file, $name, $range); + + if ('php' == $type) { + return $this->set(include $file, $name); + } elseif ('yaml' == $type && function_exists('yaml_parse_file')) { + return $this->set(yaml_parse_file($file), $name); } - } else { - return self::$config[$range]; + return $this->parse($file, $type, $name); } + + return $this->config; } /** * 检测配置是否存在 - * @param string $name 配置参数名(支持二级配置 .号分割) - * @param string $range 作用域 + * @access public + * @param string $name 配置参数名(支持多级配置 .号分割) * @return bool */ - public static function has($name, $range = '') + public function has($name) { - $range = $range ?: self::$range; - if (!strpos($name, '.')) { - return isset(self::$config[$range][strtolower($name)]); - } else { - // 二维数组设置和获取支持 - $name = explode('.', $name); - return isset(self::$config[$range][strtolower($name[0])][$name[1]]); + $name = $this->prefix . '.' . $name; } + + return !is_null($this->get($name)) ? true : false; + } + + /** + * 获取一级配置 + * @access public + * @param string $name 一级配置名 + * @return array + */ + public function pull($name) + { + $name = strtolower($name); + + return isset($this->config[$name]) ? $this->config[$name] : []; } /** * 获取配置参数 为空则获取所有配置 - * @param string $name 配置参数名(支持二级配置 .号分割) - * @param string $range 作用域 + * @access public + * @param string $name 配置参数名(支持多级配置 .号分割) + * @param mixed $default 默认值 * @return mixed */ - public static function get($name = null, $range = '') + public function get($name = null, $default = null) { - $range = $range ?: self::$range; // 无参数时获取所有 - if (empty($name) && isset(self::$config[$range])) { - return self::$config[$range]; + if (empty($name)) { + return $this->config; } if (!strpos($name, '.')) { - $name = strtolower($name); - return isset(self::$config[$range][$name]) ? self::$config[$range][$name] : null; - } else { - // 二维数组设置和获取支持 - $name = explode('.', $name); - $name[0] = strtolower($name[0]); - return isset(self::$config[$range][$name[0]][$name[1]]) ? self::$config[$range][$name[0]][$name[1]] : null; + $name = $this->prefix . '.' . $name; + } elseif ('.' == substr($name, -1)) { + return $this->pull(substr($name, 0, -1)); + } + + $name = explode('.', $name); + $name[0] = strtolower($name[0]); + $config = $this->config; + + // 按.拆分成多维数组进行判断 + foreach ($name as $val) { + if (isset($config[$val])) { + $config = $config[$val]; + } else { + return $default; + } } + + return $config; } /** * 设置配置参数 name为数组则为批量设置 - * @param string|array $name 配置参数名(支持二级配置 .号分割) - * @param mixed $value 配置值 - * @param string $range 作用域 + * @access public + * @param string|array $name 配置参数名(支持三级配置 .号分割) + * @param mixed $value 配置值 * @return mixed */ - public static function set($name, $value = null, $range = '') + public function set($name, $value = null) { - $range = $range ?: self::$range; - if (!isset(self::$config[$range])) { - self::$config[$range] = []; - } if (is_string($name)) { if (!strpos($name, '.')) { - self::$config[$range][strtolower($name)] = $value; + $name = $this->prefix . '.' . $name; + } + + $name = explode('.', $name, 3); + + if (count($name) == 2) { + $this->config[strtolower($name[0])][$name[1]] = $value; } else { - // 二维数组设置和获取支持 - $name = explode('.', $name); - self::$config[$range][strtolower($name[0])][$name[1]] = $value; + $this->config[strtolower($name[0])][$name[1]][$name[2]] = $value; } - return; + + return $value; } elseif (is_array($name)) { // 批量设置 if (!empty($value)) { - self::$config[$range][$value] = isset(self::$config[$range][$value]) ? - array_merge(self::$config[$range][$value], $name) : - self::$config[$range][$value] = $name; - return self::$config[$range][$value]; + if (isset($this->config[$value])) { + $result = array_merge($this->config[$value], $name); + } else { + $result = $name; + } + + $this->config[$value] = $result; } else { - return self::$config[$range] = array_merge(self::$config[$range], array_change_key_case($name)); + $result = $this->config = array_merge($this->config, $name); } } else { // 为空直接返回 已有配置 - return self::$config[$range]; + $result = $this->config; + } + + return $result; + } + + /** + * 移除配置 + * @access public + * @param string $name 配置参数名(支持三级配置 .号分割) + * @return void + */ + public function remove($name) + { + if (!strpos($name, '.')) { + $name = $this->prefix . '.' . $name; + } + + $name = explode('.', $name, 3); + + if (count($name) == 2) { + unset($this->config[strtolower($name[0])][$name[1]]); + } else { + unset($this->config[strtolower($name[0])][$name[1]][$name[2]]); } } /** * 重置配置参数 + * @access public + * @param string $prefix 配置前缀名 + * @return void */ - public static function reset($range = '') + public function reset($prefix = '') { - $range = $range ?: self::$range; - if (true === $range) { - self::$config = []; + if ('' === $prefix) { + $this->config = []; } else { - self::$config[$range] = []; + $this->config[$prefix] = []; } } + + /** + * 设置配置 + * @access public + * @param string $name 参数名 + * @param mixed $value 值 + */ + public function __set($name, $value) + { + return $this->set($name, $value); + } + + /** + * 获取配置参数 + * @access public + * @param string $name 参数名 + * @return mixed + */ + public function __get($name) + { + return $this->get($name); + } + + /** + * 检测是否存在参数 + * @access public + * @param string $name 参数名 + * @return bool + */ + public function __isset($name) + { + return $this->has($name); + } + + // ArrayAccess + public function offsetSet($name, $value) + { + $this->set($name, $value); + } + + public function offsetExists($name) + { + return $this->has($name); + } + + public function offsetUnset($name) + { + $this->remove($name); + } + + public function offsetGet($name) + { + return $this->get($name); + } } diff --git a/library/think/Console.php b/library/think/Console.php index ab8e0211ba15dd7ceae107bc2efd80224df78f9d..9757e4766035d491a511d0beb21500e92d4fa8c8 100644 --- a/library/think/Console.php +++ b/library/think/Console.php @@ -41,17 +41,31 @@ class Console "think\\console\\command\\Clear", "think\\console\\command\\make\\Controller", "think\\console\\command\\make\\Model", + "think\\console\\command\\make\\Middleware", + "think\\console\\command\\make\\Validate", "think\\console\\command\\optimize\\Autoload", "think\\console\\command\\optimize\\Config", - "think\\console\\command\\optimize\\Route", "think\\console\\command\\optimize\\Schema", + "think\\console\\command\\optimize\\Route", + "think\\console\\command\\RunServer", ]; - public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN') + /** + * Console constructor. + * @access public + * @param string $name 名称 + * @param string $version 版本 + * @param null|string $user 执行用户 + */ + public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN', $user = null) { $this->name = $name; $this->version = $version; + if ($user) { + $this->setUser($user); + } + $this->defaultCommand = 'list'; $this->definition = $this->getDefaultInputDefinition(); @@ -60,15 +74,40 @@ class Console } } + /** + * 设置执行用户 + * @param $user + */ + public function setUser($user) + { + $user = posix_getpwnam($user); + if ($user) { + posix_setuid($user['uid']); + posix_setgid($user['gid']); + } + } + + /** + * 初始化 Console + * @access public + * @param bool $run 是否运行 Console + * @return int|Console + */ public static function init($run = true) { static $console; + if (!$console) { - // 实例化console - $console = new self('Think Console', '0.1'); + $config = Container::get('config')->pull('console'); + // 实例化 console + $console = new self($config['name'], $config['version'], $config['user']); + // 读取指令集 - if (is_file(CONF_PATH . 'command' . EXT)) { - $commands = include CONF_PATH . 'command' . EXT; + $file = Container::get('env')->get('app_path') . 'command.php'; + + if (is_file($file)) { + $commands = include $file; + if (is_array($commands)) { foreach ($commands as $command) { if (class_exists($command) && is_subclass_of($command, "\\think\\console\\Command")) { @@ -79,6 +118,7 @@ class Console } } } + if ($run) { // 运行 return $console->run(); @@ -88,18 +128,20 @@ class Console } /** - * @param $command - * @param array $parameters + * @access public + * @param string $command + * @param array $parameters + * @param string $driver * @return Output|Buffer */ - public static function call($command, array $parameters = []) + public static function call($command, array $parameters = [], $driver = 'buffer') { $console = self::init(false); array_unshift($parameters, $command); $input = new Input($parameters); - $output = new Output('buffer'); + $output = new Output($driver); $console->setCatchExceptions(false); $console->find($command)->run($input, $output); @@ -109,6 +151,7 @@ class Console /** * 执行当前的指令 + * @access public * @return int * @throws \Exception * @api @@ -153,8 +196,9 @@ class Console /** * 执行指令 - * @param Input $input - * @param Output $output + * @access public + * @param Input $input + * @param Output $output * @return int */ public function doRun(Input $input, Output $output) @@ -190,7 +234,8 @@ class Console /** * 设置输入参数定义 - * @param InputDefinition $definition + * @access public + * @param InputDefinition $definition */ public function setDefinition(InputDefinition $definition) { @@ -199,6 +244,7 @@ class Console /** * 获取输入参数定义 + * @access public * @return InputDefinition The InputDefinition instance */ public function getDefinition() @@ -208,6 +254,7 @@ class Console /** * Gets the help message. + * @access public * @return string A help message. */ public function getHelp() @@ -217,7 +264,8 @@ class Console /** * 是否捕获异常 - * @param bool $boolean + * @access public + * @param bool $boolean * @api */ public function setCatchExceptions($boolean) @@ -227,7 +275,8 @@ class Console /** * 是否自动退出 - * @param bool $boolean + * @access public + * @param bool $boolean * @api */ public function setAutoExit($boolean) @@ -237,6 +286,7 @@ class Console /** * 获取名称 + * @access public * @return string */ public function getName() @@ -246,7 +296,8 @@ class Console /** * 设置名称 - * @param string $name + * @access public + * @param string $name */ public function setName($name) { @@ -255,6 +306,7 @@ class Console /** * 获取版本 + * @access public * @return string * @api */ @@ -265,7 +317,8 @@ class Console /** * 设置版本 - * @param string $version + * @access public + * @param string $version */ public function setVersion($version) { @@ -274,6 +327,7 @@ class Console /** * 获取完整的版本号 + * @access public * @return string */ public function getLongVersion() @@ -287,7 +341,8 @@ class Console /** * 注册一个指令 - * @param string $name + * @access public + * @param string $name * @return Command */ public function register($name) @@ -297,7 +352,8 @@ class Console /** * 添加指令 - * @param Command[] $commands + * @access public + * @param Command[] $commands */ public function addCommands(array $commands) { @@ -308,7 +364,8 @@ class Console /** * 添加一个指令 - * @param Command $command + * @access public + * @param Command $command * @return Command */ public function add(Command $command) @@ -317,7 +374,7 @@ class Console if (!$command->isEnabled()) { $command->setConsole(null); - return null; + return; } if (null === $command->getDefinition()) { @@ -335,7 +392,8 @@ class Console /** * 获取指令 - * @param string $name 指令名称 + * @access public + * @param string $name 指令名称 * @return Command * @throws \InvalidArgumentException */ @@ -362,7 +420,8 @@ class Console /** * 某个指令是否存在 - * @param string $name 指令名称 + * @access public + * @param string $name 指令名称 * @return bool */ public function has($name) @@ -372,6 +431,7 @@ class Console /** * 获取所有的命名空间 + * @access public * @return array */ public function getNamespaces() @@ -390,7 +450,8 @@ class Console /** * 查找注册命名空间中的名称或缩写。 - * @param string $namespace + * @access public + * @param string $namespace * @return string * @throws \InvalidArgumentException */ @@ -428,16 +489,19 @@ class Console /** * 查找指令 - * @param string $name 名称或者别名 + * @access public + * @param string $name 名称或者别名 * @return Command * @throws \InvalidArgumentException */ public function find($name) { $allCommands = array_keys($this->commands); - $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { + + $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]) . '[^:]*'; }, $name); + $commands = preg_grep('{^' . $expr . '}', $allCommands); if (empty($commands) || count(preg_grep('{^' . $expr . '$}', $commands)) < 1) { @@ -461,7 +525,8 @@ class Console if (count($commands) > 1) { $commandList = $this->commands; - $commands = array_filter($commands, function ($nameOrAlias) use ($commandList, $commands) { + + $commands = array_filter($commands, function ($nameOrAlias) use ($commandList, $commands) { $commandName = $commandList[$nameOrAlias]->getName(); return $commandName === $nameOrAlias || !in_array($commandName, $commands); @@ -480,7 +545,8 @@ class Console /** * 获取所有的指令 - * @param string $namespace 命名空间 + * @access public + * @param string $namespace 命名空间 * @return Command[] * @api */ @@ -502,7 +568,8 @@ class Console /** * 获取可能的指令名 - * @param array $names + * @access public + * @param array $names * @return array */ public static function getAbbreviations($names) @@ -520,8 +587,9 @@ class Console /** * 配置基于用户的参数和选项的输入和输出实例。 - * @param Input $input 输入实例 - * @param Output $output 输出实例 + * @access protected + * @param Input $input 输入实例 + * @param Output $output 输出实例 */ protected function configureIO(Input $input, Output $output) { @@ -550,9 +618,10 @@ class Console /** * 执行指令 - * @param Command $command 指令实例 - * @param Input $input 输入实例 - * @param Output $output 输出实例 + * @access protected + * @param Command $command 指令实例 + * @param Input $input 输入实例 + * @param Output $output 输出实例 * @return int * @throws \Exception */ @@ -563,7 +632,8 @@ class Console /** * 获取指令的基础名称 - * @param Input $input + * @access protected + * @param Input $input * @return string */ protected function getCommandName(Input $input) @@ -573,6 +643,7 @@ class Console /** * 获取默认输入定义 + * @access protected * @return InputDefinition */ protected function getDefaultInputDefinition() @@ -591,6 +662,7 @@ class Console /** * 设置默认命令 + * @access protected * @return Command[] An array of default Command instances */ protected function getDefaultCommands() @@ -613,7 +685,8 @@ class Console /** * 获取可能的建议 - * @param array $abbrevs + * @access private + * @param array $abbrevs * @return string */ private function getAbbreviationSuggestions($abbrevs) @@ -623,8 +696,9 @@ class Console /** * 返回命名空间部分 - * @param string $name 指令 - * @param string $limit 部分的命名空间的最大数量 + * @access public + * @param string $name 指令 + * @param string $limit 部分的命名空间的最大数量 * @return string */ public function extractNamespace($name, $limit = null) @@ -637,8 +711,9 @@ class Console /** * 查找可替代的建议 - * @param string $name - * @param array|\Traversable $collection + * @access private + * @param string $name + * @param array|\Traversable $collection * @return array */ private function findAlternatives($name, $collection) @@ -687,7 +762,8 @@ class Console /** * 设置默认的指令 - * @param string $commandName The Command name + * @access public + * @param string $commandName The Command name */ public function setDefaultCommand($commandName) { @@ -696,7 +772,8 @@ class Console /** * 返回所有的命名空间 - * @param string $name + * @access private + * @param string $name * @return array */ private function extractAllNamespaces($name) diff --git a/library/think/Container.php b/library/think/Container.php new file mode 100644 index 0000000000000000000000000000000000000000..79c84e13ac3cf1dcf7a561c4f260122f3326d64c --- /dev/null +++ b/library/think/Container.php @@ -0,0 +1,505 @@ + +// +---------------------------------------------------------------------- + +namespace think; + +use Closure; +use InvalidArgumentException; +use ReflectionClass; +use ReflectionException; +use ReflectionFunction; +use ReflectionMethod; +use think\exception\ClassNotFoundException; + +class Container implements \ArrayAccess +{ + /** + * 容器对象实例 + * @var Container + */ + protected static $instance; + + /** + * 容器中的对象实例 + * @var array + */ + protected $instances = []; + + /** + * 容器绑定标识 + * @var array + */ + protected $bind = [ + 'app' => App::class, + 'build' => Build::class, + 'cache' => Cache::class, + 'config' => Config::class, + 'cookie' => Cookie::class, + 'debug' => Debug::class, + 'env' => Env::class, + 'hook' => Hook::class, + 'lang' => Lang::class, + 'log' => Log::class, + 'middleware' => Middleware::class, + 'request' => Request::class, + 'response' => Response::class, + 'route' => Route::class, + 'session' => Session::class, + 'url' => Url::class, + 'validate' => Validate::class, + 'view' => View::class, + 'rule_name' => route\RuleName::class, + // 接口依赖注入 + 'think\LoggerInterface' => Log::class, + ]; + + /** + * 容器标识别名 + * @var array + */ + protected $name = []; + + /** + * 获取当前容器的实例(单例) + * @access public + * @return static + */ + public static function getInstance() + { + if (is_null(static::$instance)) { + static::$instance = new static; + } + + return static::$instance; + } + + /** + * 设置当前容器的实例 + * @access public + * @param object $instance + * @return void + */ + public static function setInstance($instance) + { + static::$instance = $instance; + } + + /** + * 获取容器中的对象实例 + * @access public + * @param string $abstract 类名或者标识 + * @param array|true $vars 变量 + * @param bool $newInstance 是否每次创建新的实例 + * @return object + */ + public static function get($abstract, $vars = [], $newInstance = false) + { + return static::getInstance()->make($abstract, $vars, $newInstance); + } + + /** + * 绑定一个类、闭包、实例、接口实现到容器 + * @access public + * @param string $abstract 类标识、接口 + * @param mixed $concrete 要绑定的类、闭包或者实例 + * @return Container + */ + public static function set($abstract, $concrete = null) + { + return static::getInstance()->bindTo($abstract, $concrete); + } + + /** + * 移除容器中的对象实例 + * @access public + * @param string $abstract 类标识、接口 + * @return void + */ + public static function remove($abstract) + { + return static::getInstance()->delete($abstract); + } + + /** + * 清除容器中的对象实例 + * @access public + * @return void + */ + public static function clear() + { + return static::getInstance()->flush(); + } + + /** + * 绑定一个类、闭包、实例、接口实现到容器 + * @access public + * @param string|array $abstract 类标识、接口 + * @param mixed $concrete 要绑定的类、闭包或者实例 + * @return $this + */ + public function bindTo($abstract, $concrete = null) + { + if (is_array($abstract)) { + $this->bind = array_merge($this->bind, $abstract); + } elseif ($concrete instanceof Closure) { + $this->bind[$abstract] = $concrete; + } elseif (is_object($concrete)) { + $this->instances[$abstract] = $concrete; + } else { + $this->bind[$abstract] = $concrete; + } + + return $this; + } + + /** + * 绑定一个类实例当容器 + * @access public + * @param string $abstract 类名或者标识 + * @param object|\Closure $instance 类的实例 + * @return $this + */ + public function instance($abstract, $instance) + { + if ($instance instanceof \Closure) { + $this->bind[$abstract] = $instance; + } else { + if (isset($this->bind[$abstract])) { + $abstract = $this->bind[$abstract]; + } + + $this->instances[$abstract] = $instance; + } + + return $this; + } + + /** + * 判断容器中是否存在类及标识 + * @access public + * @param string $abstract 类名或者标识 + * @return bool + */ + public function bound($abstract) + { + return isset($this->bind[$abstract]) || isset($this->instances[$abstract]); + } + + /** + * 判断容器中是否存在对象实例 + * @access public + * @param string $abstract 类名或者标识 + * @return bool + */ + public function exists($abstract) + { + if (isset($this->bind[$abstract])) { + $abstract = $this->bind[$abstract]; + } + + return isset($this->instances[$abstract]); + } + + /** + * 判断容器中是否存在类及标识 + * @access public + * @param string $name 类名或者标识 + * @return bool + */ + public function has($name) + { + return $this->bound($name); + } + + /** + * 创建类的实例 + * @access public + * @param string $abstract 类名或者标识 + * @param array|true $vars 变量 + * @param bool $newInstance 是否每次创建新的实例 + * @return object + */ + public function make($abstract, $vars = [], $newInstance = false) + { + if (true === $vars) { + // 总是创建新的实例化对象 + $newInstance = true; + $vars = []; + } + + $abstract = isset($this->name[$abstract]) ? $this->name[$abstract] : $abstract; + + if (isset($this->instances[$abstract]) && !$newInstance) { + return $this->instances[$abstract]; + } + + if (isset($this->bind[$abstract])) { + $concrete = $this->bind[$abstract]; + + if ($concrete instanceof Closure) { + $object = $this->invokeFunction($concrete, $vars); + } else { + $this->name[$abstract] = $concrete; + return $this->make($concrete, $vars, $newInstance); + } + } else { + $object = $this->invokeClass($abstract, $vars); + } + + if (!$newInstance) { + $this->instances[$abstract] = $object; + } + + return $object; + } + + /** + * 删除容器中的对象实例 + * @access public + * @param string|array $abstract 类名或者标识 + * @return void + */ + public function delete($abstract) + { + foreach ((array) $abstract as $name) { + $name = isset($this->name[$name]) ? $this->name[$name] : $name; + + if (isset($this->instances[$name])) { + unset($this->instances[$name]); + } + } + } + + /** + * 清除容器中的对象实例 + * @access public + * @return void + */ + public function flush() + { + $this->instances = []; + $this->bind = []; + $this->name = []; + } + + /** + * 执行函数或者闭包方法 支持参数调用 + * @access public + * @param mixed $function 函数或者闭包 + * @param array $vars 参数 + * @return mixed + */ + public function invokeFunction($function, $vars = []) + { + try { + $reflect = new ReflectionFunction($function); + + $args = $this->bindParams($reflect, $vars); + + return call_user_func_array($function, $args); + } catch (ReflectionException $e) { + throw new Exception('function not exists: ' . $function . '()'); + } + } + + /** + * 调用反射执行类的方法 支持参数绑定 + * @access public + * @param mixed $method 方法 + * @param array $vars 参数 + * @return mixed + */ + public function invokeMethod($method, $vars = []) + { + try { + if (is_array($method)) { + $class = is_object($method[0]) ? $method[0] : $this->invokeClass($method[0]); + $reflect = new ReflectionMethod($class, $method[1]); + } else { + // 静态方法 + $reflect = new ReflectionMethod($method); + } + + $args = $this->bindParams($reflect, $vars); + + return $reflect->invokeArgs(isset($class) ? $class : null, $args); + } catch (ReflectionException $e) { + if (is_array($method) && is_object($method[0])) { + $method[0] = get_class($method[0]); + } + + throw new Exception('method not exists: ' . (is_array($method) ? $method[0] . '::' . $method[1] : $method) . '()'); + } + } + + /** + * 调用反射执行类的方法 支持参数绑定 + * @access public + * @param object $instance 对象实例 + * @param mixed $reflect 反射类 + * @param array $vars 参数 + * @return mixed + */ + public function invokeReflectMethod($instance, $reflect, $vars = []) + { + $args = $this->bindParams($reflect, $vars); + + return $reflect->invokeArgs($instance, $args); + } + + /** + * 调用反射执行callable 支持参数绑定 + * @access public + * @param mixed $callable + * @param array $vars 参数 + * @return mixed + */ + public function invoke($callable, $vars = []) + { + if ($callable instanceof Closure) { + return $this->invokeFunction($callable, $vars); + } + + return $this->invokeMethod($callable, $vars); + } + + /** + * 调用反射执行类的实例化 支持依赖注入 + * @access public + * @param string $class 类名 + * @param array $vars 参数 + * @return mixed + */ + public function invokeClass($class, $vars = []) + { + try { + $reflect = new ReflectionClass($class); + + if ($reflect->hasMethod('__make')) { + $method = new ReflectionMethod($class, '__make'); + + if ($method->isPublic() && $method->isStatic()) { + $args = $this->bindParams($method, $vars); + return $method->invokeArgs(null, $args); + } + } + + $constructor = $reflect->getConstructor(); + + $args = $constructor ? $this->bindParams($constructor, $vars) : []; + + return $reflect->newInstanceArgs($args); + + } catch (ReflectionException $e) { + throw new ClassNotFoundException('class not exists: ' . $class, $class); + } + } + + /** + * 绑定参数 + * @access protected + * @param \ReflectionMethod|\ReflectionFunction $reflect 反射类 + * @param array $vars 参数 + * @return array + */ + protected function bindParams($reflect, $vars = []) + { + if ($reflect->getNumberOfParameters() == 0) { + return []; + } + + // 判断数组类型 数字数组时按顺序绑定参数 + reset($vars); + $type = key($vars) === 0 ? 1 : 0; + $params = $reflect->getParameters(); + + foreach ($params as $param) { + $name = $param->getName(); + $class = $param->getClass(); + + if ($class) { + $args[] = $this->getObjectParam($class->getName(), $vars); + } elseif (1 == $type && !empty($vars)) { + $args[] = array_shift($vars); + } elseif (0 == $type && isset($vars[$name])) { + $args[] = $vars[$name]; + } elseif ($param->isDefaultValueAvailable()) { + $args[] = $param->getDefaultValue(); + } else { + throw new InvalidArgumentException('method param miss:' . $name); + } + } + + return $args; + } + + /** + * 获取对象类型的参数值 + * @access protected + * @param string $className 类名 + * @param array $vars 参数 + * @return mixed + */ + protected function getObjectParam($className, &$vars) + { + $array = $vars; + $value = array_shift($array); + + if ($value instanceof $className) { + $result = $value; + array_shift($vars); + } else { + $result = $this->make($className); + } + + return $result; + } + + public function __set($name, $value) + { + $this->bindTo($name, $value); + } + + public function __get($name) + { + return $this->make($name); + } + + public function __isset($name) + { + return $this->bound($name); + } + + public function __unset($name) + { + $this->delete($name); + } + + public function offsetExists($key) + { + return $this->__isset($key); + } + + public function offsetGet($key) + { + return $this->__get($key); + } + + public function offsetSet($key, $value) + { + $this->__set($key, $value); + } + + public function offsetUnset($key) + { + $this->__unset($key); + } +} diff --git a/library/think/Controller.php b/library/think/Controller.php index a889e4d9e4fe56275408303e3356c90161fd3542..19fc8df6f0b98603b60943f61c2016a9941a1460 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,67 +11,96 @@ namespace think; -\think\Loader::import('controller/Jump', TRAIT_PATH, EXT); - -use think\Exception; use think\exception\ValidateException; +use traits\controller\Jump; class Controller { - use \traits\controller\Jump; + use Jump; - // 视图类实例 + /** + * 视图类实例 + * @var \think\View + */ protected $view; - // Request实例 + + /** + * Request实例 + * @var \think\Request + */ protected $request; - // 验证失败是否抛出异常 + + /** + * 验证失败是否抛出异常 + * @var bool + */ protected $failException = false; - // 是否批量验证 + + /** + * 是否批量验证 + * @var bool + */ protected $batchValidate = false; /** - * 前置操作方法列表 + * 前置操作方法列表(即将废弃) * @var array $beforeActionList - * @access protected */ protected $beforeActionList = []; /** - * 架构函数 - * @param Request $request Request对象 + * 控制器中间件 + * @var array + */ + protected $middleware = []; + + /** + * 构造方法 * @access public */ - public function __construct(Request $request = null) + public function __construct(App $app = null) { - if (is_null($request)) { - $request = Request::instance(); - } - $this->view = View::instance(Config::get('template'), Config::get('view_replace_str')); - $this->request = $request; + $this->app = $app ?: Container::get('app'); + $this->request = $this->app['request']; + $this->view = $this->app['view']; // 控制器初始化 - $this->_initialize(); - - // 前置操作方法 - if ($this->beforeActionList) { - foreach ($this->beforeActionList as $method => $options) { - is_numeric($method) ? - $this->beforeAction($options) : - $this->beforeAction($method, $options); + $this->initialize(); + + // 控制器中间件 + if ($this->middleware) { + foreach ($this->middleware as $key => $val) { + if (!is_int($key)) { + if (isset($val['only']) && !in_array($this->request->action(), $val['only'])) { + continue; + } elseif (isset($val['except']) && in_array($this->request->action(), $val['except'])) { + continue; + } else { + $val = $key; + } + } + + $this->app['middleware']->controller($val); } } + + // 前置操作方法 即将废弃 + foreach ((array) $this->beforeActionList as $method => $options) { + is_numeric($method) ? + $this->beforeAction($options) : + $this->beforeAction($method, $options); + } } // 初始化 - protected function _initialize() - { - } + protected function initialize() + {} /** * 前置操作 * @access protected - * @param string $method 前置操作方法名 - * @param array $options 调用参数 ['only'=>[...]] 或者['except'=>[...]] + * @param string $method 前置操作方法名 + * @param array $options 调用参数 ['only'=>[...]] 或者['except'=>[...]] */ protected function beforeAction($method, $options = []) { @@ -97,92 +126,109 @@ class Controller /** * 加载模板输出 * @access protected - * @param string $template 模板文件名 - * @param array $vars 模板输出变量 - * @param array $replace 模板替换 - * @param array $config 模板参数 + * @param string $template 模板文件名 + * @param array $vars 模板输出变量 + * @param array $config 模板参数 * @return mixed */ - protected function fetch($template = '', $vars = [], $replace = [], $config = []) + protected function fetch($template = '', $vars = [], $config = []) { - return $this->view->fetch($template, $vars, $replace, $config); + return $this->view->fetch($template, $vars, $config); } /** * 渲染内容输出 * @access protected - * @param string $content 模板内容 - * @param array $vars 模板输出变量 - * @param array $replace 替换内容 - * @param array $config 模板参数 + * @param string $content 模板内容 + * @param array $vars 模板输出变量 + * @param array $config 模板参数 * @return mixed */ - protected function display($content = '', $vars = [], $replace = [], $config = []) + protected function display($content = '', $vars = [], $config = []) { - return $this->view->display($content, $vars, $replace, $config); + return $this->view->display($content, $vars, $config); } /** * 模板变量赋值 * @access protected - * @param mixed $name 要显示的模板变量 - * @param mixed $value 变量的值 - * @return void + * @param mixed $name 要显示的模板变量 + * @param mixed $value 变量的值 + * @return $this */ protected function assign($name, $value = '') { $this->view->assign($name, $value); + + return $this; + } + + /** + * 视图过滤 + * @access protected + * @param Callable $filter 过滤方法或闭包 + * @return $this + */ + protected function filter($filter) + { + $this->view->filter($filter); + + return $this; } /** * 初始化模板引擎 * @access protected - * @param array|string $engine 引擎参数 - * @return void + * @param array|string $engine 引擎参数 + * @return $this */ protected function engine($engine) { $this->view->engine($engine); + + return $this; } /** * 设置验证失败后是否抛出异常 * @access protected - * @param bool $fail 是否抛出异常 + * @param bool $fail 是否抛出异常 * @return $this */ protected function validateFailException($fail = true) { $this->failException = $fail; + return $this; } /** * 验证数据 * @access protected - * @param array $data 数据 - * @param string|array $validate 验证器名或者验证规则数组 - * @param array $message 提示信息 - * @param bool $batch 是否批量验证 - * @param mixed $callback 回调方法(闭包) + * @param array $data 数据 + * @param string|array $validate 验证器名或者验证规则数组 + * @param array $message 提示信息 + * @param bool $batch 是否批量验证 + * @param mixed $callback 回调方法(闭包) * @return array|string|true * @throws ValidateException */ protected function validate($data, $validate, $message = [], $batch = false, $callback = null) { if (is_array($validate)) { - $v = Loader::validate(); + $v = $this->app->validate(); $v->rule($validate); } else { if (strpos($validate, '.')) { // 支持场景 list($validate, $scene) = explode('.', $validate); } - $v = Loader::validate($validate); + $v = $this->app->validate($validate); if (!empty($scene)) { $v->scene($scene); } } + // 是否批量验证 if ($batch || $this->batchValidate) { $v->batch(true); @@ -199,11 +245,10 @@ class Controller if (!$v->check($data)) { if ($this->failException) { throw new ValidateException($v->getError()); - } else { - return $v->getError(); } - } else { - return true; + return $v->getError(); } + + return true; } } diff --git a/library/think/Cookie.php b/library/think/Cookie.php index 648b2c6086c6937b74ec0b59995606bc52608d45..08141617c58acb38acaa8638da76197d6bf0f032 100644 --- a/library/think/Cookie.php +++ b/library/think/Cookie.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,7 +13,11 @@ namespace think; class Cookie { - protected static $config = [ + /** + * 配置参数 + * @var array + */ + protected $config = [ // cookie 名称前缀 'prefix' => '', // cookie 保存时间 @@ -25,56 +29,66 @@ class Cookie // cookie 启用安全传输 'secure' => false, // httponly设置 - 'httponly' => '', + 'httponly' => false, // 是否使用 setcookie 'setcookie' => true, ]; - protected static $init; + /** + * 构造方法 + * @access public + */ + public function __construct(array $config = []) + { + $this->init($config); + } /** * Cookie初始化 - * @param array $config + * @access public + * @param array $config * @return void */ - public static function init(array $config = []) + public function init(array $config = []) { - if (empty($config)) { - $config = Config::get('cookie'); - } - self::$config = array_merge(self::$config, array_change_key_case($config)); - if (!empty(self::$config['httponly'])) { + $this->config = array_merge($this->config, array_change_key_case($config)); + + if (!empty($this->config['httponly']) && PHP_SESSION_ACTIVE != session_status()) { ini_set('session.cookie_httponly', 1); } - self::$init = true; + } + + public static function __make(Config $config) + { + return new static($config->pull('cookie')); } /** * 设置或者获取cookie作用域(前缀) - * @param string $prefix + * @access public + * @param string $prefix * @return string|void */ - public static function prefix($prefix = '') + public function prefix($prefix = '') { if (empty($prefix)) { - return self::$config['prefix']; + return $this->config['prefix']; } - self::$config['prefix'] = $prefix; + + $this->config['prefix'] = $prefix; } /** * Cookie 设置、获取、删除 * - * @param string $name cookie名称 - * @param mixed $value cookie值 - * @param mixed $option 可选参数 可能会是 null|integer|string - * - * @return mixed - * @internal param mixed $options cookie参数 + * @access public + * @param string $name cookie名称 + * @param mixed $value cookie值 + * @param mixed $option 可选参数 可能会是 null|integer|string + * @return void */ - public static function set($name, $value = '', $option = null) + public function set($name, $value = '', $option = null) { - !isset(self::$init) && self::init(); // 参数设置(会覆盖黙认设置) if (!is_null($option)) { if (is_numeric($option)) { @@ -82,95 +96,139 @@ class Cookie } elseif (is_string($option)) { parse_str($option, $option); } - $config = array_merge(self::$config, array_change_key_case($option)); + + $config = array_merge($this->config, array_change_key_case($option)); } else { - $config = self::$config; + $config = $this->config; } + $name = $config['prefix'] . $name; + // 设置cookie if (is_array($value)) { - array_walk_recursive($value, 'self::jsonFormatProtect', 'encode'); + array_walk_recursive($value, [$this, 'jsonFormatProtect'], 'encode'); $value = 'think:' . json_encode($value); } + $expire = !empty($config['expire']) ? $_SERVER['REQUEST_TIME'] + intval($config['expire']) : 0; + if ($config['setcookie']) { setcookie($name, $value, $expire, $config['path'], $config['domain'], $config['secure'], $config['httponly']); } + $_COOKIE[$name] = $value; } + /** + * 永久保存Cookie数据 + * @access public + * @param string $name cookie名称 + * @param mixed $value cookie值 + * @param mixed $option 可选参数 可能会是 null|integer|string + * @return void + */ + public function forever($name, $value = '', $option = null) + { + if (is_null($option) || is_numeric($option)) { + $option = []; + } + + $option['expire'] = 315360000; + + $this->set($name, $value, $option); + } + /** * 判断Cookie数据 - * @param string $name cookie名称 - * @param string|null $prefix cookie前缀 + * @access public + * @param string $name cookie名称 + * @param string|null $prefix cookie前缀 * @return bool */ - public static function has($name, $prefix = null) + public function has($name, $prefix = null) { - !isset(self::$init) && self::init(); - $prefix = !is_null($prefix) ? $prefix : self::$config['prefix']; + $prefix = !is_null($prefix) ? $prefix : $this->config['prefix']; $name = $prefix . $name; + return isset($_COOKIE[$name]); } /** * Cookie获取 - * @param string $name cookie名称 - * @param string|null $prefix cookie前缀 + * @access public + * @param string $name cookie名称 留空获取全部 + * @param string|null $prefix cookie前缀 * @return mixed */ - public static function get($name, $prefix = null) + public function get($name = '', $prefix = null) { - !isset(self::$init) && self::init(); - $prefix = !is_null($prefix) ? $prefix : self::$config['prefix']; - $name = $prefix . $name; - if (isset($_COOKIE[$name])) { - $value = $_COOKIE[$name]; + $prefix = !is_null($prefix) ? $prefix : $this->config['prefix']; + $key = $prefix . $name; + + if ('' == $name) { + if ($prefix) { + $value = []; + foreach ($_COOKIE as $k => $val) { + if (0 === strpos($k, $prefix)) { + $value[$k] = $val; + } + } + } else { + $value = $_COOKIE; + } + } elseif (isset($_COOKIE[$key])) { + $value = $_COOKIE[$key]; + if (0 === strpos($value, 'think:')) { $value = substr($value, 6); $value = json_decode($value, true); - array_walk_recursive($value, 'self::jsonFormatProtect', 'decode'); + array_walk_recursive($value, [$this, 'jsonFormatProtect'], 'decode'); } - return $value; } else { - return null; + $value = null; } + + return $value; } /** * Cookie删除 - * @param string $name cookie名称 - * @param string|null $prefix cookie前缀 - * @return mixed + * @access public + * @param string $name cookie名称 + * @param string|null $prefix cookie前缀 + * @return void */ - public static function delete($name, $prefix = null) + public function delete($name, $prefix = null) { - !isset(self::$init) && self::init(); - $config = self::$config; + $config = $this->config; $prefix = !is_null($prefix) ? $prefix : $config['prefix']; $name = $prefix . $name; + if ($config['setcookie']) { setcookie($name, '', $_SERVER['REQUEST_TIME'] - 3600, $config['path'], $config['domain'], $config['secure'], $config['httponly']); } + // 删除指定cookie unset($_COOKIE[$name]); } /** * Cookie清空 - * @param string|null $prefix cookie前缀 - * @return mixed + * @access public + * @param string|null $prefix cookie前缀 + * @return void */ - public static function clear($prefix = null) + public function clear($prefix = null) { // 清除指定前缀的所有cookie if (empty($_COOKIE)) { return; } - !isset(self::$init) && self::init(); + // 要删除的cookie前缀,不指定则删除config设置的指定前缀 - $config = self::$config; + $config = $this->config; $prefix = !is_null($prefix) ? $prefix : $config['prefix']; + if ($prefix) { // 如果前缀为空字符串将不作处理直接返回 foreach ($_COOKIE as $key => $val) { @@ -182,10 +240,11 @@ class Cookie } } } + return; } - private static function jsonFormatProtect(&$val, $key, $type = 'encode') + private function jsonFormatProtect(&$val, $key, $type = 'encode') { if (!empty($val) && true !== $val) { $val = 'decode' == $type ? urldecode($val) : urlencode($val); diff --git a/library/think/Db.php b/library/think/Db.php index b00aee6100a690908bee48c899ffa735e6a7ee92..f72c0f1d1e95ad4606af771a1074243b9b888282 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,118 +11,167 @@ namespace think; -use think\App; -use think\Collection; -use think\db\Query; -use think\paginator\Collection as PaginatorCollection; +use think\db\Connection; /** * Class Db * @package think - * @method Query table(string $table) static 指定数据表(含前缀) - * @method Query name(string $name) static 指定数据表(不含前缀) - * @method Query where(mixed $field, string $op = null, mixed $condition = null) static 查询条件 - * @method Query join(mixed $join, mixed $condition = null, string $type = 'INNER') static JOIN查询 - * @method Query union(mixed $union, boolean $all = false) static UNION查询 - * @method Query limit(mixed $offset, integer $length = null) static 查询LIMIT - * @method Query order(mixed $field, string $order = null) static 查询ORDER - * @method Query cache(mixed $key = true , integer $expire = null) static 设置查询缓存 + * @method \think\db\Query connect(array $config =[], mixed $name = false) static 连接/切换数据库连接 + * @method \think\db\Query master() static 从主服务器读取数据 + * @method \think\db\Query readMaster(bool $all = false) static 后续从主服务器读取数据 + * @method \think\db\Query table(string $table) static 指定数据表(含前缀) + * @method \think\db\Query name(string $name) static 指定数据表(不含前缀) + * @method \think\db\Expression raw(string $value) static 使用表达式设置数据 + * @method \think\db\Query where(mixed $field, string $op = null, mixed $condition = null) static 查询条件 + * @method \think\db\Query whereRaw(string $where, array $bind = []) static 表达式查询 + * @method \think\db\Query whereExp(string $field, string $condition, array $bind = []) static 字段表达式查询 + * @method \think\db\Query when(mixed $condition, mixed $query, mixed $otherwise = null) static 条件查询 + * @method \think\db\Query join(mixed $join, mixed $condition = null, string $type = 'INNER') static JOIN查询 + * @method \think\db\Query view(mixed $join, mixed $field = null, mixed $on = null, string $type = 'INNER') static 视图查询 + * @method \think\db\Query field(mixed $field, boolean $except = false) static 指定查询字段 + * @method \think\db\Query fieldRaw(string $field, array $bind = []) static 指定查询字段 + * @method \think\db\Query union(mixed $union, boolean $all = false) static UNION查询 + * @method \think\db\Query limit(mixed $offset, integer $length = null) static 查询LIMIT + * @method \think\db\Query order(mixed $field, string $order = null) static 查询ORDER + * @method \think\db\Query orderRaw(string $field, array $bind = []) static 查询ORDER + * @method \think\db\Query cache(mixed $key = null , integer $expire = null) static 设置查询缓存 * @method mixed value(string $field) static 获取某个字段的值 * @method array column(string $field, string $key = '') static 获取某个列的值 - * @method Query view(mixed $join, mixed $field = null, mixed $on = null, string $type = 'INNER') static 视图查询 - * @method mixed find(mixed $data = []) static 查询单个记录 - * @method mixed select(mixed $data = []) static 查询多个记录 + * @method mixed find(mixed $data = null) static 查询单个记录 + * @method mixed select(mixed $data = null) static 查询多个记录 * @method integer insert(array $data, boolean $replace = false, boolean $getLastInsID = false, string $sequence = null) static 插入一条记录 * @method integer insertGetId(array $data, boolean $replace = false, string $sequence = null) static 插入一条记录并返回自增ID * @method integer insertAll(array $dataSet) static 插入多条记录 * @method integer update(array $data) static 更新记录 - * @method integer delete(mixed $data = []) static 删除记录 + * @method integer delete(mixed $data = null) static 删除记录 * @method boolean chunk(integer $count, callable $callback, string $column = null) static 分块获取数据 - * @method mixed query(string $sql, array $bind = [], boolean $fetch = false, boolean $master = false, mixed $class = false) static SQL查询 + * @method \Generator cursor(mixed $data = null) static 使用游标查找记录 + * @method mixed query(string $sql, array $bind = [], boolean $master = false, bool $pdo = false) static SQL查询 * @method integer execute(string $sql, array $bind = [], boolean $fetch = false, boolean $getLastInsID = false, string $sequence = null) static SQL执行 - * @method PaginatorCollection paginate(integer $listRows = 15, mixed $simple = false, array $config = []) static 分页查询 + * @method \think\Paginator paginate(integer $listRows = 15, mixed $simple = null, array $config = []) static 分页查询 * @method mixed transaction(callable $callback) static 执行数据库事务 + * @method void startTrans() static 启动事务 + * @method void commit() static 用于非自动提交状态下面的查询提交 + * @method void rollback() static 事务回滚 * @method boolean batchQuery(array $sqlArray) static 批处理执行SQL语句 + * @method string getLastInsID(string $sequence = null) static 获取最近插入的ID + * @method mixed getConfig(string $name = '') static 获取数据库的配置参数 */ class Db { - // 数据库连接实例 - private static $instance = []; - // 查询次数 + /** + * 当前数据库连接对象 + * @var Connection + */ + protected static $connection; + + /** + * 数据库配置 + * @var array + */ + protected static $config = []; + + /** + * 查询次数 + * @var integer + */ public static $queryTimes = 0; - // 执行次数 + + /** + * 执行次数 + * @var integer + */ public static $executeTimes = 0; /** - * 数据库初始化 并取得数据库类实例 - * @static + * 配置 * @access public - * @param mixed $config 连接配置 - * @param bool|string $name 连接标识 true 强制重新连接 - * @return \think\db\Connection - * @throws Exception + * @param mixed $config + * @return void */ - public static function connect($config = [], $name = false) + public static function init($config = []) { - if (false === $name) { - $name = md5(serialize($config)); + self::$config = $config; + + if (empty($config['query'])) { + self::$config['query'] = '\\think\\db\\Query'; } - if (true === $name || !isset(self::$instance[$name])) { - // 解析连接参数 支持数组和字符串 - $options = self::parseConfig($config); - if (empty($options['type'])) { - throw new \InvalidArgumentException('Underfined db type'); - } - $class = false !== strpos($options['type'], '\\') ? $options['type'] : '\\think\\db\\connector\\' . ucwords($options['type']); - // 记录初始化信息 - if (App::$debug) { - Log::record('[ DB ] INIT ' . $options['type'], 'info'); - } - if (true === $name) { - return new $class($options); - } else { - self::$instance[$name] = new $class($options); - } + } + + /** + * 获取数据库配置 + * @access public + * @param string $config 配置名称 + * @return mixed + */ + public static function getConfig($name = '') + { + if ('' === $name) { + return self::$config; } - return self::$instance[$name]; + + return isset(self::$config[$name]) ? self::$config[$name] : null; + } + + /** + * 切换数据库连接 + * @access public + * @param mixed $config 连接配置 + * @param bool|string $name 连接标识 true 强制重新连接 + * @param string $query 查询对象类名 + * @return mixed 返回查询对象实例 + * @throws Exception + */ + public static function connect($config = [], $name = false, $query = '') + { + // 解析配置参数 + $options = self::parseConfig($config ?: self::$config); + + $query = $query ?: $options['query']; + + // 创建数据库连接对象实例 + self::$connection = Connection::instance($options, $name); + + return new $query(self::$connection); } /** * 数据库连接参数解析 - * @static * @access private - * @param mixed $config + * @param mixed $config * @return array */ private static function parseConfig($config) { - if (empty($config)) { - $config = Config::get('database'); - } elseif (is_string($config) && false === strpos($config, '/')) { + if (is_string($config) && false === strpos($config, '/')) { // 支持读取配置参数 - $config = Config::get($config); + $config = isset(self::$config[$config]) ? self::$config[$config] : self::$config; } - if (is_string($config)) { - return self::parseDsn($config); - } else { - return $config; + + $result = is_string($config) ? self::parseDsnConfig($config) : $config; + + if (empty($result['query'])) { + $result['query'] = self::$config['query']; } + + return $result; } /** * DSN解析 * 格式: mysql://username:passwd@localhost:3306/DbName?param1=val1¶m2=val2#utf8 - * @static * @access private - * @param string $dsnStr + * @param string $dsnStr * @return array */ - private static function parseDsn($dsnStr) + private static function parseDsnConfig($dsnStr) { $info = parse_url($dsnStr); + if (!$info) { return []; } + $dsn = [ 'type' => $info['scheme'], 'username' => isset($info['user']) ? $info['user'] : '', @@ -138,13 +187,12 @@ class Db } else { $dsn['params'] = []; } + return $dsn; } - // 调用驱动类的方法 - public static function __callStatic($method, $params) + public static function __callStatic($method, $args) { - // 自动初始化数据库 - return call_user_func_array([self::connect(), $method], $params); + return call_user_func_array([static::connect(), $method], $args); } } diff --git a/library/think/Debug.php b/library/think/Debug.php index e36a764e7e939f78f59ed4bab5002c3dc7d4534b..8aec3c3b425d511b809e6198becb9b675e42609a 100644 --- a/library/think/Debug.php +++ b/library/think/Debug.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,165 +11,224 @@ namespace think; -use think\Config; -use think\exception\ClassNotFoundException; -use think\Log; -use think\Request; -use think\Response; +use think\model\Collection as ModelCollection; use think\response\Redirect; class Debug { - // 区间时间信息 - protected static $info = []; - // 区间内存信息 - protected static $mem = []; + /** + * 配置参数 + * @var array + */ + protected $config = []; + + /** + * 区间时间信息 + * @var array + */ + protected $info = []; + + /** + * 区间内存信息 + * @var array + */ + protected $mem = []; + + /** + * 应用对象 + * @var App + */ + protected $app; + + public function __construct(App $app, array $config = []) + { + $this->app = $app; + $this->config = $config; + } + + public static function __make(App $app, Config $config) + { + return new static($app, $config->pull('trace')); + } + + public function setConfig(array $config) + { + $this->config = array_merge($this->config, $config); + } /** * 记录时间(微秒)和内存使用情况 - * @param string $name 标记位置 - * @param mixed $value 标记值 留空则取当前 time 表示仅记录时间 否则同时记录时间和内存 - * @return mixed + * @access public + * @param string $name 标记位置 + * @param mixed $value 标记值 留空则取当前 time 表示仅记录时间 否则同时记录时间和内存 + * @return void */ - public static function remark($name, $value = '') + public function remark($name, $value = '') { // 记录时间和内存使用 - self::$info[$name] = is_float($value) ? $value : microtime(true); + $this->info[$name] = is_float($value) ? $value : microtime(true); + if ('time' != $value) { - self::$mem['mem'][$name] = is_float($value) ? $value : memory_get_usage(); - self::$mem['peak'][$name] = memory_get_peak_usage(); + $this->mem['mem'][$name] = is_float($value) ? $value : memory_get_usage(); + $this->mem['peak'][$name] = memory_get_peak_usage(); } } /** * 统计某个区间的时间(微秒)使用情况 - * @param string $start 开始标签 - * @param string $end 结束标签 - * @param integer|string $dec 小数位 + * @access public + * @param string $start 开始标签 + * @param string $end 结束标签 + * @param integer|string $dec 小数位 * @return integer */ - public static function getRangeTime($start, $end, $dec = 6) + public function getRangeTime($start, $end, $dec = 6) { - if (!isset(self::$info[$end])) { - self::$info[$end] = microtime(true); + if (!isset($this->info[$end])) { + $this->info[$end] = microtime(true); } - return number_format((self::$info[$end] - self::$info[$start]), $dec); + + return number_format(($this->info[$end] - $this->info[$start]), $dec); } /** * 统计从开始到统计时的时间(微秒)使用情况 - * @param integer|string $dec 小数位 + * @access public + * @param integer|string $dec 小数位 * @return integer */ - public static function getUseTime($dec = 6) + public function getUseTime($dec = 6) { - return number_format((microtime(true) - THINK_START_TIME), $dec); + return number_format((microtime(true) - $this->app->getBeginTime()), $dec); } /** * 获取当前访问的吞吐率情况 + * @access public * @return string */ - public static function getThroughputRate() + public function getThroughputRate() { - return number_format(1 / self::getUseTime(), 2) . 'req/s'; + return number_format(1 / $this->getUseTime(), 2) . 'req/s'; } /** * 记录区间的内存使用情况 - * @param string $start 开始标签 - * @param string $end 结束标签 - * @param integer|string $dec 小数位 + * @access public + * @param string $start 开始标签 + * @param string $end 结束标签 + * @param integer|string $dec 小数位 * @return string */ - public static function getRangeMem($start, $end, $dec = 2) + public function getRangeMem($start, $end, $dec = 2) { - if (!isset(self::$mem['mem'][$end])) { - self::$mem['mem'][$end] = memory_get_usage(); + if (!isset($this->mem['mem'][$end])) { + $this->mem['mem'][$end] = memory_get_usage(); } - $size = self::$mem['mem'][$end] - self::$mem['mem'][$start]; + + $size = $this->mem['mem'][$end] - $this->mem['mem'][$start]; $a = ['B', 'KB', 'MB', 'GB', 'TB']; $pos = 0; + while ($size >= 1024) { $size /= 1024; $pos++; } + return round($size, $dec) . " " . $a[$pos]; } /** * 统计从开始到统计时的内存使用情况 - * @param integer|string $dec 小数位 + * @access public + * @param integer|string $dec 小数位 * @return string */ - public static function getUseMem($dec = 2) + public function getUseMem($dec = 2) { - $size = memory_get_usage() - THINK_START_MEM; + $size = memory_get_usage() - $this->app->getBeginMem(); $a = ['B', 'KB', 'MB', 'GB', 'TB']; $pos = 0; + while ($size >= 1024) { $size /= 1024; $pos++; } + return round($size, $dec) . " " . $a[$pos]; } /** * 统计区间的内存峰值情况 - * @param string $start 开始标签 - * @param string $end 结束标签 - * @param integer|string $dec 小数位 - * @return mixed + * @access public + * @param string $start 开始标签 + * @param string $end 结束标签 + * @param integer|string $dec 小数位 + * @return string */ - public static function getMemPeak($start, $end, $dec = 2) + public function getMemPeak($start, $end, $dec = 2) { - if (!isset(self::$mem['peak'][$end])) { - self::$mem['peak'][$end] = memory_get_peak_usage(); + if (!isset($this->mem['peak'][$end])) { + $this->mem['peak'][$end] = memory_get_peak_usage(); } - $size = self::$mem['peak'][$end] - self::$mem['peak'][$start]; + + $size = $this->mem['peak'][$end] - $this->mem['peak'][$start]; $a = ['B', 'KB', 'MB', 'GB', 'TB']; $pos = 0; + while ($size >= 1024) { $size /= 1024; $pos++; } + return round($size, $dec) . " " . $a[$pos]; } /** * 获取文件加载信息 - * @param bool $detail 是否显示详细 + * @access public + * @param bool $detail 是否显示详细 * @return integer|array */ - public static function getFile($detail = false) + public function getFile($detail = false) { if ($detail) { $files = get_included_files(); $info = []; + foreach ($files as $key => $file) { $info[] = $file . ' ( ' . number_format(filesize($file) / 1024, 2) . ' KB )'; } + return $info; } + return count(get_included_files()); } /** * 浏览器友好的变量输出 - * @param mixed $var 变量 - * @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串 - * @param string $label 标签 默认为空 - * @param integer $flags htmlspecialchars flags + * @access public + * @param mixed $var 变量 + * @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串 + * @param string $label 标签 默认为空 + * @param integer $flags htmlspecialchars flags * @return void|string */ - public static function dump($var, $echo = true, $label = null, $flags = ENT_SUBSTITUTE) + public function dump($var, $echo = true, $label = null, $flags = ENT_SUBSTITUTE) { $label = (null === $label) ? '' : rtrim($label) . ':'; + if ($var instanceof Model || $var instanceof ModelCollection) { + $var = $var->toArray(); + } + ob_start(); var_dump($var); + $output = ob_get_clean(); $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output); - if (IS_CLI) { + + if (PHP_SAPI == 'cli') { $output = PHP_EOL . $label . $output . PHP_EOL; } else { if (!extension_loaded('xdebug')) { @@ -178,30 +237,25 @@ class Debug $output = '
' . $label . $output . '
'; } if ($echo) { - echo ($output); - return null; - } else { - return $output; + echo($output); + return; } + return $output; } - public static function inject(Response $response, &$content) + public function inject(Response $response, &$content) { - $config = Config::get('trace'); - $type = isset($config['type']) ? $config['type'] : 'Html'; - $request = Request::instance(); - $class = false !== strpos($type, '\\') ? $type : '\\think\\debug\\' . ucwords($type); + $config = $this->config; + $type = isset($config['type']) ? $config['type'] : 'Html'; + unset($config['type']); - if (class_exists($class)) { - $trace = new $class($config); - } else { - throw new ClassNotFoundException('class not exists:' . $class, $class); - } + + $trace = Loader::factory($type, '\\think\\debug\\', $config); if ($response instanceof Redirect) { //TODO 记录 } else { - $output = $trace->output($response, Log::getLog()); + $output = $trace->output($response, $this->app['log']->getLog()); if (is_string($output)) { // trace调试信息注入 $pos = strripos($content, ''); diff --git a/library/think/Env.php b/library/think/Env.php index a23d9925e335c33009eebbba986ce79e5c78d70b..ef5d9468d3fc51528c2b9d46ae524d48e32a36ee 100644 --- a/library/think/Env.php +++ b/library/think/Env.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,19 +13,97 @@ namespace think; class Env { + /** + * 环境变量数据 + * @var array + */ + protected $data = []; + + public function __construct() + { + $this->data = $_ENV; + } + + /** + * 读取环境变量定义文件 + * @access public + * @param string $file 环境变量定义文件 + * @return void + */ + public function load($file) + { + $env = parse_ini_file($file, true); + $this->set($env); + } + /** * 获取环境变量值 - * @param string $name 环境变量名(支持二级 .号分割) - * @param string $default 默认值 + * @access public + * @param string $name 环境变量名 + * @param mixed $default 默认值 * @return mixed */ - public static function get($name, $default = null) + public function get($name = null, $default = null) { - $result = getenv(ENV_PREFIX . strtoupper(str_replace('.', '_', $name))); - if (false !== $result) { - return $result; - } else { + if (is_null($name)) { + return $this->data; + } + + $name = strtoupper(str_replace('.', '_', $name)); + + if (isset($this->data[$name])) { + return $this->data[$name]; + } + + return $this->getEnv($name, $default); + } + + protected function getEnv($name, $default = null) + { + $result = getenv('PHP_' . $name); + + if (false === $result) { return $default; } + + if ('false' === $result) { + $result = false; + } elseif ('true' === $result) { + $result = true; + } + + if (!isset($this->data[$name])) { + $this->data[$name] = $result; + } + + return $result; + } + + /** + * 设置环境变量值 + * @access public + * @param string|array $env 环境变量 + * @param mixed $value 值 + * @return void + */ + public function set($env, $value = null) + { + if (is_array($env)) { + $env = array_change_key_case($env, CASE_UPPER); + + foreach ($env as $key => $val) { + if (is_array($val)) { + foreach ($val as $k => $v) { + $this->data[$key . '_' . strtoupper($k)] = $v; + } + } else { + $this->data[$key] = $val; + } + } + } else { + $name = strtoupper(str_replace('.', '_', $env)); + + $this->data[$name] = $value; + } } } diff --git a/library/think/Error.php b/library/think/Error.php index 28f758823275766a9dc7cedd4866e8d6b5400b31..ea3328eecf94cf6a98516e2b4fdedcafff8a5667 100644 --- a/library/think/Error.php +++ b/library/think/Error.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -18,8 +18,15 @@ use think\exception\ThrowableError; class Error { + /** + * 配置参数 + * @var array + */ + protected static $exceptionHandler; + /** * 注册异常处理 + * @access public * @return void */ public static function register() @@ -32,6 +39,7 @@ class Error /** * Exception Handler + * @access public * @param \Exception|\Throwable $e */ public static function appException($e) @@ -41,7 +49,8 @@ class Error } self::getExceptionHandler()->report($e); - if (IS_CLI) { + + if (PHP_SAPI == 'cli') { self::getExceptionHandler()->renderForConsole(new ConsoleOutput, $e); } else { self::getExceptionHandler()->render($e)->send(); @@ -50,26 +59,27 @@ class Error /** * Error Handler + * @access public * @param integer $errno 错误编号 * @param integer $errstr 详细错误信息 * @param string $errfile 出错的文件 * @param integer $errline 出错行号 - * @param array $errcontext * @throws ErrorException */ - public static function appError($errno, $errstr, $errfile = '', $errline = 0, $errcontext = []) + public static function appError($errno, $errstr, $errfile = '', $errline = 0) { - $exception = new ErrorException($errno, $errstr, $errfile, $errline, $errcontext); + $exception = new ErrorException($errno, $errstr, $errfile, $errline); if (error_reporting() & $errno) { // 将错误信息托管至 think\exception\ErrorException throw $exception; - } else { - self::getExceptionHandler()->report($exception); } + + self::getExceptionHandler()->report($exception); } /** * Shutdown Handler + * @access public */ public static function appShutdown() { @@ -81,12 +91,13 @@ class Error } // 写入日志 - Log::save(); + Container::get('log')->save(); } /** * 确定错误类型是否致命 * + * @access protected * @param int $type * @return bool */ @@ -95,23 +106,42 @@ class Error return in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE]); } + /** + * 设置异常处理类 + * + * @access public + * @param mixed $handle + * @return void + */ + public static function setExceptionHandler($handle) + { + self::$exceptionHandler = $handle; + } + /** * Get an instance of the exception handler. * + * @access public * @return Handle */ public static function getExceptionHandler() { static $handle; + if (!$handle) { // 异常处理handle - $class = Config::get('exception_handle'); - if ($class && class_exists($class) && is_subclass_of($class, "\\think\\exception\\Handle")) { + $class = self::$exceptionHandler; + + if ($class && is_string($class) && class_exists($class) && is_subclass_of($class, "\\think\\exception\\Handle")) { $handle = new $class; } else { $handle = new Handle; + if ($class instanceof \Closure) { + $handle->setRender($class); + } } } + return $handle; } } diff --git a/library/think/Exception.php b/library/think/Exception.php index ac6487647b97c1ec4c4dedd9115ed2cbf629dcb8..414a090ad988b26a79e3010e9a530c1b067a06af 100644 --- a/library/think/Exception.php +++ b/library/think/Exception.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -33,8 +33,9 @@ class Exception extends \Exception * key1 value1 * key2 value2 * - * @param string $label 数据分类,用于异常页面显示 - * @param array $data 需要显示的数据,必须为关联数组 + * @access protected + * @param string $label 数据分类,用于异常页面显示 + * @param array $data 需要显示的数据,必须为关联数组 */ final protected function setData($label, array $data) { @@ -44,11 +45,12 @@ class Exception extends \Exception /** * 获取异常额外Debug数据 * 主要用于输出到异常页面便于调试 + * @access public * @return array 由setData设置的Debug数据 */ final public function getData() { return $this->data; } - + } diff --git a/library/think/Facade.php b/library/think/Facade.php new file mode 100644 index 0000000000000000000000000000000000000000..f467e0f81344aa31a028590539140494963846e3 --- /dev/null +++ b/library/think/Facade.php @@ -0,0 +1,125 @@ + +// +---------------------------------------------------------------------- + +namespace think; + +class Facade +{ + /** + * 绑定对象 + * @var array + */ + protected static $bind = []; + + /** + * 始终创建新的对象实例 + * @var bool + */ + protected static $alwaysNewInstance; + + /** + * 绑定类的静态代理 + * @static + * @access public + * @param string|array $name 类标识 + * @param string $class 类名 + * @return object + */ + public static function bind($name, $class = null) + { + if (__CLASS__ != static::class) { + return self::__callStatic('bind', func_get_args()); + } + + if (is_array($name)) { + self::$bind = array_merge(self::$bind, $name); + } else { + self::$bind[$name] = $class; + } + } + + /** + * 创建Facade实例 + * @static + * @access protected + * @param string $class 类名或标识 + * @param array $args 变量 + * @param bool $newInstance 是否每次创建新的实例 + * @return object + */ + protected static function createFacade($class = '', $args = [], $newInstance = false) + { + $class = $class ?: static::class; + + $facadeClass = static::getFacadeClass(); + + if ($facadeClass) { + $class = $facadeClass; + } elseif (isset(self::$bind[$class])) { + $class = self::$bind[$class]; + } + + if (static::$alwaysNewInstance) { + $newInstance = true; + } + + return Container::getInstance()->make($class, $args, $newInstance); + } + + /** + * 获取当前Facade对应类名 + * @access protected + * @return string + */ + protected static function getFacadeClass() + {} + + /** + * 带参数实例化当前Facade类 + * @access public + * @return mixed + */ + public static function instance(...$args) + { + if (__CLASS__ != static::class) { + return self::createFacade('', $args); + } + } + + /** + * 调用类的实例 + * @access public + * @param string $class 类名或者标识 + * @param array|true $args 变量 + * @param bool $newInstance 是否每次创建新的实例 + * @return mixed + */ + public static function make($class, $args = [], $newInstance = false) + { + if (__CLASS__ != static::class) { + return self::__callStatic('make', func_get_args()); + } + + if (true === $args) { + // 总是创建新的实例化对象 + $newInstance = true; + $args = []; + } + + return self::createFacade($class, $args, $newInstance); + } + + // 调用实际类的方法 + public static function __callStatic($method, $params) + { + return call_user_func_array([static::createFacade(), $method], $params); + } +} diff --git a/library/think/File.php b/library/think/File.php index 43f3857519d038fc0a4c3a60f0bb7becaf790e41..e9985690c3dfe697156a8287016650d651716c48 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,7 +11,6 @@ namespace think; -use SplFileInfo; use SplFileObject; class File extends SplFileObject @@ -21,51 +20,85 @@ class File extends SplFileObject * @var string */ private $error = ''; - // 当前完整文件名 + + /** + * 当前完整文件名 + * @var string + */ protected $filename; - // 上传文件名 + + /** + * 上传文件名 + * @var string + */ protected $saveName; - // 文件上传命名规则 + + /** + * 上传文件命名规则 + * @var string + */ protected $rule = 'date'; - // 文件上传验证规则 + + /** + * 上传文件验证规则 + * @var array + */ protected $validate = []; - // 单元测试 + + /** + * 是否单元测试 + * @var bool + */ protected $isTest; - // 上传文件信息 - protected $info; - // 文件hash信息 + + /** + * 上传文件信息 + * @var array + */ + protected $info = []; + + /** + * 文件hash规则 + * @var array + */ protected $hash = []; public function __construct($filename, $mode = 'r') { parent::__construct($filename, $mode); - $this->filename = $this->getRealPath(); + + $this->filename = $this->getRealPath() ?: $this->getPathname(); } /** * 是否测试 + * @access public * @param bool $test 是否测试 * @return $this */ public function isTest($test = false) { $this->isTest = $test; + return $this; } /** * 设置上传信息 + * @access public * @param array $info 上传文件信息 * @return $this */ public function setUploadInfo($info) { $this->info = $info; + return $this; } /** * 获取上传文件的信息 + * @access public * @param string $name * @return array|string */ @@ -76,6 +109,7 @@ class File extends SplFileObject /** * 获取上传文件的文件名 + * @access public * @return string */ public function getSaveName() @@ -85,29 +119,35 @@ class File extends SplFileObject /** * 设置上传文件的保存文件名 + * @access public * @param string $saveName * @return $this */ public function setSaveName($saveName) { $this->saveName = $saveName; + return $this; } /** * 获取文件的哈希散列值 - * @return $string + * @access public + * @param string $type + * @return string */ public function hash($type = 'sha1') { if (!isset($this->hash[$type])) { $this->hash[$type] = hash_file($type, $this->filename); } + return $this->hash[$type]; } /** * 检查目录是否可写 + * @access protected * @param string $path 目录 * @return boolean */ @@ -119,46 +159,53 @@ class File extends SplFileObject if (mkdir($path, 0755, true)) { return true; - } else { - $this->error = "目录 {$path} 创建失败!"; - return false; } + + $this->error = ['directory {:path} creation failed', ['path' => $path]]; + return false; } /** * 获取文件类型信息 + * @access public * @return string */ public function getMime() { $finfo = finfo_open(FILEINFO_MIME_TYPE); + return finfo_file($finfo, $this->filename); } /** * 设置文件的命名规则 + * @access public * @param string $rule 文件命名规则 * @return $this */ public function rule($rule) { $this->rule = $rule; + return $this; } /** * 设置上传文件的验证规则 + * @access public * @param array $rule 验证规则 * @return $this */ public function validate($rule = []) { $this->validate = $rule; + return $this; } /** * 检测是否合法的上传文件 + * @access public * @return bool */ public function isValid() @@ -166,11 +213,13 @@ class File extends SplFileObject if ($this->isTest) { return is_file($this->filename); } + return is_uploaded_file($this->filename); } /** * 检测上传文件 + * @access public * @param array $rule 验证规则 * @return bool */ @@ -178,27 +227,10 @@ class File extends SplFileObject { $rule = $rule ?: $this->validate; - /* 检查文件大小 */ - if (isset($rule['size']) && !$this->checkSize($rule['size'])) { - $this->error = '上传文件大小不符!'; - return false; - } - - /* 检查文件Mime类型 */ - if (isset($rule['type']) && !$this->checkMime($rule['type'])) { - $this->error = '上传文件MIME类型不允许!'; - return false; - } - - /* 检查文件后缀 */ - if (isset($rule['ext']) && !$this->checkExt($rule['ext'])) { - $this->error = '上传文件后缀不允许'; - return false; - } - - /* 检查图像文件 */ - if (!$this->checkImg()) { - $this->error = '非法图像文件!'; + if ((isset($rule['size']) && !$this->checkSize($rule['size'])) + || (isset($rule['type']) && !$this->checkMime($rule['type'])) + || (isset($rule['ext']) && !$this->checkExt($rule['ext'])) + || !$this->checkImg()) { return false; } @@ -207,6 +239,7 @@ class File extends SplFileObject /** * 检测上传文件后缀 + * @access public * @param array|string $ext 允许后缀 * @return bool */ @@ -215,24 +248,32 @@ class File extends SplFileObject if (is_string($ext)) { $ext = explode(',', $ext); } + $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION)); + if (!in_array($extension, $ext)) { + $this->error = 'extensions to upload is not allowed'; return false; } + return true; } /** * 检测图像文件 + * @access public * @return bool */ public function checkImg() { $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION)); + /* 对图像文件进行严格检测 */ - if (in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']) && !in_array($this->getImageType($this->filename), [1, 2, 3, 4, 6])) { + if (in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']) && !in_array($this->getImageType($this->filename), [1, 2, 3, 4, 6, 13])) { + $this->error = 'illegal image files'; return false; } + return true; } @@ -241,27 +282,35 @@ class File extends SplFileObject { if (function_exists('exif_imagetype')) { return exif_imagetype($image); - } else { + } + + try { $info = getimagesize($image); - return $info[2]; + return $info ? $info[2] : false; + } catch (\Exception $e) { + return false; } } /** * 检测上传文件大小 + * @access public * @param integer $size 最大大小 * @return bool */ public function checkSize($size) { if ($this->getSize() > $size) { + $this->error = 'filesize not match'; return false; } + return true; } /** * 检测上传文件类型 + * @access public * @param array|string $mime 允许类型 * @return bool */ @@ -270,18 +319,22 @@ class File extends SplFileObject if (is_string($mime)) { $mime = explode(',', $mime); } + if (!in_array(strtolower($this->getMime()), $mime)) { + $this->error = 'mimetype to upload is not allowed'; return false; } + return true; } /** * 移动文件 + * @access public * @param string $path 保存路径 * @param string|bool $savename 保存的文件名 默认自动生成 * @param boolean $replace 同名文件是否覆盖 - * @return false|SplFileInfo false-失败 否则返回SplFileInfo实例 + * @return false|File false-失败 否则返回File实例 */ public function move($path, $savename = true, $replace = true) { @@ -293,7 +346,7 @@ class File extends SplFileObject // 检测合法性 if (!$this->isValid()) { - $this->error = '非法上传文件'; + $this->error = 'upload illegal files'; return false; } @@ -301,7 +354,8 @@ class File extends SplFileObject if (!$this->check()) { return false; } - $path = rtrim($path, DS) . DS; + + $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; // 文件保存命名规则 $saveName = $this->buildSaveName($savename); $filename = $path . $saveName; @@ -313,7 +367,7 @@ class File extends SplFileObject /* 不覆盖同名文件 */ if (!$replace && is_file($filename)) { - $this->error = '存在同名文件' . $filename; + $this->error = ['has the same filename: {:filename}', ['filename' => $filename]]; return false; } @@ -321,18 +375,21 @@ class File extends SplFileObject if ($this->isTest) { rename($this->filename, $filename); } elseif (!move_uploaded_file($this->filename, $filename)) { - $this->error = '文件上传保存错误!'; + $this->error = 'upload write error'; return false; } + // 返回 File对象实例 $file = new self($filename); $file->setSaveName($saveName); $file->setUploadInfo($this->info); + return $file; } /** * 获取保存文件名 + * @access protected * @param string|bool $savename 保存的文件名 默认自动生成 * @return string */ @@ -340,68 +397,94 @@ class File extends SplFileObject { if (true === $savename) { // 自动生成文件名 - if ($this->rule instanceof \Closure) { - $savename = call_user_func_array($this->rule, [$this]); - } else { - switch ($this->rule) { - case 'date': - $savename = date('Ymd') . DS . md5(microtime(true)); - break; - default: - if (in_array($this->rule, hash_algos())) { - $hash = $this->hash($this->rule); - $savename = substr($hash, 0, 2) . DS . substr($hash, 2); - } elseif (is_callable($this->rule)) { - $savename = call_user_func($this->rule); - } else { - $savename = date('Ymd') . DS . md5(microtime(true)); - } - } - } - } elseif ('' === $savename) { + $savename = $this->autoBuildName(); + } elseif ('' === $savename || false === $savename) { + // 保留原文件名 $savename = $this->getInfo('name'); } + if (!strpos($savename, '.')) { $savename .= '.' . pathinfo($this->getInfo('name'), PATHINFO_EXTENSION); } + + return $savename; + } + + /** + * 自动生成文件名 + * @access protected + * @return string + */ + protected function autoBuildName() + { + if ($this->rule instanceof \Closure) { + $savename = call_user_func_array($this->rule, [$this]); + } else { + switch ($this->rule) { + case 'date': + $savename = date('Ymd') . DIRECTORY_SEPARATOR . md5(microtime(true)); + break; + default: + if (in_array($this->rule, hash_algos())) { + $hash = $this->hash($this->rule); + $savename = substr($hash, 0, 2) . DIRECTORY_SEPARATOR . substr($hash, 2); + } elseif (is_callable($this->rule)) { + $savename = call_user_func($this->rule); + } else { + $savename = date('Ymd') . DIRECTORY_SEPARATOR . md5(microtime(true)); + } + } + } + return $savename; } /** * 获取错误代码信息 - * @param int $errorNo 错误号 + * @access private + * @param int $errorNo 错误号 */ private function error($errorNo) { switch ($errorNo) { case 1: case 2: - $this->error = '上传文件大小超过了最大值!'; + $this->error = 'upload File size exceeds the maximum value'; break; case 3: - $this->error = '文件只有部分被上传!'; + $this->error = 'only the portion of file is uploaded'; break; case 4: - $this->error = '没有文件被上传!'; + $this->error = 'no file to uploaded'; break; case 6: - $this->error = '找不到临时文件夹!'; + $this->error = 'upload temp dir not found'; break; case 7: - $this->error = '文件写入失败!'; + $this->error = 'file write error'; break; default: - $this->error = '未知上传错误!'; + $this->error = 'unknown upload error'; } } /** - * 获取错误信息 - * @return mixed + * 获取错误信息(支持多语言) + * @access public + * @return string */ public function getError() { - return $this->error; + $lang = Container::get('lang'); + + if (is_array($this->error)) { + list($msg, $vars) = $this->error; + } else { + $msg = $this->error; + $vars = []; + } + + return $lang->has($msg) ? $lang->get($msg, $vars) : $msg; } public function __call($method, $args) diff --git a/library/think/Hook.php b/library/think/Hook.php index 062ac962d6588fdc31efe2c48ca7e3eb6ffb0595..58791c815ce61b59f789344f6e47824a57de2d3f 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -1,9 +1,8 @@ app = $app; + } + + /** + * 指定入口方法名称 + * @access public + * @param string $name 方法名 + * @return $this + */ + public function portal($name) + { + self::$portal = $name; + return $this; + } + + /** + * 指定行为标识 便于调用 + * @access public + * @param string|array $name 行为标识 + * @param mixed $behavior 行为 + * @return $this + */ + public function alias($name, $behavior = null) + { + if (is_array($name)) { + $this->bind = array_merge($this->bind, $name); + } else { + $this->bind[$name] = $behavior; + } + + return $this; + } + + /** + * 动态添加行为扩展到某个标签 + * @access public + * @param string $tag 标签名称 + * @param mixed $behavior 行为名称 + * @param bool $first 是否放到开头执行 + * @return void + */ + public function add($tag, $behavior, $first = false) + { + isset($this->tags[$tag]) || $this->tags[$tag] = []; + + if (is_array($behavior) && !is_callable($behavior)) { + if (!array_key_exists('_overlay', $behavior)) { + $this->tags[$tag] = array_merge($this->tags[$tag], $behavior); + } else { + unset($behavior['_overlay']); + $this->tags[$tag] = $behavior; + } + } elseif ($first) { + array_unshift($this->tags[$tag], $behavior); + } else { + $this->tags[$tag][] = $behavior; + } + } + + /** + * 批量导入插件 + * @access public + * @param array $tags 插件信息 + * @param bool $recursive 是否递归合并 + * @return void + */ + public function import(array $tags, $recursive = true) + { + if ($recursive) { + foreach ($tags as $tag => $behavior) { + $this->add($tag, $behavior); + } + } else { + $this->tags = $tags + $this->tags; + } + } + + /** + * 获取插件信息 + * @access public + * @param string $tag 插件位置 留空获取全部 + * @return array + */ + public function get($tag = '') + { + if (empty($tag)) { + //获取全部的插件信息 + return $this->tags; + } + + return array_key_exists($tag, $this->tags) ? $this->tags[$tag] : []; + } + + /** + * 监听标签的行为 + * @access public + * @param string $tag 标签名称 + * @param mixed $params 传入参数 + * @param bool $once 只获取一个有效返回值 + * @return mixed + */ + public function listen($tag, $params = null, $once = false) + { + $results = []; + $tags = $this->get($tag); + + foreach ($tags as $key => $name) { + $results[$key] = $this->execTag($name, $tag, $params); + + if (false === $results[$key] || (!is_null($results[$key]) && $once)) { + break; + } + } + + return $once ? end($results) : $results; + } + + /** + * 执行行为 + * @access public + * @param mixed $class 行为 + * @param mixed $params 参数 + * @return mixed + */ + public function exec($class, $params = null) + { + if ($class instanceof \Closure || is_array($class)) { + $method = $class; + } else { + if (isset($this->bind[$class])) { + $class = $this->bind[$class]; + } + $method = [$class, self::$portal]; + } + + return $this->app->invoke($method, [$params]); + } + + /** + * 执行某个标签的行为 + * @access protected + * @param mixed $class 要执行的行为 + * @param string $tag 方法名(标签名) + * @param mixed $params 参数 + * @return mixed + */ + protected function execTag($class, $tag = '', $params = null) + { + $this->app->isDebug() && $this->app['debug']->remark('behavior_start', 'time'); + + $method = Loader::parseName($tag, 1, false); + + if ($class instanceof \Closure) { + $call = $class; + $class = 'Closure'; + } elseif (strpos($class, '::')) { + $call = $class; + } else { + $obj = Container::get($class); + + if (!is_callable([$obj, $method])) { + $method = self::$portal; + } + + $call = [$class, $method]; + $class = $class . '->' . $method; + } + + $result = $this->app->invoke($call, [$params]); + + if ($this->app->isDebug()) { + $debug = $this->app['debug']; + $debug->remark('behavior_end', 'time'); + $this->app->log('[ BEHAVIOR ] Run ' . $class . ' @' . $tag . ' [ RunTime:' . $debug->getRangeTime('behavior_start', 'behavior_end') . 's ]'); + } - private static $tags = []; - - /** - * 动态添加行为扩展到某个标签 - * @param string $tag 标签名称 - * @param mixed $behavior 行为名称 - * @param bool $first 是否放到开头执行 - * @return void - */ - public static function add($tag, $behavior, $first = false) - { - isset(self::$tags[$tag]) || self::$tags[$tag] = []; - if (is_array($behavior) && !is_callable($behavior)) { - if (!array_key_exists('_overlay', $behavior) || !$behavior['_overlay']) { - unset($behavior['_overlay']); - self::$tags[$tag] = array_merge(self::$tags[$tag], $behavior); - } else { - unset($behavior['_overlay']); - self::$tags[$tag] = $behavior; - } - } elseif ($first) { - array_unshift(self::$tags[$tag], $behavior); - } else { - self::$tags[$tag][] = $behavior; - } - } - - /** - * 批量导入插件 - * @param array $tags 插件信息 - * @param boolean $recursive 是否递归合并 - */ - public static function import(array $tags, $recursive = true) - { - if ($recursive) { - foreach ($tags as $tag => $behavior) { - self::add($tag, $behavior); - } - } else { - self::$tags = $tags + self::$tags; - } - } - - /** - * 获取插件信息 - * @param string $tag 插件位置 留空获取全部 - * @return array - */ - public static function get($tag = '') - { - if (empty($tag)) {//获取全部的插件信息 - return self::$tags; - } else { - return array_key_exists($tag, self::$tags) ? self::$tags[$tag] : []; - } - } - - /** - * 监听标签的行为 - * @param string $tag 标签名称 - * @param mixed $params 传入参数 - * @param mixed $extra 额外参数 - * @param bool $once 只获取一个有效返回值 - * @return mixed - */ - public static function listen($tag, &$params = null, $extra = null, $once = false) - { - $results = []; - $tags = static::get($tag); - foreach ($tags as $key => $name) { - $results[$key] = self::exec($name, $tag, $params, $extra); - if (false === $results[$key]) {// 如果返回false 则中断行为执行 - break; - } elseif (!is_null($results[$key]) && $once) { - break; - } - } - return $once ? end($results) : $results; - } - - /** - * 执行某个行为 - * @param mixed $class 要执行的行为 - * @param string $tag 方法名(标签名) - * @param Mixed $params 传人的参数 - * @param mixed $extra 额外参数 - * @return mixed - */ - public static function exec($class, $tag = '', &$params = null, $extra = null) - { - App::$debug && Debug::remark('behavior_start', 'time'); - if (is_callable($class)) { - $result = call_user_func_array($class, [ & $params, $extra]); - $class = 'Closure'; - } elseif (is_object($class)) { - $result = call_user_func_array([$class, $tag], [ & $params, $extra]); - $class = get_class($class); - } else { - $obj = new $class(); - $result = ($tag && is_callable([$obj, $tag])) ? $obj->$tag($params, $extra) : $obj->run($params, $extra); - } - if (App::$debug) { - Debug::remark('behavior_end', 'time'); - Log::record('[ BEHAVIOR ] Run ' . $class . ' @' . $tag . ' [ RunTime:' . Debug::getRangeTime('behavior_start', 'behavior_end') . 's ]', 'info'); - } - return $result; - } + return $result; + } } diff --git a/library/think/Lang.php b/library/think/Lang.php index 16e7f54558de8f60e22933b7ca3bd8ed3f46108d..5d8d9d99e9885044202668b54eb1c2e066983077 100644 --- a/library/think/Lang.php +++ b/library/think/Lang.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,116 +11,162 @@ namespace think; -use think\App; -use think\Cookie; -use think\Log; - class Lang { - // 语言数据 - private static $lang = []; - // 语言作用域 - private static $range = 'zh-cn'; - // 语言自动侦测的变量 - protected static $langDetectVar = 'lang'; - // 语言Cookie变量 - protected static $langCookieVar = 'think_var'; - // 语言Cookie的过期时间 - protected static $langCookieExpire = 3600; - // 允许语言列表 - protected static $allowLangList = []; + /** + * 多语言信息 + * @var array + */ + private $lang = []; + + /** + * 当前语言 + * @var string + */ + private $range = 'zh-cn'; + + /** + * 多语言自动侦测变量名 + * @var string + */ + protected $langDetectVar = 'lang'; + + /** + * 多语言cookie变量 + * @var string + */ + protected $langCookieVar = 'think_var'; + + /** + * 允许的多语言列表 + * @var array + */ + protected $allowLangList = []; + + /** + * Accept-Language转义为对应语言包名称 系统默认配置 + * @var string + */ + protected $acceptLanguage = [ + 'zh-hans-cn' => 'zh-cn', + ]; + + /** + * 应用对象 + * @var App + */ + protected $app; + + public function __construct(App $app) + { + $this->app = $app; + } // 设定当前的语言 - public static function range($range = '') + public function range($range = '') { if ('' == $range) { - return self::$range; + return $this->range; } else { - self::$range = $range; + $this->range = $range; } } /** * 设置语言定义(不区分大小写) - * @param string|array $name 语言变量 - * @param string $value 语言值 - * @param string $range 语言作用域 + * @access public + * @param string|array $name 语言变量 + * @param string $value 语言值 + * @param string $range 语言作用域 * @return mixed */ - public static function set($name, $value = null, $range = '') + public function set($name, $value = null, $range = '') { - $range = $range ?: self::$range; + $range = $range ?: $this->range; // 批量定义 - if (!isset(self::$lang[$range])) { - self::$lang[$range] = []; + if (!isset($this->lang[$range])) { + $this->lang[$range] = []; } + if (is_array($name)) { - return self::$lang[$range] = array_change_key_case($name) + self::$lang[$range]; - } else { - return self::$lang[$range][strtolower($name)] = $value; + return $this->lang[$range] = array_change_key_case($name) + $this->lang[$range]; } + + return $this->lang[$range][strtolower($name)] = $value; } /** * 加载语言定义(不区分大小写) - * @param string $file 语言文件 - * @param string $range 语言作用域 - * @return mixed + * @access public + * @param string|array $file 语言文件 + * @param string $range 语言作用域 + * @return array */ - public static function load($file, $range = '') + public function load($file, $range = '') { - $range = $range ?: self::$range; - if (!isset(self::$lang[$range])) { - self::$lang[$range] = []; + $range = $range ?: $this->range; + if (!isset($this->lang[$range])) { + $this->lang[$range] = []; } + // 批量定义 if (is_string($file)) { $file = [$file]; } + $lang = []; + foreach ($file as $_file) { if (is_file($_file)) { // 记录加载信息 - App::$debug && Log::record('[ LANG ] ' . $_file, 'info'); + $this->app->log('[ LANG ] ' . $_file); $_lang = include $_file; - $lang = array_change_key_case($_lang) + $lang; + if (is_array($_lang)) { + $lang = array_change_key_case($_lang) + $lang; + } } } + if (!empty($lang)) { - self::$lang[$range] = $lang + self::$lang[$range]; + $this->lang[$range] = $lang + $this->lang[$range]; } - return self::$lang[$range]; + + return $this->lang[$range]; } /** * 获取语言定义(不区分大小写) - * @param string|null $name 语言变量 - * @param array $vars 变量替换 - * @param string $range 语言作用域 - * @return mixed + * @access public + * @param string|null $name 语言变量 + * @param string $range 语言作用域 + * @return bool */ - public static function has($name, $range = '') + public function has($name, $range = '') { - $range = $range ?: self::$range; - return isset(self::$lang[$range][strtolower($name)]); + $range = $range ?: $this->range; + + return isset($this->lang[$range][strtolower($name)]); } /** * 获取语言定义(不区分大小写) - * @param string|null $name 语言变量 - * @param array $vars 变量替换 - * @param string $range 语言作用域 + * @access public + * @param string|null $name 语言变量 + * @param array $vars 变量替换 + * @param string $range 语言作用域 * @return mixed */ - public static function get($name = null, $vars = [], $range = '') + public function get($name = null, $vars = [], $range = '') { - $range = $range ?: self::$range; + $range = $range ?: $this->range; + // 空参数返回所有定义 if (empty($name)) { - return self::$lang[$range]; + return $this->lang[$range]; } + $key = strtolower($name); - $value = isset(self::$lang[$range][$key]) ? self::$lang[$range][$key] : $name; + $value = isset($this->lang[$range][$key]) ? $this->lang[$range][$key] : $name; // 变量解析 if (!empty($vars) && is_array($vars)) { @@ -141,79 +187,98 @@ class Lang } $value = str_replace($replace, $vars, $value); } - } + return $value; } /** * 自动侦测设置获取语言选择 + * @access public * @return string */ - public static function detect() + public function detect() { // 自动侦测设置获取语言选择 $langSet = ''; - if (isset($_GET[self::$langDetectVar])) { + + if (isset($_GET[$this->langDetectVar])) { // url中设置了语言变量 - $langSet = strtolower($_GET[self::$langDetectVar]); - Cookie::set(self::$langCookieVar, $langSet, self::$langCookieExpire); - } elseif (Cookie::get(self::$langCookieVar)) { - // 获取上次用户的选择 - $langSet = strtolower(Cookie::get(self::$langCookieVar)); + $langSet = strtolower($_GET[$this->langDetectVar]); + } elseif (isset($_COOKIE[$this->langCookieVar])) { + // Cookie中设置了语言变量 + $langSet = strtolower($_COOKIE[$this->langCookieVar]); } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // 自动侦测浏览器语言 preg_match('/^([a-z\d\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches); $langSet = strtolower($matches[1]); - Cookie::set(self::$langCookieVar, $langSet, self::$langCookieExpire); + if (isset($this->acceptLanguage[$langSet])) { + $langSet = $this->acceptLanguage[$langSet]; + } } - if (empty(self::$allowLangList) || in_array($langSet, self::$allowLangList)) { + + if (empty($this->allowLangList) || in_array($langSet, $this->allowLangList)) { // 合法的语言 - self::$range = $langSet ?: self::$range; + $this->range = $langSet ?: $this->range; } - if ('zh-hans-cn' == self::$range) { - self::$range = 'zh-cn'; - } - return self::$range; + + return $this->range; + } + + /** + * 设置当前语言到Cookie + * @access public + * @param string $lang 语言 + * @return void + */ + public function saveToCookie($lang = null) + { + $range = $lang ?: $this->range; + + $_COOKIE[$this->langCookieVar] = $range; } /** * 设置语言自动侦测的变量 - * @param string $var 变量名称 + * @access public + * @param string $var 变量名称 * @return void */ - public static function setLangDetectVar($var) + public function setLangDetectVar($var) { - self::$langDetectVar = $var; + $this->langDetectVar = $var; } /** * 设置语言的cookie保存变量 - * @param string $var 变量名称 + * @access public + * @param string $var 变量名称 * @return void */ - public static function setLangCookieVar($var) + public function setLangCookieVar($var) { - self::$langCookieVar = $var; + $this->langCookieVar = $var; } /** - * 设置语言的cookie的过期时间 - * @param string $expire 过期时间 + * 设置允许的语言列表 + * @access public + * @param array $list 语言列表 * @return void */ - public static function setLangCookieExpire($expire) + public function setAllowLangList(array $list) { - self::$langCookieExpire = $expire; + $this->allowLangList = $list; } /** - * 设置允许的语言列表 - * @param array $list 语言列表 + * 设置转义的语言列表 + * @access public + * @param array $list 语言列表 * @return void */ - public static function setAllowLangList($list) + public function setAcceptLanguage(array $list) { - self::$allowLangList = $list; + $this->acceptLanguage = array_merge($this->acceptLanguage, $list); } } diff --git a/library/think/Loader.php b/library/think/Loader.php index cfa0a2178a29e1fc96e236a476ef44e7138c4788..d807db6403ad25de7f9f4e612daf4096c3b6f68d 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -15,43 +15,117 @@ use think\exception\ClassNotFoundException; class Loader { - protected static $instance = []; - // 类名映射 - protected static $map = []; + /** + * 类名映射信息 + * @var array + */ + protected static $classMap = []; - // 命名空间别名 - protected static $namespaceAlias = []; + /** + * 类库别名 + * @var array + */ + protected static $classAlias = []; - // PSR-4 + /** + * PSR-4 + * @var array + */ private static $prefixLengthsPsr4 = []; private static $prefixDirsPsr4 = []; private static $fallbackDirsPsr4 = []; - // PSR-0 + /** + * PSR-0 + * @var array + */ private static $prefixesPsr0 = []; private static $fallbackDirsPsr0 = []; - // 自动加载的文件 - private static $autoloadFiles = []; + /** + * 需要加载的文件 + * @var array + */ + private static $files = []; - // 自动加载 - public static function autoload($class) + /** + * Composer安装路径 + * @var string + */ + private static $composerPath; + + // 获取应用根目录 + public static function getRootPath() { - // 检测命名空间别名 - if (!empty(self::$namespaceAlias)) { - $namespace = dirname($class); - if (isset(self::$namespaceAlias[$namespace])) { - $original = self::$namespaceAlias[$namespace] . '\\' . basename($class); - if (class_exists($original)) { - return class_alias($original, $class, false); + if ('cli' == PHP_SAPI) { + $scriptName = realpath($_SERVER['argv'][0]); + } else { + $scriptName = $_SERVER['SCRIPT_FILENAME']; + } + + $path = realpath(dirname($scriptName)); + + if (!is_file($path . DIRECTORY_SEPARATOR . 'think')) { + $path = dirname($path); + } + + return $path . DIRECTORY_SEPARATOR; + } + + // 注册自动加载机制 + public static function register($autoload = '') + { + // 注册系统自动加载 + spl_autoload_register($autoload ?: 'think\\Loader::autoload', true, true); + + $rootPath = self::getRootPath(); + + self::$composerPath = $rootPath . 'vendor' . DIRECTORY_SEPARATOR . 'composer' . DIRECTORY_SEPARATOR; + + // Composer自动加载支持 + if (is_dir(self::$composerPath)) { + if (is_file(self::$composerPath . 'autoload_static.php')) { + require self::$composerPath . 'autoload_static.php'; + + $declaredClass = get_declared_classes(); + $composerClass = array_pop($declaredClass); + + foreach (['prefixLengthsPsr4', 'prefixDirsPsr4', 'fallbackDirsPsr4', 'prefixesPsr0', 'fallbackDirsPsr0', 'classMap', 'files'] as $attr) { + if (property_exists($composerClass, $attr)) { + self::${$attr} = $composerClass::${$attr}; + } } + } else { + self::registerComposerLoader(self::$composerPath); } } + // 注册命名空间定义 + self::addNamespace([ + 'think' => __DIR__, + 'traits' => dirname(__DIR__) . DIRECTORY_SEPARATOR . 'traits', + ]); + + // 加载类库映射文件 + if (is_file($rootPath . 'runtime' . DIRECTORY_SEPARATOR . 'classmap.php')) { + self::addClassMap(__include_file($rootPath . 'runtime' . DIRECTORY_SEPARATOR . 'classmap.php')); + } + + // 自动加载extend目录 + self::addAutoLoadDir($rootPath . 'extend'); + } + + // 自动加载 + public static function autoload($class) + { + if (isset(self::$classAlias[$class])) { + return class_alias(self::$classAlias[$class], $class); + } + if ($file = self::findFile($class)) { // Win环境严格区分大小写 - if (IS_WIN && pathinfo($file, PATHINFO_FILENAME) != pathinfo(realpath($file), PATHINFO_FILENAME)) { + if (strpos(PHP_OS, 'WIN') !== false && pathinfo($file, PATHINFO_FILENAME) != pathinfo(realpath($file), PATHINFO_FILENAME)) { return false; } @@ -62,25 +136,26 @@ class Loader /** * 查找文件 - * @param $class - * @return bool + * @access private + * @param string $class + * @return string|false */ private static function findFile($class) { - if (!empty(self::$map[$class])) { + if (!empty(self::$classMap[$class])) { // 类库映射 - return self::$map[$class]; + return self::$classMap[$class]; } // 查找 PSR-4 - $logicalPathPsr4 = strtr($class, '\\', DS) . EXT; + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . '.php'; $first = $class[0]; if (isset(self::$prefixLengthsPsr4[$first])) { foreach (self::$prefixLengthsPsr4[$first] as $prefix => $length) { if (0 === strpos($class, $prefix)) { foreach (self::$prefixDirsPsr4[$prefix] as $dir) { - if (is_file($file = $dir . DS . substr($logicalPathPsr4, $length))) { + if (is_file($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) { return $file; } } @@ -90,7 +165,7 @@ class Loader // 查找 PSR-4 fallback dirs foreach (self::$fallbackDirsPsr4 as $dir) { - if (is_file($file = $dir . DS . $logicalPathPsr4)) { + if (is_file($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } @@ -99,17 +174,17 @@ class Loader if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) - . strtr(substr($logicalPathPsr4, $pos + 1), '_', DS); + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name - $logicalPathPsr0 = strtr($class, '_', DS) . EXT; + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . '.php'; } if (isset(self::$prefixesPsr0[$first])) { foreach (self::$prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { - if (is_file($file = $dir . DS . $logicalPathPsr0)) { + if (is_file($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } @@ -119,21 +194,21 @@ class Loader // 查找 PSR-0 fallback dirs foreach (self::$fallbackDirsPsr0 as $dir) { - if (is_file($file = $dir . DS . $logicalPathPsr0)) { + if (is_file($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } - return self::$map[$class] = false; + return self::$classMap[$class] = false; } // 注册classmap public static function addClassMap($class, $map = '') { if (is_array($class)) { - self::$map = array_merge(self::$map, $class); + self::$classMap = array_merge(self::$classMap, $class); } else { - self::$map[$class] = $map; + self::$classMap[$class] = $map; } } @@ -142,10 +217,10 @@ class Loader { if (is_array($namespace)) { foreach ($namespace as $prefix => $paths) { - self::addPsr4($prefix . '\\', rtrim($paths, DS), true); + self::addPsr4($prefix . '\\', rtrim($paths, DIRECTORY_SEPARATOR), true); } } else { - self::addPsr4($namespace . '\\', rtrim($path, DS), true); + self::addPsr4($namespace . '\\', rtrim($path, DIRECTORY_SEPARATOR), true); } } @@ -174,6 +249,7 @@ class Loader return; } + if ($prepend) { self::$prefixesPsr0[$first][$prefix] = array_merge( (array) $paths, @@ -209,6 +285,7 @@ class Loader if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } + self::$prefixLengthsPsr4[$prefix[0]][$prefix] = $length; self::$prefixDirsPsr4[$prefix] = (array) $paths; } elseif ($prepend) { @@ -226,310 +303,100 @@ class Loader } } - // 注册命名空间别名 - public static function addNamespaceAlias($namespace, $original = '') + // 注册自动加载类库目录 + public static function addAutoLoadDir($path) { - if (is_array($namespace)) { - self::$namespaceAlias = array_merge(self::$namespaceAlias, $namespace); - } else { - self::$namespaceAlias[$namespace] = $original; - } + self::$fallbackDirsPsr4[] = $path; } - // 注册自动加载机制 - public static function register($autoload = '') + // 注册类别名 + public static function addClassAlias($alias, $class = null) { - // 注册系统自动加载 - spl_autoload_register($autoload ?: 'think\\Loader::autoload', true, true); - // 注册命名空间定义 - self::addNamespace([ - 'think' => LIB_PATH . 'think' . DS, - 'behavior' => LIB_PATH . 'behavior' . DS, - 'traits' => LIB_PATH . 'traits' . DS, - ]); - // 加载类库映射文件 - if (is_file(RUNTIME_PATH . 'classmap' . EXT)) { - self::addClassMap(__include_file(RUNTIME_PATH . 'classmap' . EXT)); - } - - // Composer自动加载支持 - if (is_dir(VENDOR_PATH . 'composer')) { - self::registerComposerLoader(); + if (is_array($alias)) { + self::$classAlias = array_merge(self::$classAlias, $alias); + } else { + self::$classAlias[$alias] = $class; } - - // 自动加载extend目录 - self::$fallbackDirsPsr4[] = rtrim(EXTEND_PATH, DS); } // 注册composer自动加载 - private static function registerComposerLoader() + public static function registerComposerLoader($composerPath) { - if (is_file(VENDOR_PATH . 'composer/autoload_namespaces.php')) { - $map = require VENDOR_PATH . 'composer/autoload_namespaces.php'; + if (is_file($composerPath . 'autoload_namespaces.php')) { + $map = require $composerPath . 'autoload_namespaces.php'; foreach ($map as $namespace => $path) { self::addPsr0($namespace, $path); } } - if (is_file(VENDOR_PATH . 'composer/autoload_psr4.php')) { - $map = require VENDOR_PATH . 'composer/autoload_psr4.php'; + if (is_file($composerPath . 'autoload_psr4.php')) { + $map = require $composerPath . 'autoload_psr4.php'; foreach ($map as $namespace => $path) { self::addPsr4($namespace, $path); } } - if (is_file(VENDOR_PATH . 'composer/autoload_classmap.php')) { - $classMap = require VENDOR_PATH . 'composer/autoload_classmap.php'; + if (is_file($composerPath . 'autoload_classmap.php')) { + $classMap = require $composerPath . 'autoload_classmap.php'; if ($classMap) { self::addClassMap($classMap); } } - if (is_file(VENDOR_PATH . 'composer/autoload_files.php')) { - $includeFiles = require VENDOR_PATH . 'composer/autoload_files.php'; - foreach ($includeFiles as $fileIdentifier => $file) { - if (empty(self::$autoloadFiles[$fileIdentifier])) { - __require_file($file); - self::$autoloadFiles[$fileIdentifier] = true; - } - } - } - } - - /** - * 导入所需的类库 同java的Import 本函数有缓存功能 - * @param string $class 类库命名空间字符串 - * @param string $baseUrl 起始路径 - * @param string $ext 导入的文件扩展名 - * @return boolean - */ - public static function import($class, $baseUrl = '', $ext = EXT) - { - static $_file = []; - $key = $class . $baseUrl; - $class = str_replace(['.', '#'], [DS, '.'], $class); - if (isset($_file[$key])) { - return true; - } - - if (empty($baseUrl)) { - list($name, $class) = explode(DS, $class, 2); - - if (isset(self::$prefixDirsPsr4[$name . '\\'])) { - // 注册的命名空间 - $baseUrl = self::$prefixDirsPsr4[$name . '\\']; - } elseif ('@' == $name) { - //加载当前模块应用类库 - $baseUrl = App::$modulePath; - } elseif (is_dir(EXTEND_PATH . $name)) { - $baseUrl = EXTEND_PATH . $name . DS; - } else { - // 加载其它模块的类库 - $baseUrl = APP_PATH . $name . DS; - } - } elseif (substr($baseUrl, -1) != DS) { - $baseUrl .= DS; - } - // 如果类存在 则导入类库文件 - if (is_array($baseUrl)) { - foreach ($baseUrl as $path) { - $filename = $path . DS . $class . $ext; - if (is_file($filename)) { - break; - } - } - } else { - $filename = $baseUrl . $class . $ext; - } - - if (!empty($filename) && is_file($filename)) { - // 开启调试模式Win环境严格区分大小写 - if (IS_WIN && pathinfo($filename, PATHINFO_FILENAME) != pathinfo(realpath($filename), PATHINFO_FILENAME)) { - return false; - } - __include_file($filename); - $_file[$key] = true; - return true; - } - return false; - } - - /** - * 实例化(分层)模型 - * @param string $name Model名称 - * @param string $layer 业务层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @param string $common 公共模块名 - * @return Object - * @throws ClassNotFoundException - */ - public static function model($name = '', $layer = 'model', $appendSuffix = false, $common = 'common') - { - if (isset(self::$instance[$name . $layer])) { - return self::$instance[$name . $layer]; - } - if (strpos($name, '/')) { - list($module, $name) = explode('/', $name, 2); - } else { - $module = Request::instance()->module(); - } - $class = self::parseClass($module, $layer, $name, $appendSuffix); - if (class_exists($class)) { - $model = new $class(); - } else { - $class = str_replace('\\' . $module . '\\', '\\' . $common . '\\', $class); - if (class_exists($class)) { - $model = new $class(); - } else { - throw new ClassNotFoundException('class not exists:' . $class, $class); - } - } - self::$instance[$name . $layer] = $model; - return $model; - } - - /** - * 实例化(分层)控制器 格式:[模块名/]控制器名 - * @param string $name 资源地址 - * @param string $layer 控制层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @param string $empty 空控制器名称 - * @return Object|false - * @throws ClassNotFoundException - */ - public static function controller($name, $layer = 'controller', $appendSuffix = false, $empty = '') - { - if (strpos($name, '/')) { - list($module, $name) = explode('/', $name); - } else { - $module = Request::instance()->module(); - } - $class = self::parseClass($module, $layer, $name, $appendSuffix); - if (class_exists($class)) { - return App::invokeClass($class); - } elseif ($empty && class_exists($emptyClass = self::parseClass($module, $layer, $empty, $appendSuffix))) { - return new $emptyClass(Request::instance()); - } - } - - /** - * 实例化验证类 格式:[模块名/]验证器名 - * @param string $name 资源地址 - * @param string $layer 验证层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @param string $common 公共模块名 - * @return Object|false - * @throws ClassNotFoundException - */ - public static function validate($name = '', $layer = 'validate', $appendSuffix = false, $common = 'common') - { - $name = $name ?: Config::get('default_validate'); - if (empty($name)) { - return new Validate; + if (is_file($composerPath . 'autoload_files.php')) { + self::$files = require $composerPath . 'autoload_files.php'; } - - if (isset(self::$instance[$name . $layer])) { - return self::$instance[$name . $layer]; - } - if (strpos($name, '/')) { - list($module, $name) = explode('/', $name); - } else { - $module = Request::instance()->module(); - } - $class = self::parseClass($module, $layer, $name, $appendSuffix); - if (class_exists($class)) { - $validate = new $class; - } else { - $class = str_replace('\\' . $module . '\\', '\\' . $common . '\\', $class); - if (class_exists($class)) { - $validate = new $class; - } else { - throw new ClassNotFoundException('class not exists:' . $class, $class); - } - } - self::$instance[$name . $layer] = $validate; - return $validate; } - /** - * 数据库初始化 并取得数据库类实例 - * @param mixed $config 数据库配置 - * @param bool|string $name 连接标识 true 强制重新连接 - * @return \think\db\Connection - */ - public static function db($config = [], $name = false) + // 加载composer autofile文件 + public static function loadComposerAutoloadFiles() { - return Db::connect($config, $name); - } + foreach (self::$files as $fileIdentifier => $file) { + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + __require_file($file); - /** - * 远程调用模块的操作方法 参数格式 [模块/控制器/]操作 - * @param string $url 调用地址 - * @param string|array $vars 调用参数 支持字符串和数组 - * @param string $layer 要调用的控制层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @return mixed - */ - public static function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) - { - $info = pathinfo($url); - $action = $info['basename']; - $module = '.' != $info['dirname'] ? $info['dirname'] : Request::instance()->controller(); - $class = self::controller($module, $layer, $appendSuffix); - if ($class) { - if (is_scalar($vars)) { - if (strpos($vars, '=')) { - parse_str($vars, $vars); - } else { - $vars = [$vars]; - } + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; } - return App::invokeMethod([$class, $action . Config::get('action_suffix')], $vars); } } /** * 字符串命名风格转换 * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格 - * @param string $name 字符串 - * @param integer $type 转换类型 + * @access public + * @param string $name 字符串 + * @param integer $type 转换类型 + * @param bool $ucfirst 首字母是否大写(驼峰规则) * @return string */ - public static function parseName($name, $type = 0) + public static function parseName($name, $type = 0, $ucfirst = true) { if ($type) { - return ucfirst(preg_replace_callback('/_([a-zA-Z])/', function ($match) { + $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) { return strtoupper($match[1]); - }, $name)); - } else { - return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); + }, $name); + return $ucfirst ? ucfirst($name) : lcfirst($name); } - } - /** - * 解析应用类的类名 - * @param string $module 模块名 - * @param string $layer 层名 controller model ... - * @param string $name 类名 - * @param bool $appendSuffix - * @return string - */ - public static function parseClass($module, $layer, $name, $appendSuffix = false) - { - $name = str_replace(['/', '.'], '\\', $name); - $array = explode('\\', $name); - $class = self::parseName(array_pop($array), 1) . (App::$suffix || $appendSuffix ? ucfirst($layer) : ''); - $path = $array ? implode('\\', $array) . '\\' : ''; - return App::$namespace . '\\' . ($module ? $module . '\\' : '') . $layer . '\\' . $path . $class; + return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); } /** - * 初始化类的实例 - * @return void + * 创建工厂对象实例 + * @access public + * @param string $name 工厂类名 + * @param string $namespace 默认命名空间 + * @return mixed */ - public static function clearInstance() + public static function factory($name, $namespace = '', ...$args) { - self::$instance = []; + $class = false !== strpos($name, '\\') ? $name : $namespace . ucwords($name); + + if (class_exists($class)) { + return Container::getInstance()->invokeClass($class, $args); + } else { + throw new ClassNotFoundException('class not exists:' . $class, $class); + } } } diff --git a/library/think/Log.php b/library/think/Log.php index 5fd1631a55f2b04eb6c853071cd303a003fc9cc7..b63233cd65c0c602d7890add889ba91d52945a1d 100644 --- a/library/think/Log.php +++ b/library/think/Log.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,190 +11,371 @@ namespace think; -use think\exception\ClassNotFoundException; - -/** - * Class Log - * @package think - * - * @method void log($msg) static - * @method void error($msg) static - * @method void info($msg) static - * @method void sql($msg) static - * @method void notice($msg) static - * @method void alert($msg) static - */ -class Log +class Log implements LoggerInterface { - const LOG = 'log'; - const ERROR = 'error'; - const INFO = 'info'; - const SQL = 'sql'; - const NOTICE = 'notice'; - const ALERT = 'alert'; - - // 日志信息 - protected static $log = []; - // 配置参数 - protected static $config = []; - // 日志类型 - protected static $type = ['log', 'error', 'info', 'sql', 'notice', 'alert']; - // 日志写入驱动 - protected static $driver; - - // 当前日志授权key - protected static $key; + const EMERGENCY = 'emergency'; + const ALERT = 'alert'; + const CRITICAL = 'critical'; + const ERROR = 'error'; + const WARNING = 'warning'; + const NOTICE = 'notice'; + const INFO = 'info'; + const DEBUG = 'debug'; + const SQL = 'sql'; + + /** + * 日志信息 + * @var array + */ + protected $log = []; + + /** + * 配置参数 + * @var array + */ + protected $config = []; + + /** + * 日志写入驱动 + * @var object + */ + protected $driver; + + /** + * 日志授权key + * @var string + */ + protected $key; + + /** + * 是否允许日志写入 + * @var bool + */ + protected $allowWrite = true; + + /** + * 应用对象 + * @var App + */ + protected $app; + + public function __construct(App $app) + { + $this->app = $app; + } + + public static function __make(App $app, Config $config) + { + return (new static($app))->init($config->pull('log')); + } /** * 日志初始化 - * @param array $config + * @access public + * @param array $config + * @return $this */ - public static function init($config = []) + public function init($config = []) { - $type = isset($config['type']) ? $config['type'] : 'File'; - $class = false !== strpos($type, '\\') ? $type : '\\think\\log\\driver\\' . ucwords($type); - self::$config = $config; + $type = isset($config['type']) ? $config['type'] : 'File'; + + $this->config = $config; + unset($config['type']); - if (class_exists($class)) { - self::$driver = new $class($config); - } else { - throw new ClassNotFoundException('class not exists:' . $class, $class); + + if (!empty($config['close'])) { + $this->allowWrite = false; } - // 记录初始化信息 - App::$debug && Log::record('[ LOG ] INIT ' . $type, 'info'); + + $this->driver = Loader::factory($type, '\\think\\log\\driver\\', $config); + + return $this; } /** * 获取日志信息 - * @param string $type 信息类型 + * @access public + * @param string $type 信息类型 * @return array */ - public static function getLog($type = '') + public function getLog($type = '') { - return $type ? self::$log[$type] : self::$log; + return $type ? $this->log[$type] : $this->log; } /** - * 记录调试信息 - * @param mixed $msg 调试信息 - * @param string $type 信息类型 - * @return void + * 记录日志信息 + * @access public + * @param mixed $msg 日志信息 + * @param string $type 日志级别 + * @param array $context 替换内容 + * @return $this */ - public static function record($msg, $type = 'log') + public function record($msg, $type = 'info', array $context = []) { - self::$log[$type][] = $msg; + if (!$this->allowWrite) { + return; + } + + if (is_string($msg) && !empty($context)) { + $replace = []; + foreach ($context as $key => $val) { + $replace['{' . $key . '}'] = $val; + } + + $msg = strtr($msg, $replace); + } + + if (PHP_SAPI == 'cli') { + // 命令行日志实时写入 + $this->write($msg, $type, true); + } else { + $this->log[$type][] = $msg; + } + + return $this; } /** * 清空日志信息 - * @return void + * @access public + * @return $this */ - public static function clear() + public function clear() { - self::$log = []; + $this->log = []; + + return $this; } /** * 当前日志记录的授权key - * @param string $key 授权key - * @return void + * @access public + * @param string $key 授权key + * @return $this */ - public static function key($key) + public function key($key) { - self::$key = $key; + $this->key = $key; + + return $this; } /** * 检查日志写入权限 - * @param array $config 当前日志配置参数 + * @access public + * @param array $config 当前日志配置参数 * @return bool */ - public static function check($config) + public function check($config) { - if (self::$key && !empty($config['allow_key']) && !in_array(self::$key, $config['allow_key'])) { + if ($this->key && !empty($config['allow_key']) && !in_array($this->key, $config['allow_key'])) { return false; } + return true; } + /** + * 关闭本次请求日志写入 + * @access public + * @return $this + */ + public function close() + { + $this->allowWrite = false; + $this->log = []; + + return $this; + } + /** * 保存调试信息 + * @access public * @return bool */ - public static function save() + public function save() { - if (!empty(self::$log)) { - if (is_null(self::$driver)) { - self::init(Config::get('log')); - } + if (empty($this->log) || !$this->allowWrite) { + return true; + } - if (!self::check(self::$config)) { - // 检测日志写入权限 - return false; - } + if (!$this->check($this->config)) { + // 检测日志写入权限 + return false; + } - if (empty(self::$config['level'])) { - // 获取全部日志 - $log = self::$log; - } else { - // 记录允许级别 - $log = []; - foreach (self::$config['level'] as $level) { - if (isset(self::$log[$level])) { - $log[$level] = self::$log[$level]; - } + if (empty($this->config['level'])) { + // 获取全部日志 + $log = $this->log; + if (!$this->app->isDebug() && isset($log['debug'])) { + unset($log['debug']); + } + } else { + // 记录允许级别 + $log = []; + foreach ($this->config['level'] as $level) { + if (isset($this->log[$level])) { + $log[$level] = $this->log[$level]; } } + } - $result = self::$driver->save($log); - if ($result) { - self::$log = []; - } + $result = $this->driver->save($log, true); - return $result; + if ($result) { + $this->log = []; } - return true; + + return $result; } /** * 实时写入日志信息 并支持行为 - * @param mixed $msg 调试信息 - * @param string $type 信息类型 - * @param bool $force 是否强制写入 + * @access public + * @param mixed $msg 调试信息 + * @param string $type 日志级别 + * @param bool $force 是否强制写入 * @return bool */ - public static function write($msg, $type = 'log', $force = false) + public function write($msg, $type = 'info', $force = false) { // 封装日志信息 - if (true === $force || empty(self::$config['level'])) { - $log[$type][] = $msg; - } elseif (in_array($type, self::$config['level'])) { + if (empty($this->config['level'])) { + $force = true; + } + + if (true === $force || in_array($type, $this->config['level'])) { $log[$type][] = $msg; } else { return false; } // 监听log_write - Hook::listen('log_write', $log); - if (is_null(self::$driver)) { - self::init(Config::get('log')); - } + $this->app['hook']->listen('log_write', $log); + // 写入日志 - return self::$driver->save($log); + return $this->driver->save($log, false); } /** - * 静态调用 - * @param $method - * @param $args - * @return mixed + * 记录日志信息 + * @access public + * @param string $level 日志级别 + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void */ - public static function __callStatic($method, $args) + public function log($level, $message, array $context = []) { - if (in_array($method, self::$type)) { - array_push($args, $method); - return call_user_func_array('\\think\\Log::record', $args); - } + $this->record($message, $level, $context); + } + + /** + * 记录emergency信息 + * @access public + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void + */ + public function emergency($message, array $context = []) + { + $this->log(__FUNCTION__, $message, $context); + } + + /** + * 记录警报信息 + * @access public + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void + */ + public function alert($message, array $context = []) + { + $this->log(__FUNCTION__, $message, $context); + } + + /** + * 记录紧急情况 + * @access public + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void + */ + public function critical($message, array $context = []) + { + $this->log(__FUNCTION__, $message, $context); + } + + /** + * 记录错误信息 + * @access public + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void + */ + public function error($message, array $context = []) + { + $this->log(__FUNCTION__, $message, $context); + } + + /** + * 记录warning信息 + * @access public + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void + */ + public function warning($message, array $context = []) + { + $this->log(__FUNCTION__, $message, $context); + } + + /** + * 记录notice信息 + * @access public + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void + */ + public function notice($message, array $context = []) + { + $this->log(__FUNCTION__, $message, $context); } + /** + * 记录一般信息 + * @access public + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void + */ + public function info($message, array $context = []) + { + $this->log(__FUNCTION__, $message, $context); + } + + /** + * 记录调试信息 + * @access public + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void + */ + public function debug($message, array $context = []) + { + $this->log(__FUNCTION__, $message, $context); + } + + /** + * 记录sql信息 + * @access public + * @param mixed $message 日志信息 + * @param array $context 替换内容 + * @return void + */ + public function sql($message, array $context = []) + { + $this->log(__FUNCTION__, $message, $context); + } } diff --git a/library/think/Middleware.php b/library/think/Middleware.php new file mode 100644 index 0000000000000000000000000000000000000000..4814fdb99b72a9278506db93268dc9b05963c0f6 --- /dev/null +++ b/library/think/Middleware.php @@ -0,0 +1,189 @@ + +// +---------------------------------------------------------------------- + +namespace think; + +use InvalidArgumentException; +use LogicException; +use think\exception\HttpResponseException; + +class Middleware +{ + protected $queue = []; + protected $app; + protected $config = [ + 'default_namespace' => 'app\\http\\middleware\\', + ]; + + public function __construct(App $app, array $config = []) + { + $this->app = $app; + $this->config = array_merge($this->config, $config); + } + + public static function __make(App $app, Config $config) + { + return new static($app, $config->pull('middleware')); + } + + public function setConfig(array $config) + { + $this->config = array_merge($this->config, $config); + } + + /** + * 导入中间件 + * @access public + * @param array $middlewares + * @param string $type 中间件类型 + */ + public function import(array $middlewares = [], $type = 'route') + { + foreach ($middlewares as $middleware) { + $this->add($middleware, $type); + } + } + + /** + * 注册中间件 + * @access public + * @param mixed $middleware + * @param string $type 中间件类型 + */ + public function add($middleware, $type = 'route') + { + if (is_null($middleware)) { + return; + } + + $middleware = $this->buildMiddleware($middleware, $type); + + if ($middleware) { + $this->queue[$type][] = $middleware; + } + } + + /** + * 注册控制器中间件 + * @access public + * @param mixed $middleware + */ + public function controller($middleware) + { + return $this->add($middleware, 'controller'); + } + + /** + * 移除中间件 + * @access public + * @param mixed $middleware + * @param string $type 中间件类型 + */ + public function unshift($middleware, $type = 'route') + { + if (is_null($middleware)) { + return; + } + + $middleware = $this->buildMiddleware($middleware, $type); + + if ($middleware) { + array_unshift($this->queue[$type], $middleware); + } + } + + /** + * 获取注册的中间件 + * @access public + * @param string $type 中间件类型 + */ + public function all($type = 'route') + { + return $this->queue[$type] ?: []; + } + + /** + * 中间件调度 + * @access public + * @param Request $request + * @param string $type 中间件类型 + */ + public function dispatch(Request $request, $type = 'route') + { + return call_user_func($this->resolve($type), $request); + } + + /** + * 解析中间件 + * @access protected + * @param mixed $middleware + * @param string $type 中间件类型 + */ + protected function buildMiddleware($middleware, $type = 'route') + { + if (is_array($middleware)) { + list($middleware, $param) = $middleware; + } + + if ($middleware instanceof \Closure) { + return [$middleware, isset($param) ? $param : null]; + } + + if (!is_string($middleware)) { + throw new InvalidArgumentException('The middleware is invalid'); + } + + if (false === strpos($middleware, '\\')) { + if (isset($this->config[$middleware])) { + $middleware = $this->config[$middleware]; + } else { + $middleware = $this->config['default_namespace'] . $middleware; + } + } + + if (is_array($middleware)) { + return $this->import($middleware, $type); + } + + if (strpos($middleware, ':')) { + list($middleware, $param) = explode(':', $middleware, 2); + } + + return [[$this->app->make($middleware), 'handle'], isset($param) ? $param : null]; + } + + protected function resolve($type = 'route') + { + return function (Request $request) use ($type) { + + $middleware = array_shift($this->queue[$type]); + + if (null === $middleware) { + throw new InvalidArgumentException('The queue was exhausted, with no response returned'); + } + + list($call, $param) = $middleware; + + try { + $response = call_user_func_array($call, [$request, $this->resolve($type), $param]); + } catch (HttpResponseException $exception) { + $response = $exception->getResponse(); + } + + if (!$response instanceof Response) { + throw new LogicException('The middleware must return Response instance'); + } + + return $response; + }; + } + +} diff --git a/library/think/Model.php b/library/think/Model.php index f062e3c5c7089643969088f9665ef6591bdecddc..98d29eb4cd2bc2148548e0f8c2a0a810fc044db6 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,107 +12,121 @@ namespace think; use InvalidArgumentException; -use think\Cache; -use think\Config; -use think\Db; use think\db\Query; -use think\Exception; -use think\Exception\ValidateException; -use think\Loader; -use think\model\Relation; -use think\paginator\Collection as PaginatorCollection; /** * Class Model * @package think - * @method static PaginatorCollection paginate(integer $listRows = 15, boolean $simple = false, array $config = []) 分页查询 - * @method static mixed value($field, $default = null) 得到某个字段的值 - * @method static array column($field, $key = '') 得到某个列的数组 - * @method static integer count($field = '*') COUNT查询 - * @method static integer sum($field = '*') SUM查询 - * @method static integer min($field = '*') MIN查询 - * @method static integer max($field = '*') MAX查询 - * @method static integer avg($field = '*') AVG查询 - * @method static setField($field, $value = '') - * @method static Query where($field, $op = null, $condition = null) 指定AND查询条件 - * @method static static findOrFail($data = null) 查找单条记录 如果不存在则抛出异常 - * + * @mixin Query */ abstract class Model implements \JsonSerializable, \ArrayAccess { - // 数据库对象池 - protected static $links = []; - // 数据库配置 + use model\concern\Attribute; + use model\concern\RelationShip; + use model\concern\ModelEvent; + use model\concern\TimeStamp; + use model\concern\Conversion; + + /** + * 是否存在数据 + * @var bool + */ + private $exists = false; + + /** + * 是否Replace + * @var bool + */ + private $replace = false; + + /** + * 是否强制更新所有数据 + * @var bool + */ + private $force = false; + + /** + * 更新条件 + * @var array + */ + private $updateWhere; + + /** + * 数据库配置信息 + * @var array|string + */ protected $connection = []; - // 数据库查询对象 + + /** + * 数据库查询对象类名 + * @var string + */ protected $query; - // 当前模型名称 + + /** + * 模型名称 + * @var string + */ protected $name; - // 数据表名称 + + /** + * 数据表名称 + * @var string + */ protected $table; - // 当前类名称 - protected $class; - // 回调事件 - private static $event = []; - // 错误信息 - protected $error; - // 字段验证规则 - protected $validate; - // 数据表主键 复合主键使用数组定义 不设置则自动获取 - protected $pk; - // 数据表字段信息 留空则自动获取 - protected $field = []; - // 只读字段 - protected $readonly = []; - // 显示属性 - protected $visible = []; - // 隐藏属性 - protected $hidden = []; - // 追加属性 - protected $append = []; - // 数据信息 - protected $data = []; - // 记录改变字段 - protected $change = []; - - // 保存自动完成列表 + + /** + * 写入自动完成定义 + * @var array + */ protected $auto = []; - // 新增自动完成列表 + + /** + * 新增自动完成定义 + * @var array + */ protected $insert = []; - // 更新自动完成列表 + + /** + * 更新自动完成定义 + * @var array + */ protected $update = []; - // 是否需要自动写入时间戳 如果设置为字符串 则表示时间字段的类型 - protected $autoWriteTimestamp; - // 创建时间字段 - protected $createTime = 'create_time'; - // 更新时间字段 - protected $updateTime = 'update_time'; - // 时间字段取出后的默认时间格式 - protected $dateFormat = 'Y-m-d H:i:s'; - // 字段类型或者格式转换 - protected $type = []; - // 是否为更新数据 - protected $isUpdate = false; - // 更新条件 - protected $updateWhere; - // 当前执行的关联对象 - protected $relation; - // 验证失败是否抛出异常 - protected $failException = false; - // 全局查询范围 - protected $useGlobalScope = true; /** * 初始化过的模型. - * * @var array */ protected static $initialized = []; + /** + * 是否从主库读取(主从分布式有效) + * @var array + */ + protected static $readMaster; + + /** + * 查询对象实例 + * @var Query + */ + protected $queryInstance; + + /** + * 错误信息 + * @var mixed + */ + protected $error; + + /** + * 软删除字段默认值 + * @var mixed + */ + protected $defaultSoftDelete; + /** * 架构函数 * @access public - * @param array|object $data 数据 + * @param array|object $data 数据 */ public function __construct($data = []) { @@ -122,14 +136,25 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->data = $data; } - // 当前类名 - $this->class = get_class($this); + if ($this->disuse) { + // 废弃字段 + foreach ((array) $this->disuse as $key) { + if (array_key_exists($key, $this->data)) { + unset($this->data[$key]); + } + } + } + + // 记录原始数据 + $this->origin = $this->data; + + $config = Db::getConfig(); if (empty($this->name)) { // 当前模型名 - $name = str_replace('\\', '/', $this->class); + $name = str_replace('\\', '/', static::class); $this->name = basename($name); - if (Config::get('class_suffix')) { + if (Container::get('config')->get('class_suffix')) { $suffix = basename(dirname($name)); $this->name = substr($this->name, 0, -strlen($suffix)); } @@ -137,7 +162,26 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (is_null($this->autoWriteTimestamp)) { // 自动写入时间戳 - $this->autoWriteTimestamp = $this->db()->getConfig('auto_timestamp'); + $this->autoWriteTimestamp = $config['auto_timestamp']; + } + + if (is_null($this->dateFormat)) { + // 设置时间戳格式 + $this->dateFormat = $config['datetime_format']; + } + + if (is_null($this->resultSetType)) { + $this->resultSetType = $config['resultset_type']; + } + + if (!empty($this->connection) && is_array($this->connection)) { + // 设置模型的数据库连接 + $this->connection = array_merge($config, $this->connection); + } + + if ($this->observerClass) { + // 注册模型观察者 + static::observe($this->observerClass); } // 执行初始化操作 @@ -145,629 +189,464 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } /** - * 获取当前模型的数据库查询对象 + * 获取当前模型名称 * @access public - * @param bool $baseQuery 是否调用全局查询范围 - * @return Query + * @return string */ - public function db($baseQuery = true) + public function getName() { - $model = $this->class; - if (!isset(self::$links[$model])) { - // 设置当前模型 确保查询返回模型对象 - $query = Db::connect($this->connection)->model($model, $this->query); - - // 设置当前数据表和模型名 - if (!empty($this->table)) { - $query->setTable($this->table); - } else { - $query->name($this->name); - } - - if (!empty($this->pk)) { - $query->pk($this->pk); - } - - self::$links[$model] = $query; - } - // 全局作用域 - if ($baseQuery && method_exists($this, 'base')) { - call_user_func_array([$this, 'base'], [ & self::$links[$model]]); - } - // 返回当前模型的数据库查询对象 - return self::$links[$model]; + return $this->name; } /** - * 获取关联模型实例 - * @access protected - * @param string|array $relation 关联查询 - * @return Relation|Query + * 是否从主库读取数据(主从分布有效) + * @access public + * @param bool $all 是否所有模型有效 + * @return $this */ - protected function relation($relation = null) + public function readMaster($all = false) { - if (!is_null($relation)) { - // 执行关联查询 - return $this->db()->relation($relation); - } + $model = $all ? '*' : static::class; - // 获取关联对象实例 - if (is_null($this->relation)) { - $this->relation = new Relation($this); - } - return $this->relation; + static::$readMaster[$model] = true; + + return $this; } /** - * 初始化模型 - * @access protected - * @return void + * 创建新的模型实例 + * @access public + * @param array|object $data 数据 + * @param bool $isUpdate 是否为更新 + * @param mixed $where 更新条件 + * @return Model */ - protected function initialize() + public function newInstance($data = [], $isUpdate = false, $where = null) { - $class = get_class($this); - if (!isset(static::$initialized[$class])) { - static::$initialized[$class] = true; - static::init(); - } + return (new static($data))->isUpdate($isUpdate, $where); } /** - * 初始化处理 + * 创建模型的查询对象 * @access protected - * @return void - */ - protected static function init() - {} - - /** - * 设置数据对象值 - * @access public - * @param mixed $data 数据或者属性名 - * @param mixed $value 值 - * @return $this + * @return Query */ - public function data($data, $value = null) + protected function buildQuery() { - if (is_string($data)) { - $this->data[$data] = $value; + // 设置当前模型 确保查询返回模型对象 + $query = Db::connect($this->connection, false, $this->query); + $query->model($this) + ->json($this->json, $this->jsonAssoc) + ->setJsonFieldType($this->jsonType); + + if (isset(static::$readMaster['*']) || isset(static::$readMaster[static::class])) { + $query->master(true); + } + + // 设置当前数据表和模型名 + if (!empty($this->table)) { + $query->table($this->table); } else { - // 清空数据 - $this->data = []; - if (is_object($data)) { - $data = get_object_vars($data); - } - if (true === $value) { - // 数据对象赋值 - foreach ($data as $key => $value) { - $this->setAttr($key, $value, $data); - } - } else { - $this->data = $data; - } + $query->name($this->name); } - return $this; + + if (!empty($this->pk)) { + $query->pk($this->pk); + } + + return $query; } /** - * 获取对象原始数据 如果不存在指定字段返回false + * 获取当前模型的数据库查询对象 * @access public - * @param string $name 字段名 留空获取全部 - * @return mixed - * @throws InvalidArgumentException + * @param Query $query 查询对象实例 + * @return $this */ - public function getData($name = null) + public function setQuery($query) { - if (is_null($name)) { - return $this->data; - } elseif (array_key_exists($name, $this->data)) { - return $this->data[$name]; - } else { - throw new InvalidArgumentException('property not exists:' . $this->class . '->' . $name); - } + $this->queryInstance = $query; + return $this; } /** - * 修改器 设置数据对象值 + * 获取当前模型的数据库查询对象 * @access public - * @param string $name 属性名 - * @param mixed $value 属性值 - * @param array $data 数据 - * @return $this + * @param bool $useBaseQuery 是否调用全局查询范围 + * @return Query */ - public function setAttr($name, $value, $data = []) + public function db($useBaseQuery = true) { - if (is_null($value) && $this->autoWriteTimestamp && in_array($name, [$this->createTime, $this->updateTime])) { - // 自动写入的时间戳字段 - $value = $this->autoWriteTimestamp($name); - } else { - // 检测修改器 - $method = 'set' . Loader::parseName($name, 1) . 'Attr'; - if (method_exists($this, $method)) { - $value = $this->$method($value, array_merge($data, $this->data)); - } elseif (isset($this->type[$name])) { - // 类型转换 - $value = $this->writeTransform($value, $this->type[$name]); - } + if ($this->queryInstance) { + return $this->queryInstance; } - // 标记字段更改 - if (!isset($this->data[$name]) || ($this->data[$name] != $value && !in_array($name, $this->change))) { - $this->change[] = $name; + $query = $this->buildQuery(); + + // 软删除 + if (property_exists($this, 'withTrashed') && !$this->withTrashed) { + $this->withNoTrashed($query); } - // 设置数据对象属性 - $this->data[$name] = $value; - return $this; + + // 全局作用域 + if ($useBaseQuery && method_exists($this, 'base')) { + call_user_func_array([$this, 'base'], [ & $query]); + } + + // 返回当前模型的数据库查询对象 + return $query; } /** - * 自动写入时间戳 - * @access public - * @param string $name 时间戳字段 - * @return mixed + * 初始化模型 + * @access protected + * @return void */ - protected function autoWriteTimestamp($name) + protected function initialize() { - if (isset($this->type[$name])) { - $type = $this->type[$name]; - if (strpos($type, ':')) { - list($type, $param) = explode(':', $type, 2); - } - switch ($type) { - case 'datetime': - case 'date': - $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, $_SERVER['REQUEST_TIME']); - break; - case 'timestamp': - case 'int': - $value = $_SERVER['REQUEST_TIME']; - break; - } - } elseif (is_string($this->autoWriteTimestamp) && in_array(strtolower($this->autoWriteTimestamp), ['datetime', 'date', 'timestamp'])) { - $value = date($this->dateFormat, $_SERVER['REQUEST_TIME']); - } else { - $value = $_SERVER['REQUEST_TIME']; + if (!isset(static::$initialized[static::class])) { + static::$initialized[static::class] = true; + static::init(); } - return $value; } /** - * 数据写入 类型转换 - * @access public - * @param mixed $value 值 - * @param string|array $type 要转换的类型 - * @return mixed + * 初始化处理 + * @access protected + * @return void */ - protected function writeTransform($value, $type) - { - if (is_array($type)) { - list($type, $param) = $type; - } elseif (strpos($type, ':')) { - list($type, $param) = explode(':', $type, 2); - } - switch ($type) { - case 'integer': - $value = (int) $value; - break; - case 'float': - if (empty($param)) { - $value = (float) $value; - } else { - $value = (float) number_format($value, $param); - } - break; - case 'boolean': - $value = (bool) $value; - break; - case 'timestamp': - if (!is_numeric($value)) { - $value = strtotime($value); - } - break; - case 'datetime': - $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, is_numeric($value) ? $value : strtotime($value)); - break; - case 'object': - if (is_object($value)) { - $value = json_encode($value, JSON_FORCE_OBJECT); - } - break; - case 'array': - $value = (array) $value; - case 'json': - $option = !empty($param) ? (int) $param : JSON_UNESCAPED_UNICODE; - $value = json_encode($value, $option); - break; - case 'serialize': - $value = serialize($value); - break; - } - return $value; - } + protected static function init() + {} /** - * 获取器 获取数据对象的值 - * @access public - * @param string $name 名称 - * @return mixed - * @throws InvalidArgumentException + * 数据自动完成 + * @access protected + * @param array $auto 要自动更新的字段列表 + * @return void */ - public function getAttr($name) + protected function autoCompleteData($auto = []) { - try { - $notFound = false; - $value = $this->getData($name); - } catch (InvalidArgumentException $e) { - $notFound = true; - $value = null; - } + foreach ($auto as $field => $value) { + if (is_integer($field)) { + $field = $value; + $value = null; + } - // 检测属性获取器 - $method = 'get' . Loader::parseName($name, 1) . 'Attr'; - if (method_exists($this, $method)) { - $value = $this->$method($value, $this->data); - } elseif (isset($this->type[$name])) { - // 类型转换 - $value = $this->readTransform($value, $this->type[$name]); - } elseif ($notFound) { - $method = Loader::parseName($name, 1); - if (method_exists($this, $method) && !method_exists('\think\Model', $method)) { - // 不存在该字段 获取关联数据 - $value = $this->relation()->getRelation($method); - // 保存关联对象值 - $this->data[$name] = $value; + if (!isset($this->data[$field])) { + $default = null; } else { - throw new InvalidArgumentException('property not exists:' . $this->class . '->' . $name); + $default = $this->data[$field]; } - } - return $value; - } - /** - * 数据读取 类型转换 - * @access public - * @param mixed $value 值 - * @param string|array $type 要转换的类型 - * @return mixed - */ - protected function readTransform($value, $type) - { - if (is_array($type)) { - list($type, $param) = $type; - } elseif (strpos($type, ':')) { - list($type, $param) = explode(':', $type, 2); + $this->setAttr($field, !is_null($value) ? $value : $default); } - switch ($type) { - case 'integer': - $value = (int) $value; - break; - case 'float': - if (empty($param)) { - $value = (float) $value; - } else { - $value = (float) number_format($value, $param); - } - break; - case 'boolean': - $value = (bool) $value; - break; - case 'timestamp': - if (!is_null($value)) { - $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, $value); - } - break; - case 'datetime': - if (!is_null($value)) { - $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, strtotime($value)); - } - break; - case 'json': - $value = json_decode($value, true); - break; - case 'array': - $value = is_null($value) ? [] : json_decode($value, true); - break; - case 'object': - $value = empty($value) ? new \stdClass() : json_decode($value); - break; - case 'serialize': - $value = unserialize($value); - break; - } - return $value; } /** - * 设置需要追加的输出属性 + * 更新是否强制写入数据 而不做比较 * @access public - * @param array $append 属性列表 + * @param bool $force * @return $this */ - public function append($append = []) + public function force($force = true) { - $this->append = $append; + $this->force = $force; return $this; } /** - * 设置需要隐藏的输出属性 + * 判断force * @access public - * @param array $hidden 属性列表 - * @return $this + * @return bool */ - public function hidden($hidden = []) + public function isForce() { - $this->hidden = $hidden; - return $this; + return $this->force; } /** - * 设置需要输出的属性 - * @param array $visible + * 新增数据是否使用Replace + * @access public + * @param bool $replace * @return $this */ - public function visible($visible = []) + public function replace($replace = true) { - $this->visible = $visible; + $this->replace = $replace; return $this; } /** - * 转换当前模型对象为数组 + * 设置数据是否存在 * @access public - * @return array + * @param bool $exists + * @return void */ - public function toArray() + public function exists($exists) { - $item = []; - - //过滤属性 - if (!empty($this->visible)) { - $data = array_intersect_key($this->data, array_flip($this->visible)); - } elseif (!empty($this->hidden)) { - $data = array_diff_key($this->data, array_flip($this->hidden)); - } else { - $data = $this->data; - } - - foreach ($data as $key => $val) { - if ($val instanceof Model || $val instanceof Collection) { - // 关联模型对象 - $item[$key] = $val->toArray(); - } elseif (is_array($val) && reset($val) instanceof Model) { - // 关联模型数据集 - $arr = []; - foreach ($val as $k => $value) { - $arr[$k] = $value->toArray(); - } - $item[$key] = $arr; - } else { - // 模型属性 - $item[$key] = $this->getAttr($key); - } - } - // 追加属性(必须定义获取器) - if (!empty($this->append)) { - foreach ($this->append as $name) { - $item[$name] = $this->getAttr($name); - } - } - return !empty($item) ? $item : []; + $this->exists = $exists; } /** - * 转换当前模型对象为JSON字符串 + * 判断数据是否存在数据库 * @access public - * @param integer $options json参数 - * @return string + * @return bool */ - public function toJson($options = JSON_UNESCAPED_UNICODE) + public function isExists() { - return json_encode($this->toArray(), $options); + return $this->exists; } /** - * 获取模型对象的主键 + * 保存当前数据对象 * @access public - * @param string $name 模型名 - * @return mixed + * @param array $data 数据 + * @param array $where 更新条件 + * @param string $sequence 自增序列名 + * @return bool */ - public function getPk($name = '') + public function save($data = [], $where = [], $sequence = null) { - if (!empty($name)) { - $table = $this->db()->getTable($name); - return $this->db()->getPk($table); - } elseif (empty($this->pk)) { - $this->pk = $this->db()->getPk(); + if (is_string($data)) { + $sequence = $data; + $data = []; } - return $this->pk; - } - /** - * 判断一个字段名是否为主键字段 - * @access public - * @param string $key 名称 - * @return bool - */ - protected function isPk($key) - { - $pk = $this->getPk(); - if (is_string($pk) && $pk == $key) { - return true; - } elseif (is_array($pk) && in_array($key, $pk)) { - return true; + if (!$this->checkBeforeSave($data, $where)) { + return false; + } + + $result = $this->exists ? $this->updateData($where) : $this->insertData($sequence); + + if (false === $result) { + return false; } - return false; + + // 写入回调 + $this->trigger('after_write'); + + // 重新记录原始数据 + $this->origin = $this->data; + + return true; } /** - * 保存当前数据对象 - * @access public - * @param array $data 数据 - * @param array $where 更新条件 - * @param string $sequence 自增序列名 - * @return integer|false + * 写入之前检查数据 + * @access protected + * @param array $data 数据 + * @param array $where 保存条件 + * @return bool */ - public function save($data = [], $where = [], $sequence = null) + protected function checkBeforeSave($data, $where) { if (!empty($data)) { - // 数据自动验证 - if (!$this->validateData($data)) { - return false; - } // 数据对象赋值 foreach ($data as $key => $value) { $this->setAttr($key, $value, $data); } + if (!empty($where)) { - $this->isUpdate = true; + $this->exists = true; + $this->updateWhere = $where; } } + // 数据自动完成 + $this->autoCompleteData($this->auto); + + // 事件回调 + if (false === $this->trigger('before_write')) { + return false; + } + + return true; + } + + /** + * 检查数据是否允许写入 + * @access protected + * @param array $append 自动完成的字段列表 + * @return array + */ + protected function checkAllowFields(array $append = []) + { // 检测字段 - if (!empty($this->field)) { - foreach ($this->data as $key => $val) { - if (!in_array($key, $this->field)) { - unset($this->data[$key]); - } + if (empty($this->field) || true === $this->field) { + $query = $this->db(false); + $table = $this->table ?: $query->getTable(); + + $this->field = $query->getConnection()->getTableFields($table); + + $field = $this->field; + } else { + $field = array_merge($this->field, $append); + + if ($this->autoWriteTimestamp) { + array_push($field, $this->createTime, $this->updateTime); } } - // 数据自动完成 - $this->autoCompleteData($this->auto); - - // 自动写入更新时间 - if ($this->autoWriteTimestamp && $this->updateTime) { - $this->setAttr($this->updateTime, null); + if ($this->disuse) { + // 废弃字段 + $field = array_diff($field, (array) $this->disuse); } + return $field; + } + + /** + * 更新写入数据 + * @access protected + * @param mixed $where 更新条件 + * @return bool + */ + protected function updateData($where) + { + // 自动更新 + $this->autoCompleteData($this->update); + // 事件回调 - if (false === $this->trigger('before_write', $this)) { + if (false === $this->trigger('before_update')) { return false; } - if ($this->isUpdate) { - // 自动更新 - $this->autoCompleteData($this->update); + // 获取有更新的数据 + $data = $this->getChangedData(); - // 事件回调 - if (false === $this->trigger('before_update', $this)) { - return false; + if (empty($data)) { + // 关联更新 + if (!empty($this->relationWrite)) { + $this->autoRelationUpdate(); } - // 去除没有更新的字段 - $data = []; - foreach ($this->data as $key => $val) { - if (in_array($key, $this->change) || $this->isPk($key)) { - $data[$key] = $val; - } - } + return false; + } elseif ($this->autoWriteTimestamp && $this->updateTime && !isset($data[$this->updateTime])) { + // 自动写入更新时间 + $data[$this->updateTime] = $this->autoWriteTimestamp($this->updateTime); - if (!empty($this->readonly)) { - // 只读字段不允许更新 - foreach ($this->readonly as $key => $field) { - if (isset($data[$field])) { - unset($data[$field]); - } - } + $this->data[$this->updateTime] = $data[$this->updateTime]; + } + + if (empty($where) && !empty($this->updateWhere)) { + $where = $this->updateWhere; + } + + // 检查允许字段 + $allowFields = $this->checkAllowFields(array_merge($this->auto, $this->update)); + + // 保留主键数据 + foreach ($this->data as $key => $val) { + if ($this->isPk($key)) { + $data[$key] = $val; } + } + + $pk = $this->getPk(); + $array = []; - if (empty($where) && !empty($this->updateWhere)) { - $where = $this->updateWhere; + foreach ((array) $pk as $key) { + if (isset($data[$key])) { + $array[] = [$key, '=', $data[$key]]; + unset($data[$key]); } + } - if (!empty($where)) { - $pk = $this->getPk(); - if (is_string($pk) && isset($data[$pk])) { - if (!isset($where[$pk])) { - unset($where); - $where[$pk] = $data[$pk]; + if (!empty($array)) { + $where = $array; + } + + foreach ((array) $this->relationWrite as $name => $val) { + if (is_array($val)) { + foreach ($val as $key) { + if (isset($data[$key])) { + unset($data[$key]); } - unset($data[$pk]); } } + } - $result = $this->db()->where($where)->update($data); - // 清空change - $this->change = []; - // 更新回调 - $this->trigger('after_update', $this); - } else { - // 自动写入 - $this->autoCompleteData($this->insert); + // 模型更新 + $db = $this->db(false); + $db->startTrans(); - // 自动写入创建时间 - if ($this->autoWriteTimestamp && $this->createTime) { - $this->setAttr($this->createTime, null); + try { + $db->where($where) + ->strict(false) + ->field($allowFields) + ->update($data); + + // 关联更新 + if (!empty($this->relationWrite)) { + $this->autoRelationUpdate(); } - if (false === $this->trigger('before_insert', $this)) { - return false; - } + $db->commit(); - $result = $this->db()->insert($this->data); + // 更新回调 + $this->trigger('after_update'); - // 获取自动增长主键 - if ($result) { - $insertId = $this->db()->getLastInsID($sequence); - $pk = $this->getPk(); - if (is_string($pk) && $insertId) { - $this->data[$pk] = $insertId; - } - } - // 标记为更新 - $this->isUpdate = true; - // 清空change - $this->change = []; - // 新增回调 - $this->trigger('after_insert', $this); + return true; + } catch (\Exception $e) { + $db->rollback(); + throw $e; } - // 写入回调 - $this->trigger('after_write', $this); - - return $result; } /** - * 保存多个数据到当前数据对象 - * @access public - * @param array $dataSet 数据 - * @param boolean $replace 是否自动识别更新和写入 - * @return array|false + * 新增写入数据 + * @access protected + * @param string $sequence 自增序列名 + * @return bool */ - public function saveAll($dataSet, $replace = true) + protected function insertData($sequence) { - if ($this->validate) { - // 数据批量验证 - $validate = $this->validate; - foreach ($dataSet as $data) { - if (!$this->validate($validate)->validateData($data)) { - return false; - } - } + // 自动写入 + $this->autoCompleteData($this->insert); + + // 时间戳自动写入 + $this->checkTimeStampWrite(); + + if (false === $this->trigger('before_insert')) { + return false; } - $result = []; - $db = $this->db(); + // 检查允许字段 + $allowFields = $this->checkAllowFields(array_merge($this->auto, $this->insert)); + + $db = $this->db(false); $db->startTrans(); + try { - $pk = $this->getPk(); - if (is_string($pk) && $replace) { - $auto = true; - } - foreach ($dataSet as $key => $data) { - if (!empty($auto) && isset($data[$pk])) { - $result[$key] = self::update($data); - } else { - $result[$key] = self::create($data); + $result = $db->strict(false) + ->field($allowFields) + ->insert($this->data, $this->replace, false, $sequence); + + // 获取自动增长主键 + if ($result && $insertId = $db->getLastInsID($sequence)) { + $pk = $this->getPk(); + + foreach ((array) $pk as $key) { + if (!isset($this->data[$key]) || '' == $this->data[$key]) { + $this->data[$key] = $insertId; + } } } + + // 关联写入 + if (!empty($this->relationWrite)) { + $this->autoRelationInsert(); + } + $db->commit(); - return $result; + + // 标记为更新 + $this->exists = true; + + // 新增回调 + $this->trigger('after_insert'); + + return true; } catch (\Exception $e) { $db->rollback(); throw $e; @@ -775,607 +654,401 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } /** - * 设置允许写入的字段 + * 字段值(延迟)增长 * @access public - * @param bool|array $field 允许写入的字段 如果为true只允许写入数据表字段 - * @return $this + * @param string $field 字段名 + * @param integer $step 增长值 + * @param integer $lazyTime 延时时间(s) + * @return bool + * @throws Exception */ - public function allowField($field) + public function setInc($field, $step = 1, $lazyTime = 0) { - if (true === $field) { - $field = $this->db()->getTableInfo('', 'fields'); + // 读取更新条件 + $where = $this->getWhere(); + + // 事件回调 + if (false === $this->trigger('before_update')) { + return false; } - $this->field = $field; - return $this; + + $result = $this->db(false) + ->where($where) + ->setInc($field, $step, $lazyTime); + + if (true !== $result) { + $this->data[$field] += $step; + } + + // 更新回调 + $this->trigger('after_update'); + + return true; } /** - * 是否为更新数据 + * 字段值(延迟)减少 * @access public - * @param bool $update - * @param mixed $where - * @return $this + * @param string $field 字段名 + * @param integer $step 减少值 + * @param integer $lazyTime 延时时间(s) + * @return bool + * @throws Exception */ - public function isUpdate($update = true, $where = null) + public function setDec($field, $step = 1, $lazyTime = 0) + { + // 读取更新条件 + $where = $this->getWhere(); + + // 事件回调 + if (false === $this->trigger('before_update')) { + return false; + } + + $result = $this->db(false) + ->where($where) + ->setDec($field, $step, $lazyTime); + + if (true !== $result) { + $this->data[$field] -= $step; + } + + // 更新回调 + $this->trigger('after_update'); + + return true; + } + + /** + * 获取当前的更新条件 + * @access protected + * @return mixed + */ + protected function getWhere() { - $this->isUpdate = $update; - if (!empty($where)) { - $this->updateWhere = $where; + // 删除条件 + $pk = $this->getPk(); + + if (is_string($pk) && isset($this->data[$pk])) { + $where[] = [$pk, '=', $this->data[$pk]]; + } elseif (!empty($this->updateWhere)) { + $where = $this->updateWhere; + } else { + $where = null; } - return $this; + + return $where; } /** - * 数据自动完成 + * 保存多个数据到当前数据对象 + * @access public + * @param array $dataSet 数据 + * @param boolean $replace 是否自动识别更新和写入 + * @return Collection + * @throws \Exception + */ + public function saveAll($dataSet, $replace = true) + { + $db = $this->db(false); + $db->startTrans(); + + try { + $pk = $this->getPk(); + + if (is_string($pk) && $replace) { + $auto = true; + } + + $result = []; + + foreach ($dataSet as $key => $data) { + if ($this->exists || (!empty($auto) && isset($data[$pk]))) { + $result[$key] = self::update($data, [], $this->field); + } else { + $result[$key] = self::create($data, $this->field); + } + } + + $db->commit(); + + return $this->toCollection($result); + } catch (\Exception $e) { + $db->rollback(); + throw $e; + } + } + + /** + * 是否为更新数据 * @access public - * @param array $auto 要自动更新的字段列表 - * @return void + * @param mixed $update + * @param mixed $where + * @return $this */ - protected function autoCompleteData($auto = []) + public function isUpdate($update = true, $where = null) { - foreach ($auto as $field => $value) { - if (is_integer($field)) { - $field = $value; - $value = null; - } - if (!in_array($field, $this->change)) { - $this->setAttr($field, !is_null($value) ? $value : (isset($this->data[$field]) ? $this->data[$field] : $value)); + if (is_bool($update)) { + $this->exists = $update; + + if (!empty($where)) { + $this->updateWhere = $where; } + } else { + $this->exists = true; + $this->updateWhere = $update; } + + return $this; } /** * 删除当前的记录 * @access public - * @return integer + * @return bool */ public function delete() { - if (false === $this->trigger('before_delete', $this)) { + if (!$this->exists || false === $this->trigger('before_delete')) { return false; } - $result = $this->db()->delete($this->data); + // 读取更新条件 + $where = $this->getWhere(); - $this->trigger('after_delete', $this); - return $result; + $db = $this->db(false); + $db->startTrans(); + + try { + // 删除当前模型数据 + $result = $db->where($where)->delete(); + + // 关联删除 + if (!empty($this->relationWrite)) { + $this->autoRelationDelete(); + } + + $db->commit(); + + $this->trigger('after_delete'); + + $this->exists = false; + + return true; + } catch (\Exception $e) { + $db->rollback(); + throw $e; + } } /** * 设置自动完成的字段( 规则通过修改器定义) * @access public - * @param array $fields 需要自动完成的字段 + * @param array $fields 需要自动完成的字段 * @return $this */ public function auto($fields) { $this->auto = $fields; + return $this; } /** - * 设置字段验证 + * 写入数据 * @access public - * @param array|string|bool $rule 验证规则 true表示自动读取验证器类 - * @param array $msg 提示信息 - * @return $this + * @param array $data 数据数组 + * @param array|true $field 允许字段 + * @param bool $replace 使用Replace + * @return static */ - public function validate($rule = true, $msg = []) + public static function create($data = [], $field = null, $replace = false) { - if (is_array($rule)) { - $this->validate = [ - 'rule' => $rule, - 'msg' => $msg, - ]; - } else { - $this->validate = true === $rule ? $this->name : $rule; + $model = new static(); + + if (!empty($field)) { + $model->allowField($field); } - return $this; + + $model->isUpdate(false)->replace($replace)->save($data, []); + + return $model; } /** - * 设置验证失败后是否抛出异常 + * 更新数据 * @access public - * @param bool $fail 是否抛出异常 - * @return $this + * @param array $data 数据数组 + * @param array $where 更新条件 + * @param array|true $field 允许字段 + * @return static */ - public function validateFailException($fail = true) + public static function update($data = [], $where = [], $field = null) { - $this->failException = $fail; - return $this; - } + $model = new static(); - /** - * 自动验证数据 - * @access protected - * @param array $data 验证数据 - * @return bool - */ - protected function validateData($data) - { - if (!empty($this->validate)) { - $info = $this->validate; - if (is_array($info)) { - $validate = Loader::validate(); - $validate->rule($info['rule']); - $validate->message($info['msg']); - } else { - $name = is_string($info) ? $info : $this->name; - if (strpos($name, '.')) { - list($name, $scene) = explode('.', $name); - } - $validate = Loader::validate($name); - if (!empty($scene)) { - $validate->scene($scene); - } - } - if (!$validate->check($data)) { - $this->error = $validate->getError(); - if ($this->failException) { - throw new ValidateException($this->error); - } else { - return false; - } - } - $this->validate = null; + if (!empty($field)) { + $model->allowField($field); } - return true; - } - /** - * 返回模型的错误信息 - * @access public - * @return string - */ - public function getError() - { - return $this->error; + $model->isUpdate(true)->save($data, $where); + + return $model; } /** - * 注册回调方法 + * 查找单条记录 * @access public - * @param string $event 事件名 - * @param callable $callback 回调方法 - * @param bool $override 是否覆盖 - * @return void + * @param mixed $data 主键值或者查询条件(闭包) + * @param mixed $with 关联预查询 + * @param bool $cache 是否缓存 + * @param bool $failException 是否抛出异常 + * @return static|null + * @throws exception\DbException */ - public static function event($event, $callback, $override = false) + public static function get($data, $with = [], $cache = false, $failException = false) { - $class = get_called_class(); - if ($override) { - self::$event[$class][$event] = []; + if (is_null($data)) { + return; } - self::$event[$class][$event][] = $callback; - } - /** - * 触发事件 - * @access protected - * @param string $event 事件名 - * @param mixed $params 传入参数(引用) - * @return bool - */ - protected function trigger($event, &$params) - { - if (isset(self::$event[$this->class][$event])) { - foreach (self::$event[$this->class][$event] as $callback) { - if (is_callable($callback)) { - $result = call_user_func_array($callback, [ & $params]); - if (false === $result) { - return false; - } - } - } + if (true === $with || is_int($with)) { + $cache = $with; + $with = []; } - return true; - } - /** - * 写入数据 - * @access public - * @param array $data 数据数组 - * @return $this - */ - public static function create($data = []) - { - $model = new static(); - $model->isUpdate(false)->save($data, []); - return $model; - } + $query = static::parseQuery($data, $with, $cache); - /** - * 更新数据 - * @access public - * @param array $data 数据数组 - * @param array $where 更新条件 - * @return $this - */ - public static function update($data = [], $where = []) - { - $model = new static(); - $result = $model->isUpdate(true)->save($data, $where); - return $model; + return $query->failException($failException)->find($data); } /** - * 查找单条记录 + * 查找单条记录 如果不存在直接抛出异常 * @access public - * @param mixed $data 主键值或者查询条件(闭包) - * @param array|string $with 关联预查询 - * @param bool $cache 是否缓存 - * @return static + * @param mixed $data 主键值或者查询条件(闭包) + * @param mixed $with 关联预查询 + * @param bool $cache 是否缓存 + * @return static|null * @throws exception\DbException */ - public static function get($data = null, $with = [], $cache = false) + public static function getOrFail($data, $with = [], $cache = false) { - $query = static::parseQuery($data, $with, $cache); - return $query->find($data); + return self::get($data, $with, $cache, true); } /** * 查找所有记录 * @access public - * @param mixed $data 主键列表或者查询条件(闭包) - * @param array|string $with 关联预查询 - * @param bool $cache 是否缓存 + * @param mixed $data 主键列表或者查询条件(闭包) + * @param array|string $with 关联预查询 + * @param bool $cache 是否缓存 * @return static[]|false * @throws exception\DbException */ public static function all($data = null, $with = [], $cache = false) { + if (true === $with || is_int($with)) { + $cache = $with; + $with = []; + } + $query = static::parseQuery($data, $with, $cache); + return $query->select($data); } /** * 分析查询表达式 * @access public - * @param mixed $data 主键列表或者查询条件(闭包) - * @param string $with 关联预查询 - * @param bool $cache 是否缓存 + * @param mixed $data 主键列表或者查询条件(闭包) + * @param string $with 关联预查询 + * @param bool $cache 是否缓存 * @return Query */ protected static function parseQuery(&$data, $with, $cache) { $result = self::with($with)->cache($cache); + if (is_array($data) && key($data) !== 0) { $result = $result->where($data); $data = null; } elseif ($data instanceof \Closure) { - call_user_func_array($data, [ & $result]); + $data($result); $data = null; } elseif ($data instanceof Query) { $result = $data->with($with)->cache($cache); $data = null; } + return $result; } /** * 删除记录 * @access public - * @param mixed $data 主键列表 支持闭包查询条件 - * @return integer 成功删除的记录数 + * @param mixed $data 主键列表 支持闭包查询条件 + * @return bool */ public static function destroy($data) { + if (empty($data) && 0 !== $data) { + return false; + } + $model = new static(); + $query = $model->db(); + if (is_array($data) && key($data) !== 0) { $query->where($data); $data = null; } elseif ($data instanceof \Closure) { - call_user_func_array($data, [ & $query]); + $data($query); $data = null; - } elseif (is_null($data)) { - return 0; } + $resultSet = $query->select($data); - $count = 0; + if ($resultSet) { foreach ($resultSet as $data) { - $result = $data->delete(); - $count += $result; - } - } - return $count; - } - - /** - * 命名范围 - * @access public - * @param string|array|Closure $name 命名范围名称 逗号分隔 - * @param mixed ...$params 参数调用 - * @return Model - */ - public static function scope($name) - { - if ($name instanceof Query) { - return $name; - } - $model = new static(); - $params = func_get_args(); - $params[0] = $model->db(); - if ($name instanceof \Closure) { - call_user_func_array($name, $params); - } elseif (is_string($name)) { - $name = explode(',', $name); - } - if (is_array($name)) { - foreach ($name as $scope) { - $method = 'scope' . trim($scope); - if (method_exists($model, $method)) { - call_user_func_array([$model, $method], $params); - } + $data->delete(); } } - return $model; - } - - /** - * 设置是否使用全局查询范围 - * @param bool $use 是否启用全局查询范围 - * @access public - * @return Model - */ - public static function useGlobalScope($use) - { - $model = new static(); - $model->useGlobalScope = $use; - return $model; - } - - /** - * 根据关联条件查询当前模型 - * @access public - * @param string $relation 关联方法名 - * @param string $operator 比较操作符 - * @param integer $count 个数 - * @param string $id 关联表的统计字段 - * @return Model - */ - public static function has($relation, $operator = '>=', $count = 1, $id = '*') - { - $model = new static(); - $info = $model->$relation()->getRelationInfo(); - $table = $info['model']::getTable(); - switch ($info['type']) { - case Relation::HAS_MANY: - return $model->db()->alias('a') - ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey'], $info['joinType']) - ->group('b.' . $info['foreignKey']) - ->having('count(' . $id . ')' . $operator . $count); - case Relation::HAS_MANY_THROUGH: - // TODO - } - } - - /** - * 根据关联条件查询当前模型 - * @access public - * @param string $relation 关联方法名 - * @param mixed $where 查询条件(数组或者闭包) - * @return Model - */ - public static function hasWhere($relation, $where = []) - { - $model = new static(); - $info = $model->$relation()->getRelationInfo(); - switch ($info['type']) { - case Relation::HAS_ONE: - case Relation::HAS_MANY: - $table = $info['model']::getTable(); - if (is_array($where)) { - foreach ($where as $key => $val) { - if (false === strpos($key, '.')) { - $where['b.' . $key] = $val; - unset($where[$key]); - } - } - } - return $model->db()->alias('a') - ->field('a.*') - ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey'], $info['joinType']) - ->where($where); - case Relation::HAS_MANY_THROUGH: - // TODO - } - } - - /** - * 解析模型的完整命名空间 - * @access public - * @param string $model 模型名(或者完整类名) - * @return string - */ - protected function parseModel($model) - { - if (false === strpos($model, '\\')) { - $path = explode('\\', get_called_class()); - array_pop($path); - array_push($path, Loader::parseName($model, 1)); - $model = implode('\\', $path); - } - return $model; - } - - /** - * 查询当前模型的关联数据 - * @access public - * @param string|array $relations 关联名 - * @return $this - */ - public function relationQuery($relations) - { - if (is_string($relations)) { - $relations = explode(',', $relations); - } - $this->relation(); - foreach ($relations as $relation) { - $this->data[$relation] = $this->relation->getRelation($relation); - } - return $this; - } - - /** - * 预载入关联查询 返回数据集 - * @access public - * @param array $resultSet 数据集 - * @param string $relation 关联名 - * @return array - */ - public function eagerlyResultSet($resultSet, $relation) - { - return $this->relation()->eagerlyResultSet($resultSet, $relation); - } - - /** - * 预载入关联查询 返回模型对象 - * @access public - * @param Model $result 数据对象 - * @param string $relation 关联名 - * @return Model - */ - public function eagerlyResult($result, $relation) - { - return $this->relation()->eagerlyResult($result, $relation); - } - - /** - * HAS ONE 关联定义 - * @access public - * @param string $model 模型名 - * @param string $foreignKey 关联外键 - * @param string $localKey 关联主键 - * @param array $alias 别名定义 - * @param string $joinType JOIN类型 - * @return Relation - */ - public function hasOne($model, $foreignKey = '', $localKey = '', $alias = [], $joinType = 'INNER') - { - // 记录当前关联信息 - $model = $this->parseModel($model); - $localKey = $localKey ?: $this->getPk(); - $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; - return $this->relation()->hasOne($model, $foreignKey, $localKey, $alias, $joinType); - } - - /** - * BELONGS TO 关联定义 - * @access public - * @param string $model 模型名 - * @param string $foreignKey 关联外键 - * @param string $otherKey 关联主键 - * @param array $alias 别名定义 - * @param string $joinType JOIN类型 - * @return Relation - */ - public function belongsTo($model, $foreignKey = '', $otherKey = '', $alias = [], $joinType = 'INNER') - { - // 记录当前关联信息 - $model = $this->parseModel($model); - $foreignKey = $foreignKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id'; - $otherKey = $otherKey ?: (new $model)->getPk(); - return $this->relation()->belongsTo($model, $foreignKey, $otherKey, $alias, $joinType); - } - /** - * HAS MANY 关联定义 - * @access public - * @param string $model 模型名 - * @param string $foreignKey 关联外键 - * @param string $localKey 关联主键 - * @param array $alias 别名定义 - * @return Relation - */ - public function hasMany($model, $foreignKey = '', $localKey = '', $alias = []) - { - // 记录当前关联信息 - $model = $this->parseModel($model); - $localKey = $localKey ?: $this->getPk(); - $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; - return $this->relation()->hasMany($model, $foreignKey, $localKey, $alias); + return true; } /** - * HAS MANY 远程关联定义 + * 获取错误信息 * @access public - * @param string $model 模型名 - * @param string $through 中间模型名 - * @param string $foreignKey 关联外键 - * @param string $throughKey 关联外键 - * @param string $localKey 关联主键 - * @param array $alias 别名定义 - * @return Relation + * @return mixed */ - public function hasManyThrough($model, $through, $foreignKey = '', $throughKey = '', $localKey = '', $alias = []) + public function getError() { - // 记录当前关联信息 - $model = $this->parseModel($model); - $through = $this->parseModel($through); - $localKey = $localKey ?: $this->getPk(); - $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; - $name = Loader::parseName(basename(str_replace('\\', '/', $through))); - $throughKey = $throughKey ?: $name . '_id'; - return $this->relation()->hasManyThrough($model, $through, $foreignKey, $throughKey, $localKey, $alias); + return $this->error; } /** - * BELONGS TO MANY 关联定义 - * @access public - * @param string $model 模型名 - * @param string $table 中间表名 - * @param string $foreignKey 关联外键 - * @param string $localKey 当前模型关联键 - * @param array $alias 别名定义 - * @return Relation + * 解序列化后处理 */ - public function belongsToMany($model, $table = '', $foreignKey = '', $localKey = '', $alias = []) - { - // 记录当前关联信息 - $model = $this->parseModel($model); - $name = Loader::parseName(basename(str_replace('\\', '/', $model))); - $table = $table ?: $this->db()->getTable(Loader::parseName($this->name) . '_' . $name); - $foreignKey = $foreignKey ?: $name . '_id'; - $localKey = $localKey ?: Loader::parseName($this->name) . '_id'; - return $this->relation()->belongsToMany($model, $table, $foreignKey, $localKey, $alias); - } - - public function __call($method, $args) - { - $query = $this->db(); - if (method_exists($this, 'scope' . $method)) { - // 动态调用命名范围 - $method = 'scope' . $method; - array_unshift($args, $query); - call_user_func_array([$this, $method], $args); - return $this; - } else { - return call_user_func_array([$query, $method], $args); - } - } - - public static function __callStatic($method, $params) + public function __wakeup() { - $query = self::getDb(); - return call_user_func_array([$query, $method], $params); + $this->initialize(); } - protected static function getDb() + public function __debugInfo() { - $model = get_called_class(); - if (!isset(self::$links[$model])) { - self::$links[$model] = (new static())->db(); - } - return self::$links[$model]; + return [ + 'data' => $this->data, + 'relation' => $this->relation, + ]; } /** * 修改器 设置数据对象的值 * @access public - * @param string $name 名称 - * @param mixed $value 值 + * @param string $name 名称 + * @param mixed $value 值 * @return void */ public function __set($name, $value) @@ -1386,7 +1059,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 获取器 获取数据对象的值 * @access public - * @param string $name 名称 + * @param string $name 名称 * @return mixed */ public function __get($name) @@ -1397,44 +1070,27 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 检测数据对象的值 * @access public - * @param string $name 名称 + * @param string $name 名称 * @return boolean */ public function __isset($name) { try { - if (array_key_exists($name, $this->data)) { - return true; - } else { - $this->getAttr($name); - return true; - } + return !is_null($this->getAttr($name)); } catch (InvalidArgumentException $e) { return false; } - } /** * 销毁数据对象的值 * @access public - * @param string $name 名称 + * @param string $name 名称 * @return void */ public function __unset($name) { - unset($this->data[$name]); - } - - public function __toString() - { - return $this->toJson(); - } - - // JsonSerializable - public function jsonSerialize() - { - return $this->toArray(); + unset($this->data[$name], $this->relation[$name]); } // ArrayAccess @@ -1459,11 +1115,27 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } /** - * 解序列化后处理 + * 设置是否使用全局查询范围 + * @access public + * @param bool $use 是否启用全局查询范围 + * @return Query */ - public function __wakeup() + public static function useGlobalScope($use) { - $this->initialize(); + $model = new static(); + + return $model->db($use); } + public function __call($method, $args) + { + return call_user_func_array([$this->db(), $method], $args); + } + + public static function __callStatic($method, $args) + { + $model = new static(); + + return call_user_func_array([$model->db(), $method], $args); + } } diff --git a/library/think/Paginator.php b/library/think/Paginator.php index 7385ebb0aacf52dfb56f5d5b2bc2d9d757c5ee72..bbe63e2e31fad0a785638086305c153e5292ba84 100644 --- a/library/think/Paginator.php +++ b/library/think/Paginator.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,79 +11,107 @@ namespace think; -use think\paginator\Collection as PaginatorCollection; -use think\Request; +use ArrayAccess; +use ArrayIterator; +use Countable; +use IteratorAggregate; +use JsonSerializable; +use Traversable; -abstract class Paginator +abstract class Paginator implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable { - /** @var bool 是否为简洁模式 */ + /** + * 是否简洁模式 + * @var bool + */ protected $simple = false; - /** @var PaginatorCollection 数据集 */ + /** + * 数据集 + * @var Collection + */ protected $items; - /** @var integer 当前页 */ + /** + * 当前页 + * @var integer + */ protected $currentPage; - /** @var integer 最后一页 */ + /** + * 最后一页 + * @var integer + */ protected $lastPage; - /** @var integer|null 数据总数 */ + /** + * 数据总数 + * @var integer|null + */ protected $total; - /** @var integer 每页的数量 */ + /** + * 每页数量 + * @var integer + */ protected $listRows; - /** @var bool 是否有下一页 */ + /** + * 是否有下一页 + * @var bool + */ protected $hasMore; - /** @var array 一些配置 */ + /** + * 分页配置 + * @var array + */ protected $options = [ 'var_page' => 'page', 'path' => '/', 'query' => [], - 'fragment' => '' + 'fragment' => '', ]; - protected function __construct($items, $listRows, $currentPage = null, $total = null, $simple = false, $options = []) + public function __construct($items, $listRows, $currentPage = null, $total = null, $simple = false, $options = []) { $this->options = array_merge($this->options, $options); - $this->options['path'] = $this->options['path'] != '/' ? rtrim($this->options['path'], '/') : $this->options['path']; + $this->options['path'] = '/' != $this->options['path'] ? rtrim($this->options['path'], '/') : $this->options['path']; $this->simple = $simple; $this->listRows = $listRows; + if (!$items instanceof Collection) { + $items = Collection::make($items); + } + if ($simple) { - if (!$items instanceof Collection) { - $items = Collection::make($items); - } $this->currentPage = $this->setCurrentPage($currentPage); $this->hasMore = count($items) > ($this->listRows); $items = $items->slice(0, $this->listRows); } else { $this->total = $total; - $this->lastPage = (int)ceil($total / $listRows); + $this->lastPage = (int) ceil($total / $listRows); $this->currentPage = $this->setCurrentPage($currentPage); $this->hasMore = $this->currentPage < $this->lastPage; } - - $this->items = PaginatorCollection::make($items, $this); + $this->items = $items; } /** + * @access public * @param $items * @param $listRows * @param null $currentPage - * @param bool $simple * @param null $total + * @param bool $simple * @param array $options - * @return PaginatorCollection + * @return Paginator */ public static function make($items, $listRows, $currentPage = null, $total = null, $simple = false, $options = []) { - $paginator = new static($items, $listRows, $currentPage, $total, $simple, $options); - return $paginator->items; + return new static($items, $listRows, $currentPage, $total, $simple, $options); } protected function setCurrentPage($currentPage) @@ -98,7 +126,8 @@ abstract class Paginator /** * 获取页码对应的链接 * - * @param $page + * @access protected + * @param $page * @return string */ protected function url($page) @@ -114,27 +143,31 @@ abstract class Paginator $parameters = []; $path = str_replace('[PAGE]', $page, $this->options['path']); } + if (count($this->options['query']) > 0) { $parameters = array_merge($this->options['query'], $parameters); } + $url = $path; if (!empty($parameters)) { - $url .= '?' . urldecode(http_build_query($parameters, null, '&')); + $url .= '?' . http_build_query($parameters, null, '&'); } + return $url . $this->buildFragment(); } /** * 自动获取当前页码 - * @param string $varPage - * @param int $default + * @access public + * @param string $varPage + * @param int $default * @return int */ public static function getCurrentPage($varPage = 'page', $default = 1) { - $page = Request::instance()->request($varPage); + $page = Container::get('request')->param($varPage); - if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int)$page >= 1) { + if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) { return $page; } @@ -143,11 +176,12 @@ abstract class Paginator /** * 自动获取当前的path + * @access public * @return string */ public static function getCurrentPath() { - return Request::instance()->baseUrl(); + return Container::get('request')->baseUrl(); } public function total() @@ -155,6 +189,7 @@ abstract class Paginator if ($this->simple) { throw new \DomainException('not support total'); } + return $this->total; } @@ -173,21 +208,24 @@ abstract class Paginator if ($this->simple) { throw new \DomainException('not support last'); } + return $this->lastPage; } /** * 数据是否足够分页 + * @access public * @return boolean */ public function hasPages() { - return !($this->currentPage == 1 && !$this->hasMore); + return !(1 == $this->currentPage && !$this->hasMore); } /** * 创建一组分页链接 * + * @access public * @param int $start * @param int $end * @return array @@ -206,18 +244,21 @@ abstract class Paginator /** * 设置URL锚点 * + * @access public * @param string|null $fragment * @return $this */ public function fragment($fragment) { $this->options['fragment'] = $fragment; + return $this; } /** * 添加URL参数 * + * @access public * @param array|string $key * @param string|null $value * @return $this @@ -239,10 +280,10 @@ abstract class Paginator return $this; } - /** * 构造锚点字符串 * + * @access public * @return string */ protected function buildFragment() @@ -252,7 +293,153 @@ abstract class Paginator /** * 渲染分页html + * @access public * @return mixed */ abstract public function render(); -} \ No newline at end of file + + public function items() + { + return $this->items->all(); + } + + public function getCollection() + { + return $this->items; + } + + public function isEmpty() + { + return $this->items->isEmpty(); + } + + /** + * 给每个元素执行个回调 + * + * @access public + * @param callable $callback + * @return $this + */ + public function each(callable $callback) + { + foreach ($this->items as $key => $item) { + $result = $callback($item, $key); + + if (false === $result) { + break; + } elseif (!is_object($item)) { + $this->items[$key] = $result; + } + } + + return $this; + } + + /** + * Retrieve an external iterator + * @access public + * @return Traversable An instance of an object implementing Iterator or + * Traversable + */ + public function getIterator() + { + return new ArrayIterator($this->items->all()); + } + + /** + * Whether a offset exists + * @access public + * @param mixed $offset + * @return bool + */ + public function offsetExists($offset) + { + return $this->items->offsetExists($offset); + } + + /** + * Offset to retrieve + * @access public + * @param mixed $offset + * @return mixed + */ + public function offsetGet($offset) + { + return $this->items->offsetGet($offset); + } + + /** + * Offset to set + * @access public + * @param mixed $offset + * @param mixed $value + */ + public function offsetSet($offset, $value) + { + $this->items->offsetSet($offset, $value); + } + + /** + * Offset to unset + * @access public + * @param mixed $offset + * @return void + * @since 5.0.0 + */ + public function offsetUnset($offset) + { + $this->items->offsetUnset($offset); + } + + /** + * Count elements of an object + */ + public function count() + { + return $this->items->count(); + } + + public function __toString() + { + return (string) $this->render(); + } + + public function toArray() + { + try { + $total = $this->total(); + } catch (\DomainException $e) { + $total = null; + } + + return [ + 'total' => $total, + 'per_page' => $this->listRows(), + 'current_page' => $this->currentPage(), + 'last_page' => $this->lastPage, + 'data' => $this->items->toArray(), + ]; + } + + /** + * Specify data which should be serialized to JSON + */ + public function jsonSerialize() + { + return $this->toArray(); + } + + public function __call($name, $arguments) + { + $collection = $this->getCollection(); + + $result = call_user_func_array([$collection, $name], $arguments); + + if ($result === $collection) { + return $this; + } + + return $result; + } + +} diff --git a/library/think/Process.php b/library/think/Process.php index 1982de2447f7f68093e43de58fe256658d1f763c..3b574db490258fd5030fb054e86f3c47190bfa5f 100644 --- a/library/think/Process.php +++ b/library/think/Process.php @@ -14,9 +14,9 @@ namespace think; use think\process\exception\Failed as ProcessFailedException; use think\process\exception\Timeout as ProcessTimeoutException; use think\process\pipes\Pipes; -use think\process\Utils; use think\process\pipes\Unix as UnixPipes; use think\process\pipes\Windows as WindowsPipes; +use think\process\Utils; class Process { @@ -47,10 +47,10 @@ class Process private $exitcode; private $fallbackExitcode; private $processInformation; - private $outputDisabled = false; + private $outputDisabled = false; private $stdout; private $stderr; - private $enhanceWindowsCompatibility = true; + private $enhanceWindowsCompatibility = true; private $enhanceSigchildCompatibility; private $process; private $status = self::STATUS_READY; @@ -114,12 +114,13 @@ class Process /** * 构造方法 - * @param string $commandline 指令 - * @param string|null $cwd 工作目录 - * @param array|null $env 环境变量 - * @param string|null $input 输入 - * @param int|float|null $timeout 超时时间 - * @param array $options proc_open的选项 + * @access public + * @param string $commandline 指令 + * @param string|null $cwd 工作目录 + * @param array|null $env 环境变量 + * @param string|null $input 输入 + * @param int|float|null $timeout 超时时间 + * @param array $options proc_open的选项 * @throws \RuntimeException * @api */ @@ -132,7 +133,7 @@ class Process $this->commandline = $commandline; $this->cwd = $cwd; - if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DS)) { + if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) { $this->cwd = getcwd(); } if (null !== $env) { @@ -141,13 +142,13 @@ class Process $this->input = $input; $this->setTimeout($timeout); - $this->useFileHandles = '\\' === DS; + $this->useFileHandles = '\\' === DIRECTORY_SEPARATOR; $this->pty = false; $this->enhanceWindowsCompatibility = true; - $this->enhanceSigchildCompatibility = '\\' !== DS && $this->isSigchildEnabled(); + $this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled(); $this->options = array_replace([ 'suppress_errors' => true, - 'binary_pipes' => true + 'binary_pipes' => true, ], $options); } @@ -163,7 +164,8 @@ class Process /** * 运行指令 - * @param callback|null $callback + * @access public + * @param callback|null $callback * @return int */ public function run($callback = null) @@ -175,7 +177,8 @@ class Process /** * 运行指令 - * @param callable|null $callback + * @access public + * @param callable|null $callback * @return self * @throws \RuntimeException * @throws ProcessFailedException @@ -195,7 +198,8 @@ class Process /** * 启动进程并写到 STDIN 输入后返回。 - * @param callable|null $callback + * @access public + * @param callable|null $callback * @throws \RuntimeException * @throws \RuntimeException * @throws \LogicException @@ -216,7 +220,7 @@ class Process $commandline = $this->commandline; - if ('\\' === DS && $this->enhanceWindowsCompatibility) { + if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) { $commandline = 'cmd /V:ON /E:ON /C "(' . $commandline . ')'; foreach ($this->processPipes->getFiles() as $offset => $filename) { $commandline .= ' ' . $offset . '>' . Utils::escapeArgument($filename); @@ -245,7 +249,8 @@ class Process /** * 重启进程 - * @param callable|null $callback + * @access public + * @param callable|null $callback * @return Process * @throws \RuntimeException * @throws \RuntimeException @@ -264,7 +269,8 @@ class Process /** * 等待要终止的进程 - * @param callable|null $callback + * @access public + * @param callable|null $callback * @return int */ public function wait($callback = null) @@ -278,8 +284,8 @@ class Process do { $this->checkTimeout(); - $running = '\\' === DS ? $this->isRunning() : $this->processPipes->areOpen(); - $close = '\\' !== DS || !$running; + $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen(); + $close = '\\' !== DIRECTORY_SEPARATOR || !$running; $this->readPipes(true, $close); } while ($running); @@ -296,6 +302,7 @@ class Process /** * 获取PID + * @access public * @return int|null * @throws \RuntimeException */ @@ -312,7 +319,8 @@ class Process /** * 将一个 POSIX 信号发送到进程中 - * @param int $signal + * @access public + * @param int $signal * @return Process */ public function signal($signal) @@ -324,6 +332,7 @@ class Process /** * 禁用从底层过程获取输出和错误输出。 + * @access public * @return Process */ public function disableOutput() @@ -342,6 +351,7 @@ class Process /** * 开启从底层过程获取输出和错误输出。 + * @access public * @return Process * @throws \RuntimeException */ @@ -358,6 +368,7 @@ class Process /** * 输出是否禁用 + * @access public * @return bool */ public function isOutputDisabled() @@ -367,9 +378,9 @@ class Process /** * 获取当前的输出管道 + * @access public * @return string * @throws \LogicException - * @throws \LogicException * @api */ public function getOutput() @@ -380,13 +391,14 @@ class Process $this->requireProcessIsStarted(__FUNCTION__); - $this->readPipes(false, '\\' === DS ? !$this->processInformation['running'] : true); + $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true); return $this->stdout; } /** * 以增量方式返回的输出结果。 + * @access public * @return string */ public function getIncrementalOutput() @@ -408,6 +420,7 @@ class Process /** * 清空输出 + * @access public * @return Process */ public function clearOutput() @@ -420,6 +433,7 @@ class Process /** * 返回当前的错误输出的过程 (STDERR)。 + * @access public * @return string */ public function getErrorOutput() @@ -430,13 +444,14 @@ class Process $this->requireProcessIsStarted(__FUNCTION__); - $this->readPipes(false, '\\' === DS ? !$this->processInformation['running'] : true); + $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true); return $this->stderr; } /** * 以增量方式返回 errorOutput + * @access public * @return string */ public function getIncrementalErrorOutput() @@ -458,6 +473,7 @@ class Process /** * 清空 errorOutput + * @access public * @return Process */ public function clearErrorOutput() @@ -470,6 +486,7 @@ class Process /** * 获取退出码 + * @access public * @return null|int */ public function getExitCode() @@ -485,12 +502,13 @@ class Process /** * 获取退出文本 + * @access public * @return null|string */ public function getExitCodeText() { if (null === $exitcode = $this->getExitCode()) { - return null; + return; } return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error'; @@ -498,6 +516,7 @@ class Process /** * 检查是否成功 + * @access public * @return bool */ public function isSuccessful() @@ -507,6 +526,7 @@ class Process /** * 是否未捕获的信号已被终止子进程 + * @access public * @return bool */ public function hasBeenSignaled() @@ -524,6 +544,7 @@ class Process /** * 返回导致子进程终止其执行的数。 + * @access public * @return int */ public function getTermSignal() @@ -541,6 +562,7 @@ class Process /** * 检查子进程信号是否已停止 + * @access public * @return bool */ public function hasBeenStopped() @@ -554,6 +576,7 @@ class Process /** * 返回导致子进程停止其执行的数。 + * @access public * @return int */ public function getStopSignal() @@ -567,6 +590,7 @@ class Process /** * 检查是否正在运行 + * @access public * @return bool */ public function isRunning() @@ -582,26 +606,29 @@ class Process /** * 检查是否已开始 + * @access public * @return bool */ public function isStarted() { - return $this->status != self::STATUS_READY; + return self::STATUS_READY != $this->status; } /** * 检查是否已终止 + * @access public * @return bool */ public function isTerminated() { $this->updateStatus(false); - return $this->status == self::STATUS_TERMINATED; + return self::STATUS_TERMINATED == $this->status; } /** * 获取当前的状态 + * @access public * @return string */ public function getStatus() @@ -613,11 +640,12 @@ class Process /** * 终止进程 + * @access public */ public function stop() { if ($this->isRunning()) { - if ('\\' === DS && !$this->isSigchildEnabled()) { + if ('\\' === DIRECTORY_SEPARATOR && !$this->isSigchildEnabled()) { exec(sprintf('taskkill /F /T /PID %d 2>&1', $this->getPid()), $output, $exitCode); if ($exitCode > 0) { throw new \RuntimeException('Unable to kill the process'); @@ -642,40 +670,44 @@ class Process /** * 添加一行输出 + * @access public * @param string $line */ public function addOutput($line) - { +{ $this->lastOutputTime = microtime(true); $this->stdout .= $line; } /** * 添加一行错误输出 + * @access public * @param string $line */ public function addErrorOutput($line) - { +{ $this->lastOutputTime = microtime(true); $this->stderr .= $line; } /** * 获取被执行的指令 + * @access public * @return string */ public function getCommandLine() - { +{ return $this->commandline; } /** * 设置指令 + * @access public * @param string $commandline * @return self */ public function setCommandLine($commandline) - { +{ $this->commandline = $commandline; return $this; @@ -683,29 +715,32 @@ class Process /** * 获取超时时间 + * @access public * @return float|null */ public function getTimeout() - { +{ return $this->timeout; } /** * 获取idle超时时间 + * @access public * @return float|null */ public function getIdleTimeout() - { +{ return $this->idleTimeout; } /** * 设置超时时间 - * @param int|float|null $timeout + * @access public + * @param int|float|null $timeout * @return self */ public function setTimeout($timeout) - { +{ $this->timeout = $this->validateTimeout($timeout); return $this; @@ -713,11 +748,12 @@ class Process /** * 设置idle超时时间 - * @param int|float|null $timeout + * @access public + * @param int|float|null $timeout * @return self */ public function setIdleTimeout($timeout) - { +{ if (null !== $timeout && $this->outputDisabled) { throw new \LogicException('Idle timeout can not be set while the output is disabled.'); } @@ -729,59 +765,64 @@ class Process /** * 设置TTY - * @param bool $tty + * @access public + * @param bool $tty * @return self */ public function setTty($tty) - { - if ('\\' === DS && $tty) { +{ + if ('\\' === DIRECTORY_SEPARATOR && $tty) { throw new \RuntimeException('TTY mode is not supported on Windows platform.'); } if ($tty && (!file_exists('/dev/tty') || !is_readable('/dev/tty'))) { throw new \RuntimeException('TTY mode requires /dev/tty to be readable.'); } - $this->tty = (bool)$tty; + $this->tty = (bool) $tty; return $this; } /** * 检查是否是tty模式 + * @access public * @return bool */ public function isTty() - { +{ return $this->tty; } /** * 设置pty模式 - * @param bool $bool + * @access public + * @param bool $bool * @return self */ public function setPty($bool) - { - $this->pty = (bool)$bool; +{ + $this->pty = (bool) $bool; return $this; } /** * 是否是pty模式 + * @access public * @return bool */ public function isPty() - { +{ return $this->pty; } /** * 获取工作目录 + * @access public * @return string|null */ public function getWorkingDirectory() - { +{ if (null === $this->cwd) { return getcwd() ?: null; } @@ -791,11 +832,12 @@ class Process /** * 设置工作目录 - * @param string $cwd + * @access public + * @param string $cwd * @return self */ public function setWorkingDirectory($cwd) - { +{ $this->cwd = $cwd; return $this; @@ -803,27 +845,29 @@ class Process /** * 获取环境变量 + * @access public * @return array */ public function getEnv() - { +{ return $this->env; } /** * 设置环境变量 - * @param array $env + * @access public + * @param array $env * @return self */ public function setEnv(array $env) - { +{ $env = array_filter($env, function ($value) { return !is_array($value); }); $this->env = []; foreach ($env as $key => $value) { - $this->env[(binary)$key] = (binary)$value; + $this->env[(binary) $key] = (binary) $value; } return $this; @@ -831,20 +875,22 @@ class Process /** * 获取输入 + * @access public * @return null|string */ public function getInput() - { +{ return $this->input; } /** * 设置输入 - * @param mixed $input + * @access public + * @param mixed $input * @return self */ public function setInput($input) - { +{ if ($this->isRunning()) { throw new \LogicException('Input can not be set while the process is running.'); } @@ -856,20 +902,22 @@ class Process /** * 获取proc_open的选项 + * @access public * @return array */ public function getOptions() - { +{ return $this->options; } /** * 设置proc_open的选项 - * @param array $options + * @access public + * @param array $options * @return self */ public function setOptions(array $options) - { +{ $this->options = $options; return $this; @@ -877,42 +925,46 @@ class Process /** * 是否兼容windows + * @access public * @return bool */ public function getEnhanceWindowsCompatibility() - { +{ return $this->enhanceWindowsCompatibility; } /** * 设置是否兼容windows - * @param bool $enhance + * @access public + * @param bool $enhance * @return self */ public function setEnhanceWindowsCompatibility($enhance) - { - $this->enhanceWindowsCompatibility = (bool)$enhance; +{ + $this->enhanceWindowsCompatibility = (bool) $enhance; return $this; } /** * 返回是否 sigchild 兼容模式激活 + * @access public * @return bool */ public function getEnhanceSigchildCompatibility() - { +{ return $this->enhanceSigchildCompatibility; } /** * 激活 sigchild 兼容性模式。 - * @param bool $enhance + * @access public + * @param bool $enhance * @return self */ public function setEnhanceSigchildCompatibility($enhance) - { - $this->enhanceSigchildCompatibility = (bool)$enhance; +{ + $this->enhanceSigchildCompatibility = (bool) $enhance; return $this; } @@ -921,8 +973,8 @@ class Process * 是否超时 */ public function checkTimeout() - { - if ($this->status !== self::STATUS_STARTED) { +{ + if (self::STATUS_STARTED !== $this->status) { return; } @@ -941,17 +993,18 @@ class Process /** * 是否支持pty + * @access public * @return bool */ public static function isPtySupported() - { +{ static $result; if (null !== $result) { return $result; } - if ('\\' === DS) { + if ('\\' === DIRECTORY_SEPARATOR) { return $result = false; } @@ -967,11 +1020,12 @@ class Process /** * 创建所需的 proc_open 的描述符 + * @access private * @return array */ private function getDescriptors() - { - if ('\\' === DS) { +{ + if ('\\' === DIRECTORY_SEPARATOR) { $this->processPipes = WindowsPipes::create($this, $this->input); } else { $this->processPipes = UnixPipes::create($this, $this->input); @@ -990,11 +1044,12 @@ class Process /** * 建立 wait () 使用的回调。 - * @param callable|null $callback + * @access protected + * @param callable|null $callback * @return callable */ protected function buildCallback($callback) - { +{ $out = self::OUT; $callback = function ($type, $data) use ($callback, $out) { if ($out == $type) { @@ -1013,10 +1068,11 @@ class Process /** * 更新状态 + * @access protected * @param bool $blocking */ protected function updateStatus($blocking) - { +{ if (self::STATUS_STARTED !== $this->status) { return; } @@ -1024,7 +1080,7 @@ class Process $this->processInformation = proc_get_status($this->process); $this->captureExitCode(); - $this->readPipes($blocking, '\\' === DS ? !$this->processInformation['running'] : true); + $this->readPipes($blocking, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true); if (!$this->processInformation['running']) { $this->close(); @@ -1033,10 +1089,11 @@ class Process /** * 是否开启 '--enable-sigchild' + * @access protected * @return bool */ protected function isSigchildEnabled() - { +{ if (null !== self::$sigchild) { return self::$sigchild; } @@ -1053,12 +1110,13 @@ class Process /** * 验证是否超时 - * @param int|float|null $timeout + * @access private + * @param int|float|null $timeout * @return float|null */ private function validateTimeout($timeout) - { - $timeout = (float)$timeout; +{ + $timeout = (float) $timeout; if (0.0 === $timeout) { $timeout = null; @@ -1071,19 +1129,20 @@ class Process /** * 读取pipes - * @param bool $blocking - * @param bool $close + * @access private + * @param bool $blocking + * @param bool $close */ private function readPipes($blocking, $close) - { +{ $result = $this->processPipes->readAndWrite($blocking, $close); $callback = $this->callback; foreach ($result as $type => $data) { if (3 == $type) { - $this->fallbackExitcode = (int)$data; + $this->fallbackExitcode = (int) $data; } else { - $callback($type === self::STDOUT ? self::OUT : self::ERR, $data); + $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data); } } } @@ -1092,7 +1151,7 @@ class Process * 捕获退出码 */ private function captureExitCode() - { +{ if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) { $this->exitcode = $this->processInformation['exitcode']; } @@ -1100,10 +1159,11 @@ class Process /** * 关闭资源 + * @access private * @return int 退出码 */ private function close() - { +{ $this->processPipes->close(); if (is_resource($this->process)) { $exitcode = proc_close($this->process); @@ -1117,7 +1177,7 @@ class Process if (-1 === $this->exitcode && null !== $this->fallbackExitcode) { $this->exitcode = $this->fallbackExitcode; } elseif (-1 === $this->exitcode && $this->processInformation['signaled'] - && 0 < $this->processInformation['termsig'] + && 0 < $this->processInformation['termsig'] ) { $this->exitcode = 128 + $this->processInformation['termsig']; } @@ -1129,7 +1189,7 @@ class Process * 重置数据 */ private function resetProcessData() - { +{ $this->starttime = null; $this->callback = null; $this->exitcode = null; @@ -1146,12 +1206,13 @@ class Process /** * 将一个 POSIX 信号发送到进程中。 - * @param int $signal - * @param bool $throwException + * @access private + * @param int $signal + * @param bool $throwException * @return bool */ private function doSignal($signal, $throwException) - { +{ if (!$this->isRunning()) { if ($throwException) { throw new \LogicException('Can not send signal on a non running process.'); @@ -1183,10 +1244,11 @@ class Process /** * 确保进程已经开启 - * @param string $functionName + * @access private + * @param string $functionName */ private function requireProcessIsStarted($functionName) - { +{ if (!$this->isStarted()) { throw new \LogicException(sprintf('Process must be started before calling %s.', $functionName)); } @@ -1194,12 +1256,13 @@ class Process /** * 确保进程已经终止 - * @param string $functionName + * @access private + * @param string $functionName */ private function requireProcessIsTerminated($functionName) - { +{ if (!$this->isTerminated()) { throw new \LogicException(sprintf('Process must be terminated before calling %s.', $functionName)); } } -} \ No newline at end of file +} diff --git a/library/think/Request.php b/library/think/Request.php index 077e190df002d42ea706a517cc3198d464bc18ff..c45b978eb585b954ee8c56d1fd2117f1908623d5 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,197 +11,363 @@ namespace think; -use think\Config; -use think\Exception; -use think\File; -use think\Session; +use think\facade\Cookie; +use think\facade\Session; class Request { /** - * @var object 对象实例 - */ - protected static $instance; + * 配置参数 + * @var array + */ + protected $config = [ + // 表单请求类型伪装变量 + 'var_method' => '_method', + // 表单ajax伪装变量 + 'var_ajax' => '_ajax', + // 表单pjax伪装变量 + 'var_pjax' => '_pjax', + // PATHINFO变量名 用于兼容模式 + 'var_pathinfo' => 's', + // 兼容PATH_INFO获取 + 'pathinfo_fetch' => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'], + // 默认全局过滤方法 用逗号分隔多个 + 'default_filter' => '', + // 域名根,如thinkphp.cn + 'url_domain_root' => '', + // HTTPS代理标识 + 'https_agent_name' => '', + // IP代理获取标识 + 'http_agent_ip' => 'HTTP_X_REAL_IP', + // URL伪静态后缀 + 'url_html_suffix' => 'html', + ]; + /** + * 请求类型 + * @var string + */ protected $method; + /** - * @var string 域名 + * 域名(含协议及端口) + * @var string */ protected $domain; /** - * @var string URL地址 + * 子域名 + * @var string + */ + protected $subDomain; + + /** + * 泛域名 + * @var string + */ + protected $panDomain; + + /** + * 当前URL地址 + * @var string */ protected $url; /** - * @var string 基础URL + * 基础URL + * @var string */ protected $baseUrl; /** - * @var string 当前执行的文件 + * 当前执行的文件 + * @var string */ protected $baseFile; /** - * @var string 访问的ROOT地址 + * 访问的ROOT地址 + * @var string */ protected $root; /** - * @var string pathinfo + * pathinfo + * @var string */ protected $pathinfo; /** - * @var string pathinfo(不含后缀) + * pathinfo(不含后缀) + * @var string */ protected $path; /** - * @var array 当前路由信息 + * 当前路由信息 + * @var array */ protected $routeInfo = []; /** - * @var array 当前调度信息 + * 当前调度信息 + * @var \think\route\Dispatch + */ + protected $dispatch; + + /** + * 当前模块名 + * @var string */ - protected $dispatch = []; protected $module; + + /** + * 当前控制器名 + * @var string + */ protected $controller; + + /** + * 当前操作名 + * @var string + */ protected $action; - // 当前语言集 + + /** + * 当前语言集 + * @var string + */ protected $langset; /** - * @var array 请求参数 + * 当前请求参数 + * @var array + */ + protected $param = []; + + /** + * 当前GET参数 + * @var array + */ + protected $get = []; + + /** + * 当前POST参数 + * @var array + */ + protected $post = []; + + /** + * 当前REQUEST参数 + * @var array */ - protected $param = []; - protected $get = []; - protected $post = []; protected $request = []; - protected $route = []; + + /** + * 当前ROUTE参数 + * @var array + */ + protected $route = []; + + /** + * 当前PUT参数 + * @var array + */ protected $put; + + /** + * 当前SESSION参数 + * @var array + */ protected $session = []; - protected $file = []; - protected $cookie = []; - protected $server = []; - protected $header = []; /** - * @var array 资源类型 + * 当前FILE参数 + * @var array + */ + protected $file = []; + + /** + * 当前COOKIE参数 + * @var array + */ + protected $cookie = []; + + /** + * 当前SERVER参数 + * @var array + */ + protected $server = []; + + /** + * 当前ENV参数 + * @var array + */ + protected $env = []; + + /** + * 当前HEADER参数 + * @var array + */ + protected $header = []; + + /** + * 资源类型定义 + * @var array */ protected $mimeType = [ - 'xml' => 'application/xml,text/xml,application/x-xml', - 'json' => 'application/json,text/x-json,application/jsonrequest,text/json', - 'js' => 'text/javascript,application/javascript,application/x-javascript', - 'css' => 'text/css', - 'rss' => 'application/rss+xml', - 'yaml' => 'application/x-yaml,text/yaml', - 'atom' => 'application/atom+xml', - 'pdf' => 'application/pdf', - 'text' => 'text/plain', - 'png' => 'image/png', - 'jpg' => 'image/jpg,image/jpeg,image/pjpeg', - 'gif' => 'image/gif', - 'csv' => 'text/csv', - 'html' => 'text/html,application/xhtml+xml,*/*', + 'xml' => 'application/xml,text/xml,application/x-xml', + 'json' => 'application/json,text/x-json,application/jsonrequest,text/json', + 'js' => 'text/javascript,application/javascript,application/x-javascript', + 'css' => 'text/css', + 'rss' => 'application/rss+xml', + 'yaml' => 'application/x-yaml,text/yaml', + 'atom' => 'application/atom+xml', + 'pdf' => 'application/pdf', + 'text' => 'text/plain', + 'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*', + 'csv' => 'text/csv', + 'html' => 'text/html,application/xhtml+xml,*/*', ]; + /** + * 当前请求内容 + * @var string + */ protected $content; - // 全局过滤规则 + /** + * 全局过滤规则 + * @var array + */ protected $filter; - // Hook扩展方法 - protected static $hook = []; - // 绑定的属性 - protected $bind = []; + + /** + * 扩展方法 + * @var array + */ + protected $hook = []; + + /** + * php://input内容 + * @var string + */ // php://input protected $input; - // 请求缓存 + + /** + * 请求缓存 + * @var array + */ protected $cache; + /** + * 缓存是否检查 + * @var bool + */ + protected $isCheckCache; + + /** + * 请求安全Key + * @var string + */ + protected $secureKey; + + /** + * 是否合并Param + * @var bool + */ + protected $mergeParam = false; + /** * 架构函数 * @access public - * @param array $options 参数 + * @param array $options 参数 */ - public function __construct($options = []) + public function __construct(array $options = []) { - foreach ($options as $name => $item) { - if (property_exists($this, $name)) { - $this->$name = $item; - } - } - if (is_null($this->filter)) { - $this->filter = Config::get('default_filter'); - } + $this->init($options); + // 保存 php://input $this->input = file_get_contents('php://input'); } + public function init(array $options = []) + { + $this->config = array_merge($this->config, $options); + + if (is_null($this->filter) && !empty($this->config['default_filter'])) { + $this->filter = $this->config['default_filter']; + } + } + + public function config($name = null) + { + if (is_null($name)) { + return $this->config; + } + return isset($this->config[$name]) ? $this->config[$name] : null; + } + + public static function __make(App $app, Config $config) + { + $request = new static($config->pull('app')); + + $request->server = $_SERVER; + $request->env = $app['env']->get(); + + return $request; + } + public function __call($method, $args) { - if (array_key_exists($method, self::$hook)) { + if (array_key_exists($method, $this->hook)) { array_unshift($args, $this); - return call_user_func_array(self::$hook[$method], $args); - } else { - throw new Exception('method not exists:' . __CLASS__ . '->' . $method); + return call_user_func_array($this->hook[$method], $args); } + + throw new Exception('method not exists:' . static::class . '->' . $method); } /** * Hook 方法注入 * @access public - * @param string|array $method 方法名 - * @param mixed $callback callable + * @param string|array $method 方法名 + * @param mixed $callback callable * @return void */ - public static function hook($method, $callback = null) + public function hook($method, $callback = null) { if (is_array($method)) { - self::$hook = array_merge(self::$hook, $method); + $this->hook = array_merge($this->hook, $method); } else { - self::$hook[$method] = $callback; + $this->hook[$method] = $callback; } } - /** - * 初始化 - * @access public - * @param array $options 参数 - * @return \think\Request - */ - public static function instance($options = []) - { - if (is_null(self::$instance)) { - self::$instance = new static($options); - } - return self::$instance; - } - /** * 创建一个URL请求 * @access public - * @param string $uri URL地址 - * @param string $method 请求类型 - * @param array $params 请求参数 - * @param array $cookie - * @param array $files - * @param array $server - * @param string $content + * @param string $uri URL地址 + * @param string $method 请求类型 + * @param array $params 请求参数 + * @param array $cookie + * @param array $files + * @param array $server + * @param string $content * @return \think\Request */ - public static function create($uri, $method = 'GET', $params = [], $cookie = [], $files = [], $server = [], $content = null) + public function create($uri, $method = 'GET', $params = [], $cookie = [], $files = [], $server = [], $content = null) { $server['PATH_INFO'] = ''; $server['REQUEST_METHOD'] = strtoupper($method); $info = parse_url($uri); + if (isset($info['host'])) { $server['SERVER_NAME'] = $info['host']; $server['HTTP_HOST'] = $info['host']; } + if (isset($info['scheme'])) { if ('https' === $info['scheme']) { $server['HTTPS'] = 'on'; @@ -211,26 +377,34 @@ class Request $server['SERVER_PORT'] = 80; } } + if (isset($info['port'])) { $server['SERVER_PORT'] = $info['port']; $server['HTTP_HOST'] = $server['HTTP_HOST'] . ':' . $info['port']; } + if (isset($info['user'])) { $server['PHP_AUTH_USER'] = $info['user']; } + if (isset($info['pass'])) { $server['PHP_AUTH_PW'] = $info['pass']; } + if (!isset($info['path'])) { $info['path'] = '/'; } + $options = []; $queryString = ''; + + $options[strtolower($method)] = $params; + if (isset($info['query'])) { parse_str(html_entity_decode($info['query']), $query); if (!empty($params)) { $params = array_replace($query, $params); - $queryString = http_build_query($query, '', '&'); + $queryString = http_build_query($params, '', '&'); } else { $params = $query; $queryString = $info['query']; @@ -238,6 +412,12 @@ class Request } elseif (!empty($params)) { $queryString = http_build_query($params, '', '&'); } + + if ($queryString) { + parse_str($queryString, $get); + $options['get'] = isset($options['get']) ? array_merge($get, $options['get']) : $get; + } + $server['REQUEST_URI'] = $info['path'] . ('' !== $queryString ? '?' . $queryString : ''); $server['QUERY_STRING'] = $queryString; $options['cookie'] = $cookie; @@ -248,125 +428,211 @@ class Request $options['baseUrl'] = $info['path']; $options['pathinfo'] = '/' == $info['path'] ? '/' : ltrim($info['path'], '/'); $options['method'] = $server['REQUEST_METHOD']; - $options['domain'] = $info['scheme'] . '://' . $server['HTTP_HOST']; + $options['domain'] = isset($info['scheme']) ? $info['scheme'] . '://' . $server['HTTP_HOST'] : ''; $options['content'] = $content; - self::$instance = new self($options); - return self::$instance; + + $request = new static(); + foreach ($options as $name => $item) { + if (property_exists($request, $name)) { + $request->$name = $item; + } + } + + return $request; + } + + /** + * 获取当前包含协议、端口的域名 + * @access public + * @param bool $port 是否需要去除端口号 + * @return string + */ + public function domain($port = false) + { + return $this->scheme() . '://' . $this->host($port); + } + + /** + * 获取当前根域名 + * @access public + * @return string + */ + public function rootDomain() + { + $root = $this->config['url_domain_root']; + + if (!$root) { + $item = explode('.', $this->host(true)); + $count = count($item); + $root = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0]; + } + + return $root; } /** - * 获取当前包含协议的域名 + * 获取当前子域名 * @access public - * @param string $domain 域名 * @return string */ - public function domain($domain = null) + public function subDomain() { - if (!is_null($domain)) { - $this->domain = $domain; - return $this; - } elseif (!$this->domain) { - $this->domain = $this->scheme() . '://' . $this->host(); + if (is_null($this->subDomain)) { + // 获取当前主域名 + $rootDomain = $this->config['url_domain_root']; + + if ($rootDomain) { + // 配置域名根 例如 thinkphp.cn 163.com.cn 如果是国家级域名 com.cn net.cn 之类的域名需要配置 + $domain = explode('.', rtrim(stristr($this->host(true), $rootDomain, true), '.')); + } else { + $domain = explode('.', $this->host(true), -2); + } + + $this->subDomain = implode('.', $domain); } - return $this->domain; + + return $this->subDomain; + } + + /** + * 设置当前泛域名的值 + * @access public + * @param string $domain 域名 + * @return $this + */ + public function setPanDomain($domain) + { + $this->panDomain = $domain; + return $this; + } + + /** + * 获取当前泛域名的值 + * @access public + * @return string + */ + public function panDomain() + { + return $this->panDomain; } /** * 获取当前完整URL 包括QUERY_STRING * @access public - * @param string|true $url URL地址 true 带域名获取 + * @param bool $complete 是否包含域名 * @return string */ - public function url($url = null) + public function url($complete = false) { - if (!is_null($url) && true !== $url) { - $this->url = $url; - return $this; - } elseif (!$this->url) { - if (IS_CLI) { + if (!$this->url) { + if ($this->isCli()) { $this->url = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : ''; - } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) { - $this->url = $_SERVER['HTTP_X_REWRITE_URL']; - } elseif (isset($_SERVER['REQUEST_URI'])) { - $this->url = $_SERVER['REQUEST_URI']; - } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { - $this->url = $_SERVER['ORIG_PATH_INFO'] . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : ''); + } elseif ($this->server('HTTP_X_REWRITE_URL')) { + $this->url = $this->server('HTTP_X_REWRITE_URL'); + } elseif ($this->server('REQUEST_URI')) { + $this->url = $this->server('REQUEST_URI'); + } elseif ($this->server('ORIG_PATH_INFO')) { + $this->url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : ''); } else { $this->url = ''; } } - return true === $url ? $this->domain() . $this->url : $this->url; + + return $complete ? $this->domain() . $this->url : $this->url; } /** * 获取当前URL 不含QUERY_STRING * @access public - * @param string $url URL地址 - * @return string + * @param bool $domain 是否包含域名 + * @return string|$this */ - public function baseUrl($url = null) + public function baseUrl($domain = false) { - if (!is_null($url) && true !== $url) { - $this->baseUrl = $url; - return $this; - } elseif (!$this->baseUrl) { + if (!$this->baseUrl) { $str = $this->url(); $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str; } - return true === $url ? $this->domain() . $this->baseUrl : $this->baseUrl; + + return $domain ? $this->domain() . $this->baseUrl : $this->baseUrl; } /** - * 获取当前执行的文件 SCRIPT_NAME + * 设置或获取当前执行的文件 SCRIPT_NAME * @access public - * @param string $file 当前执行的文件 - * @return string + * @param bool $domain 是否包含域名 + * @return string|$this */ - public function baseFile($file = null) + public function baseFile($domain = false) { - if (!is_null($file) && true !== $file) { - $this->baseFile = $file; - return $this; - } elseif (!$this->baseFile) { + if (!$this->baseFile) { $url = ''; - if (!IS_CLI) { - $script_name = basename($_SERVER['SCRIPT_FILENAME']); - if (basename($_SERVER['SCRIPT_NAME']) === $script_name) { - $url = $_SERVER['SCRIPT_NAME']; - } elseif (basename($_SERVER['PHP_SELF']) === $script_name) { - $url = $_SERVER['PHP_SELF']; - } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $script_name) { - $url = $_SERVER['ORIG_SCRIPT_NAME']; - } elseif (($pos = strpos($_SERVER['PHP_SELF'], '/' . $script_name)) !== false) { - $url = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $script_name; - } elseif (isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['DOCUMENT_ROOT']) === 0) { - $url = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME'])); + if (!$this->isCli()) { + $script_name = basename($this->server('SCRIPT_FILENAME')); + if (basename($this->server('SCRIPT_NAME')) === $script_name) { + $url = $this->server('SCRIPT_NAME'); + } elseif (basename($this->server('PHP_SELF')) === $script_name) { + $url = $this->server('PHP_SELF'); + } elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) { + $url = $this->server('ORIG_SCRIPT_NAME'); + } elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) { + $url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name; + } elseif ($this->server('DOCUMENT_ROOT') && strpos($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT')) === 0) { + $url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME'))); } } $this->baseFile = $url; } - return true === $file ? $this->domain() . $this->baseFile : $this->baseFile; + + return $domain ? $this->domain() . $this->baseFile : $this->baseFile; + } + + /** + * 设置URL访问根地址 + * @access public + * @param string $url URL地址 + * @return string|$this + */ + public function setRoot($url = null) + { + $this->root = $url; + return $this; } /** * 获取URL访问根地址 * @access public - * @param string $url URL地址 - * @return string + * @param bool $domain 是否包含域名 + * @return string|$this */ - public function root($url = null) + public function root($domain = false) { - if (!is_null($url) && true !== $url) { - $this->root = $url; - return $this; - } elseif (!$this->root) { + if (!$this->root) { $file = $this->baseFile(); if ($file && 0 !== strpos($this->url(), $file)) { $file = str_replace('\\', '/', dirname($file)); } $this->root = rtrim($file, '/'); } - return true === $url ? $this->domain() . $this->root : $this->root; + + return $domain ? $this->domain() . $this->root : $this->root; + } + + /** + * 获取URL访问根目录 + * @access public + * @return string + */ + public function rootUrl() + { + $base = $this->root(); + $root = strpos($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base; + + if ('' != $root) { + $root = '/' . ltrim($root, '/'); + } + + return $root; } /** @@ -377,27 +643,33 @@ class Request public function pathinfo() { if (is_null($this->pathinfo)) { - if (isset($_GET[Config::get('var_pathinfo')])) { + if (isset($_GET[$this->config['var_pathinfo']])) { // 判断URL里面是否有兼容模式参数 - $_SERVER['PATH_INFO'] = $_GET[Config::get('var_pathinfo')]; - unset($_GET[Config::get('var_pathinfo')]); - } elseif (IS_CLI) { + $pathinfo = $_GET[$this->config['var_pathinfo']]; + unset($_GET[$this->config['var_pathinfo']]); + } elseif ($this->isCli()) { // CLI模式下 index.php module/controller/action/params/... - $_SERVER['PATH_INFO'] = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : ''; + $pathinfo = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : ''; + } elseif ('cli-server' == PHP_SAPI) { + $pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI'); + } elseif ($this->server('PATH_INFO')) { + $pathinfo = $this->server('PATH_INFO'); } // 分析PATHINFO信息 - if (!isset($_SERVER['PATH_INFO'])) { - foreach (Config::get('pathinfo_fetch') as $type) { - if (!empty($_SERVER[$type])) { - $_SERVER['PATH_INFO'] = (0 === strpos($_SERVER[$type], $_SERVER['SCRIPT_NAME'])) ? - substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME'])) : $_SERVER[$type]; + if (!isset($pathinfo)) { + foreach ($this->config['pathinfo_fetch'] as $type) { + if ($this->server($type)) { + $pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ? + substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type); break; } } } - $this->pathinfo = empty($_SERVER['PATH_INFO']) ? '/' : ltrim($_SERVER['PATH_INFO'], '/'); + + $this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/'); } + return $this->pathinfo; } @@ -409,7 +681,7 @@ class Request public function path() { if (is_null($this->path)) { - $suffix = Config::get('url_html_suffix'); + $suffix = $this->config['url_html_suffix']; $pathinfo = $this->pathinfo(); if (false === $suffix) { // 禁止伪静态访问 @@ -422,6 +694,7 @@ class Request $this->path = preg_replace('/\.' . $this->ext() . '$/i', '', $pathinfo); } } + return $this->path; } @@ -438,12 +711,12 @@ class Request /** * 获取当前请求的时间 * @access public - * @param bool $float 是否使用浮点类型 + * @param bool $float 是否使用浮点类型 * @return integer|float */ public function time($float = false) { - return $float ? $_SERVER['REQUEST_TIME_FLOAT'] : $_SERVER['REQUEST_TIME']; + return $float ? $this->server('REQUEST_TIME_FLOAT') : $this->server('REQUEST_TIME'); } /** @@ -453,27 +726,29 @@ class Request */ public function type() { - $accept = isset($this->server['HTTP_ACCEPT']) ? $this->server['HTTP_ACCEPT'] : $_SERVER['HTTP_ACCEPT']; + $accept = $this->server('HTTP_ACCEPT'); + if (empty($accept)) { return false; } foreach ($this->mimeType as $key => $val) { - $array = explode(',', $val); - foreach ($array as $k => $v) { - if (stristr($accept, $v)) { + $array = array_flip(explode(',', $val)); + foreach ($accept as $v) { + if (isset($array[$v])) { return $key; } } } + return false; } /** * 设置资源类型 * @access public - * @param string|array $type 资源类型名 - * @param string $val 资源类型 + * @param string|array $type 资源类型名 + * @param string $val 资源类型 * @return void */ public function mimeType($type, $val = '') @@ -488,24 +763,26 @@ class Request /** * 当前的请求类型 * @access public - * @param bool $method true 获取原始请求类型 + * @param bool $origin 是否获取原始请求类型 * @return string */ - public function method($method = false) + public function method($origin = false) { - if (true === $method) { + if ($origin) { // 获取原始请求类型 - return IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); + return $this->isCli() ? 'GET' : $this->server('REQUEST_METHOD'); } elseif (!$this->method) { - if (isset($_POST[Config::get('var_method')])) { - $this->method = strtoupper($_POST[Config::get('var_method')]); - $this->{$this->method}($_POST); - } elseif (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { - $this->method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']); + if (isset($_POST[$this->config['var_method']])) { + $this->method = strtoupper($_POST[$this->config['var_method']]); + $method = strtolower($this->method); + $this->{$method} = $_POST; + } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) { + $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')); } else { - $this->method = IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); + $this->method = $this->isCli() ? 'GET' : $this->server('REQUEST_METHOD'); } } + return $this->method; } @@ -600,17 +877,18 @@ class Request } /** - * 设置获取获取当前请求的参数 + * 获取当前请求的参数 * @access public - * @param string|array $name 变量名 - * @param mixed $default 默认值 - * @param string|array $filter 过滤方法 + * @param mixed $name 变量名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤方法 * @return mixed */ - public function param($name = '', $default = null, $filter = null) + public function param($name = '', $default = null, $filter = '') { - if (empty($this->param)) { + if (!$this->mergeParam) { $method = $this->method(true); + // 自动获取请求变量 switch ($method) { case 'POST': @@ -624,207 +902,235 @@ class Request default: $vars = []; } + // 当前请求参数和URL地址中的参数合并 - $this->param = array_merge($this->get(false), $vars, $this->route(false)); + $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false)); + + $this->mergeParam = true; } + if (true === $name) { // 获取包含文件上传信息的数组 $file = $this->file(); - $data = array_merge($this->param, $file); + $data = is_array($file) ? array_merge($this->param, $file) : $this->param; + return $this->input($data, '', $default, $filter); } + return $this->input($this->param, $name, $default, $filter); } /** - * 设置获取获取路由参数 + * 设置路由变量 * @access public - * @param string|array $name 变量名 - * @param mixed $default 默认值 - * @param string|array $filter 过滤方法 + * @param array $route 路由变量 + * @return $this + */ + public function setRouteVars(array $route) + { + $this->route = array_merge($this->route, $route); + return $this; + } + + /** + * 获取路由参数 + * @access public + * @param string|false $name 变量名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤方法 * @return mixed */ - public function route($name = '', $default = null, $filter = null) + public function route($name = '', $default = null, $filter = '') { - if (is_array($name)) { - $this->param = []; - return $this->route = array_merge($this->route, $name); - } return $this->input($this->route, $name, $default, $filter); } /** - * 设置获取获取GET参数 + * 获取GET参数 * @access public - * @param string|array $name 变量名 - * @param mixed $default 默认值 - * @param string|array $filter 过滤方法 + * @param string|false $name 变量名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤方法 * @return mixed */ - public function get($name = '', $default = null, $filter = null) + public function get($name = '', $default = null, $filter = '') { if (empty($this->get)) { $this->get = $_GET; } - if (is_array($name)) { - $this->param = []; - return $this->get = array_merge($this->get, $name); - } + return $this->input($this->get, $name, $default, $filter); } /** - * 设置获取获取POST参数 + * 获取POST参数 * @access public - * @param string $name 变量名 - * @param mixed $default 默认值 - * @param string|array $filter 过滤方法 + * @param string|false $name 变量名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤方法 * @return mixed */ - public function post($name = '', $default = null, $filter = null) + public function post($name = '', $default = null, $filter = '') { if (empty($this->post)) { - $this->post = $_POST; - } - if (is_array($name)) { - $this->param = []; - return $this->post = array_merge($this->post, $name); + $this->post = !empty($_POST) ? $_POST : $this->getJsonInputData($this->input); } + return $this->input($this->post, $name, $default, $filter); } /** - * 设置获取获取PUT参数 + * 获取PUT参数 * @access public - * @param string|array $name 变量名 - * @param mixed $default 默认值 - * @param string|array $filter 过滤方法 + * @param string|false $name 变量名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤方法 * @return mixed */ - public function put($name = '', $default = null, $filter = null) + public function put($name = '', $default = null, $filter = '') { if (is_null($this->put)) { - $content = $this->input; - if (strpos($content, '":')) { - $this->put = json_decode($content, true); + $data = $this->getJsonInputData($this->input); + + if (!empty($data)) { + $this->put = $data; } else { - parse_str($content, $this->put); + parse_str($this->input, $this->put); } } - if (is_array($name)) { - $this->param = []; - return $this->put = is_null($this->put) ? $name : array_merge($this->put, $name); - } return $this->input($this->put, $name, $default, $filter); } + protected function getJsonInputData($content) + { + if (false !== strpos($this->contentType(), 'application/json')) { + return (array) json_decode($content, true); + } + + return []; + } + /** - * 设置获取获取DELETE参数 + * 获取DELETE参数 * @access public - * @param string|array $name 变量名 - * @param mixed $default 默认值 - * @param string|array $filter 过滤方法 + * @param string|false $name 变量名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤方法 * @return mixed */ - public function delete($name = '', $default = null, $filter = null) + public function delete($name = '', $default = null, $filter = '') { return $this->put($name, $default, $filter); } /** - * 设置获取获取PATCH参数 + * 获取PATCH参数 * @access public - * @param string|array $name 变量名 - * @param mixed $default 默认值 - * @param string|array $filter 过滤方法 + * @param string|false $name 变量名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤方法 * @return mixed */ - public function patch($name = '', $default = null, $filter = null) + public function patch($name = '', $default = null, $filter = '') { return $this->put($name, $default, $filter); } /** * 获取request变量 - * @param string $name 数据名称 - * @param string $default 默认值 - * @param string|array $filter 过滤方法 + * @access public + * @param string|false $name 变量名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤方法 * @return mixed */ - public function request($name = '', $default = null, $filter = null) + public function request($name = '', $default = null, $filter = '') { if (empty($this->request)) { $this->request = $_REQUEST; } - if (is_array($name)) { - $this->param = []; - return $this->request = array_merge($this->request, $name); - } + return $this->input($this->request, $name, $default, $filter); } /** * 获取session数据 * @access public - * @param string|array $name 数据名称 - * @param string $default 默认值 - * @param string|array $filter 过滤方法 + * @param string $name 数据名称 + * @param string $default 默认值 * @return mixed */ - public function session($name = '', $default = null, $filter = null) + public function session($name = '', $default = null) { if (empty($this->session)) { $this->session = Session::get(); } - if (is_array($name)) { - return $this->session = array_merge($this->session, $name); + + if ('' === $name) { + return $this->session; } - return $this->input($this->session, $name, $default, $filter); + + $data = $this->getData($this->session, $name); + + return is_null($data) ? $default : $data; } /** * 获取cookie参数 * @access public - * @param string|array $name 数据名称 - * @param string $default 默认值 - * @param string|array $filter 过滤方法 + * @param string $name 变量名 + * @param string $default 默认值 + * @param string|array $filter 过滤方法 * @return mixed */ - public function cookie($name = '', $default = null, $filter = null) + public function cookie($name = '', $default = null, $filter = '') { if (empty($this->cookie)) { - $this->cookie = $_COOKIE; + $this->cookie = Cookie::get(); } - if (is_array($name)) { - return $this->cookie = array_merge($this->cookie, $name); + + if (!empty($name)) { + $data = Cookie::has($name) ? Cookie::get($name) : $default; + } else { + $data = $this->cookie; + } + + // 解析过滤器 + $filter = $this->getFilter($filter, $default); + + if (is_array($data)) { + array_walk_recursive($data, [$this, 'filterValue'], $filter); + reset($data); + } else { + $this->filterValue($data, $name, $filter); } - return $this->input($this->cookie, $name, $default, $filter); + + return $data; } /** * 获取server参数 * @access public - * @param string|array $name 数据名称 - * @param string $default 默认值 - * @param string|array $filter 过滤方法 + * @param string $name 数据名称 + * @param string $default 默认值 * @return mixed */ - public function server($name = '', $default = null, $filter = null) + public function server($name = '', $default = null) { - if (empty($this->server)) { - $this->server = $_SERVER; - } - if (is_array($name)) { - return $this->server = array_merge($this->server, $name); + if (empty($name)) { + return $this->server; + } else { + $name = strtoupper($name); } - return $this->input($this->server, false === $name ? false : strtoupper($name), $default, $filter); + + return isset($this->server[$name]) ? $this->server[$name] : $default; } /** * 获取上传的文件信息 * @access public - * @param string|array $name 名称 + * @param string $name 名称 * @return null|array|\think\File */ public function file($name = '') @@ -832,43 +1138,16 @@ class Request if (empty($this->file)) { $this->file = isset($_FILES) ? $_FILES : []; } - if (is_array($name)) { - return $this->file = array_merge($this->file, $name); - } + $files = $this->file; if (!empty($files)) { // 处理上传文件 - $array = []; - foreach ($files as $key => $file) { - if (is_array($file['name'])) { - $item = []; - $keys = array_keys($file); - $count = count($file['name']); - for ($i = 0; $i < $count; $i++) { - if (empty($file['tmp_name'][$i])) { - continue; - } - $temp['key'] = $key; - foreach ($keys as $_key) { - $temp[$_key] = $file[$_key][$i]; - } - $item[] = (new File($temp['tmp_name']))->setUploadInfo($temp); - } - $array[$key] = $item; - } else { - if ($file instanceof File) { - $array[$key] = $file; - } else { - if (empty($file['tmp_name'])) { - continue; - } - $array[$key] = (new File($file['tmp_name']))->setUploadInfo($file); - } - } - } + $array = $this->dealUploadFile($files); + if (strpos($name, '.')) { list($name, $sub) = explode('.', $name); } + if ('' === $name) { // 获取全部文件 return $array; @@ -878,108 +1157,145 @@ class Request return $array[$name]; } } - return null; + + return; + } + + protected function dealUploadFile($files) + { + $array = []; + foreach ($files as $key => $file) { + if (is_array($file['name'])) { + $item = []; + $keys = array_keys($file); + $count = count($file['name']); + + for ($i = 0; $i < $count; $i++) { + if (empty($file['tmp_name'][$i]) || !is_file($file['tmp_name'][$i])) { + continue; + } + + $temp['key'] = $key; + + foreach ($keys as $_key) { + $temp[$_key] = $file[$_key][$i]; + } + + $item[] = (new File($temp['tmp_name']))->setUploadInfo($temp); + } + + $array[$key] = $item; + } else { + if ($file instanceof File) { + $array[$key] = $file; + } else { + if (empty($file['tmp_name']) || !is_file($file['tmp_name'])) { + continue; + } + + $array[$key] = (new File($file['tmp_name']))->setUploadInfo($file); + } + } + } + + return $array; } /** * 获取环境变量 - * @param string|array $name 数据名称 - * @param string $default 默认值 - * @param string|array $filter 过滤方法 + * @access public + * @param string $name 数据名称 + * @param string $default 默认值 * @return mixed */ - public function env($name = '', $default = null, $filter = null) + public function env($name = '', $default = null) { - if (empty($this->env)) { - $this->env = $_ENV; - } - if (is_array($name)) { - return $this->env = array_merge($this->env, $name); + if (empty($name)) { + return $this->env; + } else { + $name = strtoupper($name); } - return $this->input($this->env, false === $name ? false : strtoupper($name), $default, $filter); + + return isset($this->env[$name]) ? $this->env[$name] : $default; } /** - * 设置或者获取当前的Header + * 获取当前的Header * @access public - * @param string|array $name header名称 - * @param string $default 默认值 - * @return string + * @param string $name header名称 + * @param string $default 默认值 + * @return string|array */ public function header($name = '', $default = null) { if (empty($this->header)) { $header = []; - $server = $this->server ?: $_SERVER; - foreach ($server as $key => $val) { - if (0 === strpos($key, 'HTTP_')) { - $key = str_replace('_', '-', strtolower(substr($key, 5))); - $header[$key] = $val; + if (function_exists('apache_request_headers') && $result = apache_request_headers()) { + $header = $result; + } else { + $server = $this->server; + foreach ($server as $key => $val) { + if (0 === strpos($key, 'HTTP_')) { + $key = str_replace('_', '-', strtolower(substr($key, 5))); + $header[$key] = $val; + } + } + if (isset($server['CONTENT_TYPE'])) { + $header['content-type'] = $server['CONTENT_TYPE']; + } + if (isset($server['CONTENT_LENGTH'])) { + $header['content-length'] = $server['CONTENT_LENGTH']; } - } - if (isset($server['CONTENT_TYPE'])) { - $header['content-type'] = $server['CONTENT_TYPE']; - } - if (isset($server['CONTENT_LENGTH'])) { - $header['content-length'] = $server['CONTENT_LENGTH']; } $this->header = array_change_key_case($header); } - if (is_array($name)) { - return $this->header = array_merge($this->header, $name); - } + if ('' === $name) { return $this->header; } + $name = str_replace('_', '-', strtolower($name)); + return isset($this->header[$name]) ? $this->header[$name] : $default; } /** * 获取变量 支持过滤和默认值 - * @param array $data 数据源 - * @param string|false $name 字段名 - * @param mixed $default 默认值 - * @param string|array $filter 过滤函数 + * @access public + * @param array $data 数据源 + * @param string|false $name 字段名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤函数 * @return mixed */ - public function input($data = [], $name = '', $default = null, $filter = null) + public function input($data = [], $name = '', $default = null, $filter = '') { if (false === $name) { // 获取原始数据 return $data; } + $name = (string) $name; if ('' != $name) { // 解析name if (strpos($name, '/')) { list($name, $type) = explode('/', $name); - } else { - $type = 's'; } - // 按.拆分成多维数组进行判断 - foreach (explode('.', $name) as $val) { - if (isset($data[$val])) { - $data = $data[$val]; - } else { - // 无输入数据,返回默认值 - return $default; - } + + $data = $this->getData($data, $name); + + if (is_null($data)) { + return $default; } + if (is_object($data)) { return $data; } } // 解析过滤器 - $filter = $filter ?: $this->filter; + $filter = $this->getFilter($filter, $default); - if (is_string($filter)) { - $filter = explode(',', $filter); - } else { - $filter = (array) $filter; - } - $filter[] = $default; if (is_array($data)) { array_walk_recursive($data, [$this, 'filterValue'], $filter); reset($data); @@ -991,39 +1307,81 @@ class Request // 强制类型转换 $this->typeCast($data, $type); } + + return $data; + } + + /** + * 获取数据 + * @access public + * @param array $data 数据源 + * @param string|false $name 字段名 + * @return mixed + */ + protected function getData(array $data, $name) + { + foreach (explode('.', $name) as $val) { + if (isset($data[$val])) { + $data = $data[$val]; + } else { + return; + } + } + return $data; } /** * 设置或获取当前的过滤规则 - * @param mixed $filter 过滤规则 + * @access public + * @param mixed $filter 过滤规则 * @return mixed */ public function filter($filter = null) { if (is_null($filter)) { return $this->filter; + } + + $this->filter = $filter; + } + + protected function getFilter($filter, $default) + { + if (is_null($filter)) { + $filter = []; } else { - $this->filter = $filter; + $filter = $filter ?: $this->filter; + if (is_string($filter) && false === strpos($filter, '/')) { + $filter = explode(',', $filter); + } else { + $filter = (array) $filter; + } } + + $filter[] = $default; + + return $filter; } /** * 递归过滤给定的值 - * @param mixed $value 键值 - * @param mixed $key 键名 - * @param array $filters 过滤方法+默认值 + * @access public + * @param mixed $value 键值 + * @param mixed $key 键名 + * @param array $filters 过滤方法+默认值 * @return mixed */ private function filterValue(&$value, $key, $filters) { $default = array_pop($filters); + foreach ($filters as $filter) { if (is_callable($filter)) { // 调用函数或者方法过滤 $value = call_user_func($filter, $value); } elseif (is_scalar($value)) { - if (strpos($filter, '/')) { + if (false !== strpos($filter, '/')) { // 正则过滤 if (!preg_match($filter, $value)) { // 匹配不成功返回默认值 @@ -1041,27 +1399,15 @@ class Request } } } - return $this->filterExp($value); - } - /** - * 过滤表单中的表达式 - * @param string $value - * @return void - */ - public function filterExp(&$value) - { - // 过滤查询特殊字符 - if (is_string($value) && preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i', $value)) { - $value .= ' '; - } - // TODO 其他安全过滤 + return $value; } /** * 强制类型转换 - * @param string $data - * @param string $type + * @access public + * @param string $data + * @param string $type * @return mixed */ private function typeCast(&$data, $type) @@ -1085,30 +1431,35 @@ class Request break; // 字符串 case 's': - default: if (is_scalar($data)) { $data = (string) $data; } else { throw new \InvalidArgumentException('variable type error:' . gettype($data)); } + break; } } /** * 是否存在某个请求参数 * @access public - * @param string $name 变量名 - * @param string $type 变量类型 - * @param bool $checkEmpty 是否检测空值 + * @param string $name 变量名 + * @param string $type 变量类型 + * @param bool $checkEmpty 是否检测空值 * @return mixed */ public function has($name, $type = 'param', $checkEmpty = false) { + if (!in_array($type, ['param', 'get', 'post', 'request', 'put', 'file', 'session', 'cookie', 'env', 'header', 'route'])) { + return false; + } + if (empty($this->$type)) { $param = $this->$type(); } else { $param = $this->$type; } + // 按.拆分成多维数组进行判断 foreach (explode('.', $name) as $val) { if (isset($param[$val])) { @@ -1117,36 +1468,50 @@ class Request return false; } } + return ($checkEmpty && '' === $param) ? false : true; } /** * 获取指定的参数 * @access public - * @param string|array $name 变量名 - * @param string $type 变量类型 + * @param string|array $name 变量名 + * @param string $type 变量类型 * @return mixed */ public function only($name, $type = 'param') { $param = $this->$type(); + if (is_string($name)) { $name = explode(',', $name); } + $item = []; - foreach ($name as $key) { + foreach ($name as $key => $val) { + + if (is_int($key)) { + $default = null; + $key = $val; + } else { + $default = $val; + } + if (isset($param[$key])) { $item[$key] = $param[$key]; + } elseif (isset($default)) { + $item[$key] = $default; } } + return $item; } /** * 排除指定参数获取 * @access public - * @param string|array $name 变量名 - * @param string $type 变量类型 + * @param string|array $name 变量名 + * @param string $type 变量类型 * @return mixed */ public function except($name, $type = 'param') @@ -1155,11 +1520,13 @@ class Request if (is_string($name)) { $name = explode(',', $name); } + foreach ($name as $key) { if (isset($param[$key])) { unset($param[$key]); } } + return $param; } @@ -1170,86 +1537,106 @@ class Request */ public function isSsl() { - $server = array_merge($_SERVER, $this->server); - if (isset($server['HTTPS']) && ('1' == $server['HTTPS'] || 'on' == strtolower($server['HTTPS']))) { + if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) { + return true; + } elseif ('https' == $this->server('REQUEST_SCHEME')) { return true; - } elseif (isset($server['REQUEST_SCHEME']) && 'https' == $server['REQUEST_SCHEME']) { + } elseif ('443' == $this->server('SERVER_PORT')) { return true; - } elseif (isset($server['SERVER_PORT']) && ('443' == $server['SERVER_PORT'])) { + } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) { return true; - } elseif (isset($server['HTTP_X_FORWARDED_PROTO']) && 'https' == $server['HTTP_X_FORWARDED_PROTO']) { + } elseif ($this->config['https_agent_name'] && $this->server($this->config['https_agent_name'])) { return true; } + return false; } /** * 当前是否Ajax请求 * @access public - * @param bool $ajax true 获取原始ajax请求 + * @param bool $ajax true 获取原始ajax请求 * @return bool */ public function isAjax($ajax = false) { - $value = $this->server('HTTP_X_REQUESTED_WITH', '', 'strtolower'); - $result = ('xmlhttprequest' == $value) ? true : false; + $value = $this->server('HTTP_X_REQUESTED_WITH'); + $result = 'xmlhttprequest' == strtolower($value) ? true : false; + if (true === $ajax) { return $result; - } else { - return $this->param(Config::get('var_ajax')) ? true : $result; } + + return $this->param($this->config['var_ajax']) ? true : $result; } /** * 当前是否Pjax请求 * @access public - * @param bool $pjax true 获取原始pjax请求 + * @param bool $pjax true 获取原始pjax请求 * @return bool */ public function isPjax($pjax = false) { $result = !is_null($this->server('HTTP_X_PJAX')) ? true : false; + if (true === $pjax) { return $result; - } else { - return $this->param(Config::get('var_pjax')) ? true : $result; } + + return $this->param($this->config['var_pjax']) ? true : $result; } /** * 获取客户端IP地址 - * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字 - * @param boolean $adv 是否进行高级模式获取(有可能被伪装) + * @access public + * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字 + * @param boolean $adv 是否进行高级模式获取(有可能被伪装) * @return mixed */ - public function ip($type = 0, $adv = false) + public function ip($type = 0, $adv = true) { $type = $type ? 1 : 0; static $ip = null; + if (null !== $ip) { return $ip[$type]; } - if ($adv) { - if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { - $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); + $httpAgentIp = $this->config['http_agent_ip']; + + if ($httpAgentIp && $this->server($httpAgentIp)) { + $ip = $this->server($httpAgentIp); + } elseif ($adv) { + if ($this->server('HTTP_X_FORWARDED_FOR')) { + $arr = explode(',', $this->server('HTTP_X_FORWARDED_FOR')); $pos = array_search('unknown', $arr); if (false !== $pos) { unset($arr[$pos]); } - - $ip = trim($arr[0]); - } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { - $ip = $_SERVER['HTTP_CLIENT_IP']; - } elseif (isset($_SERVER['REMOTE_ADDR'])) { - $ip = $_SERVER['REMOTE_ADDR']; + $ip = trim(current($arr)); + } elseif ($this->server('HTTP_CLIENT_IP')) { + $ip = $this->server('HTTP_CLIENT_IP'); + } elseif ($this->server('REMOTE_ADDR')) { + $ip = $this->server('REMOTE_ADDR'); } - } elseif (isset($_SERVER['REMOTE_ADDR'])) { - $ip = $_SERVER['REMOTE_ADDR']; + } elseif ($this->server('REMOTE_ADDR')) { + $ip = $this->server('REMOTE_ADDR'); } + + // IP地址类型 + $ip_mode = (strpos($ip, ':') === false) ? 'ipv4' : 'ipv6'; + // IP地址合法验证 - $long = sprintf("%u", ip2long($ip)); - $ip = $long ? array($ip, $long) : array('0.0.0.0', 0); + if (filter_var($ip, FILTER_VALIDATE_IP) !== $ip) { + $ip = ('ipv4' === $ip_mode) ? '0.0.0.0' : '::'; + } + + // 如果是ipv4地址,则直接使用ip2long返回int类型ip;如果是ipv6地址,暂时不支持,直接返回0 + $long_ip = ('ipv4' === $ip_mode) ? sprintf("%u", ip2long($ip)) : 0; + + $ip = [$ip, $long_ip]; + return $ip[$type]; } @@ -1260,17 +1647,17 @@ class Request */ public function isMobile() { - if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) { + if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) { return true; - } elseif (isset($_SERVER['HTTP_ACCEPT']) && strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML")) { + } elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) { return true; - } elseif (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) { + } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) { return true; - } elseif (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])) { + } elseif ($this->server('HTTP_USER_AGENT') && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $this->server('HTTP_USER_AGENT'))) { return true; - } else { - return false; } + + return false; } /** @@ -1296,11 +1683,14 @@ class Request /** * 当前请求的host * @access public + * @param bool $strict true 仅仅获取HOST * @return string */ - public function host() + public function host($strict = false) { - return $this->server('HTTP_HOST'); + $host = $this->server('HTTP_X_REAL_HOST') ?: $this->server('HTTP_HOST'); + + return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host; } /** @@ -1316,7 +1706,7 @@ class Request /** * 当前请求 SERVER_PROTOCOL * @access public - * @return integer + * @return string */ public function protocol() { @@ -1333,97 +1723,161 @@ class Request return $this->server('REMOTE_PORT'); } + /** + * 当前请求 HTTP_CONTENT_TYPE + * @access public + * @return string + */ + public function contentType() + { + $contentType = $this->server('CONTENT_TYPE'); + + if ($contentType) { + if (strpos($contentType, ';')) { + list($type) = explode(';', $contentType); + } else { + $type = $contentType; + } + return trim($type); + } + + return ''; + } + /** * 获取当前请求的路由信息 * @access public - * @param array $route 路由名称 + * @param array $route 路由名称 * @return array */ - public function routeInfo($route = []) + public function routeInfo(array $route = []) { if (!empty($route)) { $this->routeInfo = $route; - } else { - return $this->routeInfo; } + + return $this->routeInfo; } /** * 设置或者获取当前请求的调度信息 * @access public - * @param array $dispatch 调度信息 - * @return array + * @param \think\route\Dispatch $dispatch 调度信息 + * @return \think\route\Dispatch */ public function dispatch($dispatch = null) { if (!is_null($dispatch)) { $this->dispatch = $dispatch; } + return $this->dispatch; } /** - * 设置或者获取当前的模块名 + * 获取当前请求的安全Key * @access public - * @param string $module 模块名 - * @return string|$this + * @return string */ - public function module($module = null) + public function secureKey() { - if (!is_null($module)) { - $this->module = $module; - return $this; - } else { - return $this->module ?: ''; + if (is_null($this->secureKey)) { + $this->secureKey = uniqid('', true); } + + return $this->secureKey; } /** - * 设置或者获取当前的控制器名 + * 设置当前的模块名 * @access public - * @param string $controller 控制器名 - * @return string|$this + * @param string $module 模块名 + * @return $this */ - public function controller($controller = null) + public function setModule($module) { - if (!is_null($controller)) { - $this->controller = $controller; - return $this; - } else { - return $this->controller ?: ''; - } + $this->module = $module; + return $this; } /** - * 设置或者获取当前的操作名 + * 设置当前的控制器名 + * @access public + * @param string $controller 控制器名 + * @return $this + */ + public function setController($controller) + { + $this->controller = $controller; + return $this; + } + + /** + * 设置当前的操作名 + * @access public + * @param string $action 操作名 + * @return $this + */ + public function setAction($action) + { + $this->action = $action; + return $this; + } + + /** + * 获取当前的模块名 * @access public - * @param string $action 操作名 * @return string */ - public function action($action = null) + public function module() { - if (!is_null($action)) { - $this->action = $action; - return $this; - } else { - return $this->action ?: ''; - } + return $this->module ?: ''; } /** - * 设置或者获取当前的语言 + * 获取当前的控制器名 * @access public - * @param string $lang 语言名 + * @param bool $convert 转换为小写 * @return string */ - public function langset($lang = null) + public function controller($convert = false) { - if (!is_null($lang)) { - $this->langset = $lang; - return $this; - } else { - return $this->langset ?: ''; - } + $name = $this->controller ?: ''; + return $convert ? strtolower($name) : $name; + } + + /** + * 获取当前的操作名 + * @access public + * @param bool $convert 转换为驼峰 + * @return string + */ + public function action($convert = false) + { + $name = $this->action ?: ''; + return $convert ? $name : strtolower($name); + } + + /** + * 设置当前的语言 + * @access public + * @param string $lang 语言名 + * @return $this + */ + public function setLangset($lang) + { + $this->langset = $lang; + return $this; + } + + /** + * 获取当前的语言 + * @access public + * @return string + */ + public function langset() + { + return $this->langset ?: ''; } /** @@ -1436,6 +1890,7 @@ class Request if (is_null($this->content)) { $this->content = $this->input; } + return $this->content; } @@ -1452,66 +1907,94 @@ class Request /** * 生成请求令牌 * @access public - * @param string $name 令牌名称 - * @param mixed $type 令牌生成方法 + * @param string $name 令牌名称 + * @param mixed $type 令牌生成方法 * @return string */ - public function token($name = '__token__', $type = 'md5') + public function token($name = '__token__', $type = null) { $type = is_callable($type) ? $type : 'md5'; - $token = call_user_func($type, $_SERVER['REQUEST_TIME_FLOAT']); + $token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT')); + if ($this->isAjax()) { header($name . ': ' . $token); } - Session::set($name, $token); + + facade\Session::set($name, $token); + return $token; } /** - * 读取或者设置缓存 + * 设置当前地址的请求缓存 * @access public - * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id - * @param mixed $expire 缓存有效期 + * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id + * @param mixed $expire 缓存有效期 + * @param array $except 缓存排除 + * @param string $tag 缓存标签 * @return mixed */ - public function cache($key, $expire = null) + public function cache($key, $expire = null, $except = [], $tag = null) { - if ($this->isGet()) { - if (false !== strpos($key, ':')) { - $param = $this->param(); - foreach ($param as $item => $val) { - if (is_string($val) && false !== strpos($key, ':' . $item)) { - $key = str_replace(':' . $item, $val, $key); - } - } - } elseif ('__URL__' == $key) { - // 当前URL地址作为缓存标识 - $key = md5($this->url()); - } elseif (strpos($key, ']')) { - if ('[' . $this->ext() . ']' == $key) { - // 缓存某个后缀的请求 - $key = md5($this->url()); - } else { - return; - } + if (!is_array($except)) { + $tag = $except; + $except = []; + } + + if (false === $key || !$this->isGet() || $this->isCheckCache || false === $expire) { + // 关闭当前缓存 + return; + } + + // 标记请求缓存检查 + $this->isCheckCache = true; + + foreach ($except as $rule) { + if (0 === stripos($this->url(), $rule)) { + return; } + } + + if ($key instanceof \Closure) { + $key = call_user_func_array($key, [$this]); + } elseif (true === $key) { + // 自动缓存功能 + $key = '__URL__'; + } elseif (strpos($key, '|')) { + list($key, $fun) = explode('|', $key); + } - if (strtotime($this->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $_SERVER['REQUEST_TIME']) { - // 读取缓存 - $response = Response::create()->code(304); - throw new \think\exception\HttpResponseException($response); - } elseif (Cache::has($key)) { - list($content, $header) = Cache::get($key); - $response = Response::create($content)->header($header); - throw new \think\exception\HttpResponseException($response); + // 特殊规则替换 + if (false !== strpos($key, '__')) { + $key = str_replace(['__MODULE__', '__CONTROLLER__', '__ACTION__', '__URL__'], [$this->module, $this->controller, $this->action, md5($this->url(true))], $key); + } + + if (false !== strpos($key, ':')) { + $param = $this->param(); + foreach ($param as $item => $val) { + if (is_string($val) && false !== strpos($key, ':' . $item)) { + $key = str_replace(':' . $item, $val, $key); + } + } + } elseif (strpos($key, ']')) { + if ('[' . $this->ext() . ']' == $key) { + // 缓存某个后缀的请求 + $key = md5($this->url()); } else { - $this->cache = [$key, $expire]; + return; } } + + if (isset($fun)) { + $key = $fun($key); + } + + $this->cache = [$key, $expire, $tag]; + return $this->cache; } /** - * 读取缓存设置 + * 读取请求缓存设置 * @access public * @return array */ @@ -1521,33 +2004,35 @@ class Request } /** - * 设置当前请求绑定的对象实例 + * 设置请求数据 * @access public - * @param string $name 绑定的对象标识 - * @param mixed $obj 绑定的对象实例 - * @return mixed + * @param string $name 参数名 + * @param mixed $value 值 */ - public function bind($name, $obj = null) - { - if (is_array($name)) { - $this->bind = array_merge($this->bind, $name); - } else { - $this->bind[$name] = $obj; - } - } - public function __set($name, $value) { - $this->bind[$name] = $value; + return $this->param[$name] = $value; } + /** + * 获取请求数据的值 + * @access public + * @param string $name 参数名 + * @return mixed + */ public function __get($name) { - return isset($this->bind[$name]) ? $this->bind[$name] : null; + return $this->param($name); } + /** + * 检测请求数据的值 + * @access public + * @param string $name 名称 + * @return boolean + */ public function __isset($name) { - return isset($this->bind[$name]); + return isset($this->param[$name]); } } diff --git a/library/think/Response.php b/library/think/Response.php index 8b62e4199adf3a493fd110c96cd70deb9ce3bc6d..09cb6a9245dca933616104a2d266f99a8507177c 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,96 +11,136 @@ namespace think; -use think\Cache; -use think\Config; -use think\Debug; -use think\Env; -use think\Request; -use think\response\Json as JsonResponse; -use think\response\Jsonp as JsonpResponse; use think\response\Redirect as RedirectResponse; -use think\response\View as ViewResponse; -use think\response\Xml as XmlResponse; class Response { - - // 原始数据 + /** + * 原始数据 + * @var mixed + */ protected $data; - // 当前的contentType + /** + * 应用对象实例 + * @var App + */ + protected $app; + + /** + * 当前contentType + * @var string + */ protected $contentType = 'text/html'; - // 字符集 + /** + * 字符集 + * @var string + */ protected $charset = 'utf-8'; - //状态 + /** + * 状态码 + * @var integer + */ protected $code = 200; - // 输出参数 + /** + * 是否允许请求缓存 + * @var bool + */ + protected $allowCache = true; + + /** + * 输出参数 + * @var array + */ protected $options = []; - // header参数 + + /** + * header参数 + * @var array + */ protected $header = []; + /** + * 输出内容 + * @var string + */ protected $content = null; /** * 架构函数 - * @access public - * @param mixed $data 输出数据 - * @param int $code - * @param array $header - * @param array $options 输出参数 + * @access public + * @param mixed $data 输出数据 + * @param int $code + * @param array $header + * @param array $options 输出参数 */ public function __construct($data = '', $code = 200, array $header = [], $options = []) { $this->data($data); - $this->header = $header; - $this->code = $code; + if (!empty($options)) { $this->options = array_merge($this->options, $options); } + $this->contentType($this->contentType, $this->charset); + + $this->code = $code; + $this->app = Container::get('app'); + $this->header = array_merge($this->header, $header); } /** * 创建Response对象 * @access public - * @param mixed $data 输出数据 - * @param string $type 输出类型 - * @param int $code - * @param array $header - * @param array $options 输出参数 - * @return Response|JsonResponse|ViewResponse|XmlResponse|RedirectResponse|JsonpResponse + * @param mixed $data 输出数据 + * @param string $type 输出类型 + * @param int $code + * @param array $header + * @param array $options 输出参数 + * @return Response */ public static function create($data = '', $type = '', $code = 200, array $header = [], $options = []) { - $type = empty($type) ? 'null' : strtolower($type); + $class = false !== strpos($type, '\\') ? $type : '\\think\\response\\' . ucfirst(strtolower($type)); - $class = false !== strpos($type, '\\') ? $type : '\\think\\response\\' . ucfirst($type); if (class_exists($class)) { - $response = new $class($data, $code, $header, $options); - } else { - $response = new static($data, $code, $header, $options); + return new $class($data, $code, $header, $options); } - return $response; + return new static($data, $code, $header, $options); } /** * 发送数据到客户端 * @access public - * @return mixed + * @return void * @throws \InvalidArgumentException */ public function send() { + // 监听response_send + $this->app['hook']->listen('response_send', $this); + // 处理输出数据 $data = $this->getContent(); // Trace调试注入 - if (Env::get('app_trace', Config::get('app_trace'))) { - Debug::inject($this, $data); + if ('cli' != PHP_SAPI && $this->app['env']->get('app_trace', $this->app->config('app.app_trace'))) { + $this->app['debug']->inject($this, $data); + } + + if (200 == $this->code && $this->allowCache) { + $cache = $this->app['request']->getCache(); + if ($cache) { + $this->header['Cache-Control'] = 'max-age=' . $cache[1] . ',must-revalidate'; + $this->header['Last-Modified'] = gmdate('D, d M Y H:i:s') . ' GMT'; + $this->header['Expires'] = gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME'] + $cache[1]) . ' GMT'; + + $this->app['cache']->tag($cache[2])->set($cache[0], [$data, $this->header], $cache[1]); + } } if (!headers_sent() && !empty($this->header)) { @@ -108,20 +148,11 @@ class Response http_response_code($this->code); // 发送头部信息 foreach ($this->header as $name => $val) { - header($name . ':' . $val); + header($name . (!is_null($val) ? ':' . $val : '')); } } - if (200 == $this->code) { - $cache = Request::instance()->getCache(); - if ($cache) { - header('Cache-Control: max-age=' . $cache[1] . ',must-revalidate'); - header('Last-Modified:' . gmdate('D, d M Y H:i:s') . ' GMT'); - header('Expires:' . gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME'] + $cache[1]) . ' GMT'); - $header['Content-Type'] = $this->header['Content-Type']; - Cache::set($cache[0], [$data, $header], $cache[1]); - } - } - echo $data; + + $this->sendData($data); if (function_exists('fastcgi_finish_request')) { // 提高页面响应 @@ -129,13 +160,18 @@ class Response } // 监听response_end - Hook::listen('response_end', $this); + $this->app['hook']->listen('response_end', $this); + + // 清空当次请求有效的数据 + if (!($this instanceof RedirectResponse)) { + $this->app['session']->flush(); + } } /** * 处理数据 * @access protected - * @param mixed $data 要处理的数据 + * @param mixed $data 要处理的数据 * @return mixed */ protected function output($data) @@ -143,35 +179,61 @@ class Response return $data; } + /** + * 输出数据 + * @access protected + * @param string $data 要处理的数据 + * @return void + */ + protected function sendData($data) + { + echo $data; + } + /** * 输出的参数 * @access public - * @param mixed $options 输出参数 + * @param mixed $options 输出参数 * @return $this */ public function options($options = []) { $this->options = array_merge($this->options, $options); + return $this; } /** * 输出数据设置 * @access public - * @param mixed $data 输出数据 + * @param mixed $data 输出数据 * @return $this */ public function data($data) { $this->data = $data; + + return $this; + } + + /** + * 是否允许请求缓存 + * @access public + * @param bool $cache 允许请求缓存 + * @return $this + */ + public function allowCache($cache) + { + $this->allowCache = $cache; + return $this; } /** * 设置响应头 * @access public - * @param string|array $name 参数名 - * @param string $value 参数值 + * @param string|array $name 参数名 + * @param string $value 参数值 * @return $this */ public function header($name, $value = null) @@ -181,12 +243,14 @@ class Response } else { $this->header[$name] = $value; } + return $this; } /** * 设置页面输出内容 - * @param $content + * @access public + * @param mixed $content * @return $this */ public function content($content) @@ -206,83 +270,101 @@ class Response /** * 发送HTTP状态 - * @param integer $code 状态码 + * @access public + * @param integer $code 状态码 * @return $this */ public function code($code) { $this->code = $code; + return $this; } /** * LastModified - * @param string $time + * @access public + * @param string $time * @return $this */ public function lastModified($time) { $this->header['Last-Modified'] = $time; + return $this; } /** * Expires - * @param string $time + * @access public + * @param string $time * @return $this */ public function expires($time) { $this->header['Expires'] = $time; + return $this; } /** * ETag - * @param string $eTag + * @access public + * @param string $eTag * @return $this */ public function eTag($eTag) { $this->header['ETag'] = $eTag; + return $this; } /** * 页面缓存控制 - * @param string $cache 状态码 + * @access public + * @param string $cache 状态码 * @return $this */ public function cacheControl($cache) { $this->header['Cache-control'] = $cache; + return $this; } /** * 页面输出类型 - * @param string $contentType 输出类型 - * @param string $charset 输出编码 + * @access public + * @param string $contentType 输出类型 + * @param string $charset 输出编码 * @return $this */ public function contentType($contentType, $charset = 'utf-8') { $this->header['Content-Type'] = $contentType . '; charset=' . $charset; + return $this; } /** * 获取头部信息 - * @param string $name 头部名称 + * @access public + * @param string $name 头部名称 * @return mixed */ public function getHeader($name = '') { - return !empty($name) ? $this->header[$name] : $this->header; + if (!empty($name)) { + return isset($this->header[$name]) ? $this->header[$name] : null; + } + + return $this->header; } /** * 获取原始数据 + * @access public * @return mixed */ public function getData() @@ -292,6 +374,7 @@ class Response /** * 获取输出数据 + * @access public * @return mixed */ public function getContent() @@ -309,11 +392,13 @@ class Response $this->content = (string) $content; } + return $this->content; } /** * 获取状态码 + * @access public * @return integer */ public function getCode() diff --git a/library/think/Route.php b/library/think/Route.php index c18a2d6762062285a605edbcef06535dc0ee065b..29e0d33e6f98b0c85a21e078a972e49beddb6763 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,1499 +11,893 @@ namespace think; -use think\App; -use think\Config; -use think\exception\HttpException; -use think\Hook; -use think\Loader; -use think\Log; -use think\Request; -use think\Response; +use think\exception\RouteNotFoundException; +use think\route\AliasRule; +use think\route\dispatch\Url as UrlDispatch; +use think\route\Domain; +use think\route\Resource; +use think\route\RuleGroup; +use think\route\RuleItem; class Route { - // 路由规则 - private static $rules = [ - 'GET' => [], - 'POST' => [], - 'PUT' => [], - 'DELETE' => [], - 'PATCH' => [], - 'HEAD' => [], - 'OPTIONS' => [], - '*' => [], - 'alias' => [], - 'domain' => [], - 'pattern' => [], - 'name' => [], + /** + * REST定义 + * @var array + */ + protected $rest = [ + 'index' => ['get', '', 'index'], + 'create' => ['get', '/create', 'create'], + 'edit' => ['get', '//edit', 'edit'], + 'read' => ['get', '/', 'read'], + 'save' => ['post', '', 'save'], + 'update' => ['put', '/', 'update'], + 'delete' => ['delete', '/', 'delete'], ]; - // REST路由操作方法定义 - private static $rest = [ - 'index' => ['GET', '', 'index'], - 'create' => ['GET', '/create', 'create'], - 'edit' => ['GET', '/:id/edit', 'edit'], - 'read' => ['GET', '/:id', 'read'], - 'save' => ['POST', '', 'save'], - 'update' => ['PUT', '/:id', 'update'], - 'delete' => ['DELETE', '/:id', 'delete'], + /** + * 请求方法前缀定义 + * @var array + */ + protected $methodPrefix = [ + 'get' => 'get', + 'post' => 'post', + 'put' => 'put', + 'delete' => 'delete', + 'patch' => 'patch', ]; - // 不同请求类型的方法前缀 - private static $methodPrefix = [ - 'GET' => 'get', - 'POST' => 'post', - 'PUT' => 'put', - 'DELETE' => 'delete', - ]; + /** + * 应用对象 + * @var App + */ + protected $app; - // 子域名 - private static $subDomain = ''; - // 域名绑定 - private static $bind = []; - // 当前分组信息 - private static $group = []; - // 当前子域名绑定 - private static $domainBind; - private static $domainRule; - // 当前域名 - private static $domain; + /** + * 请求对象 + * @var Request + */ + protected $request; /** - * 注册变量规则 - * @access public - * @param string|array $name 变量名 - * @param string $rule 变量规则 - * @return void + * 当前HOST + * @var string + */ + protected $host; + + /** + * 当前域名 + * @var string + */ + protected $domain; + + /** + * 当前分组对象 + * @var RuleGroup + */ + protected $group; + + /** + * 配置参数 + * @var array + */ + protected $config = []; + + /** + * 路由绑定 + * @var array + */ + protected $bind = []; + + /** + * 域名对象 + * @var array + */ + protected $domains = []; + + /** + * 跨域路由规则 + * @var RuleGroup + */ + protected $cross; + + /** + * 路由别名 + * @var array + */ + protected $alias = []; + + /** + * 路由是否延迟解析 + * @var bool + */ + protected $lazy = true; + + /** + * (分组)路由规则是否合并解析 + * @var bool */ - public static function pattern($name = null, $rule = '') + protected $mergeRuleRegex = true; + + /** + * 路由解析自动搜索多级控制器 + * @var bool + */ + protected $autoSearchController = true; + + public function __construct(App $app, array $config = []) { - if (is_array($name)) { - self::$rules['pattern'] = array_merge(self::$rules['pattern'], $name); - } else { - self::$rules['pattern'][$name] = $rule; + $this->app = $app; + $this->request = $app['request']; + $this->config = $config; + $this->host = $this->request->host(true); + + $this->setDefaultDomain(); + } + + public function config($name = null) + { + if (is_null($name)) { + return $this->config; } + + return isset($this->config[$name]) ? $this->config[$name] : null; } /** - * 注册子域名部署规则 + * 配置 * @access public - * @param string|array $domain 子域名 - * @param mixed $rule 路由规则 - * @param array $option 路由参数 - * @param array $pattern 变量规则 + * @param array $config * @return void */ - public static function domain($domain, $rule = '', $option = [], $pattern = []) + public function setConfig(array $config = []) { - if (is_array($domain)) { - foreach ($domain as $key => $item) { - self::domain($key, $item, $option, $pattern); - } - } elseif ($rule instanceof \Closure) { - // 执行闭包 - self::setDomain($domain); - call_user_func_array($rule, []); - self::setDomain(null); - } elseif (is_array($rule)) { - self::setDomain($domain); - self::group('', function () use ($rule) { - // 动态注册域名的路由规则 - self::registerRules($rule); - }, $option, $pattern); - self::setDomain(null); - } else { - self::$rules['domain'][$domain]['[bind]'] = [$rule, $option, $pattern]; - } + $this->config = array_merge($this->config, array_change_key_case($config)); } - private static function setDomain($domain) + public static function __make(App $app, Config $config) { - self::$domain = $domain; + $config = $config->pull('app'); + $route = new static($app, $config); + + $route->lazy($config['url_lazy_route']) + ->autoSearchController($config['controller_auto_search']) + ->mergeRuleRegex($config['route_rule_merge']); + + return $route; } /** - * 设置路由绑定 + * 设置路由域名及分组(包括资源路由)是否延迟解析 * @access public - * @param mixed $bind 绑定信息 - * @param string $type 绑定类型 默认为module 支持 namespace class - * @return mixed + * @param bool $lazy 路由是否延迟解析 + * @return $this */ - public static function bind($bind, $type = 'module') + public function lazy($lazy = true) { - self::$bind = ['type' => $type, $type => $bind]; + $this->lazy = $lazy; + return $this; } /** - * 设置或者获取路由标识 + * 设置路由域名及分组(包括资源路由)是否合并解析 * @access public - * @param string|array $name 路由命名标识 数组表示批量设置 - * @param array $value 路由地址及变量信息 - * @return array + * @param bool $merge 路由是否合并解析 + * @return $this */ - public static function name($name = '', $value = null) + public function mergeRuleRegex($merge = true) { - if (is_array($name)) { - return self::$rules['name'] = $name; - } elseif ('' === $name) { - return self::$rules['name']; - } elseif (!is_null($value)) { - self::$rules['name'][$name][] = $value; - } else { - return isset(self::$rules['name'][$name]) ? self::$rules['name'][$name] : null; - } + $this->mergeRuleRegex = $merge; + $this->group->mergeRuleRegex($merge); + + return $this; } /** - * 读取路由绑定 + * 设置路由自动解析是否搜索多级控制器 * @access public - * @param string $type 绑定类型 - * @return mixed + * @param bool $auto 是否自动搜索多级控制器 + * @return $this */ - public static function getBind($type) + public function autoSearchController($auto = true) { - return isset(self::$bind[$type]) ? self::$bind[$type] : null; + $this->autoSearchController = $auto; + return $this; } /** - * 导入配置文件的路由规则 - * @access public - * @param array $rule 路由规则 - * @param string $type 请求类型 + * 初始化默认域名 + * @access protected * @return void */ - public static function import(array $rule, $type = '*') + protected function setDefaultDomain() { - // 检查域名部署 - if (isset($rule['__domain__'])) { - self::domain($rule['__domain__']); - unset($rule['__domain__']); - } - - // 检查变量规则 - if (isset($rule['__pattern__'])) { - self::pattern($rule['__pattern__']); - unset($rule['__pattern__']); - } - - // 检查路由别名 - if (isset($rule['__alias__'])) { - self::alias($rule['__alias__']); - unset($rule['__alias__']); - } + // 默认域名 + $this->domain = $this->host; - // 检查资源路由 - if (isset($rule['__rest__'])) { - self::resource($rule['__rest__']); - unset($rule['__rest__']); - } + // 注册默认域名 + $domain = new Domain($this, $this->host); - self::registerRules($rule, strtoupper($type)); - } + $this->domains[$this->host] = $domain; - // 批量注册路由 - protected static function registerRules($rules, $type = '*') - { - foreach ($rules as $key => $val) { - if (is_numeric($key)) { - $key = array_shift($val); - } - if (empty($val)) { - continue; - } - if (is_string($key) && 0 === strpos($key, '[')) { - $key = substr($key, 1, -1); - self::group($key, $val); - } elseif (is_array($val)) { - self::setRule($key, $val[0], $type, $val[1], isset($val[2]) ? $val[2] : []); - } else { - self::setRule($key, $val, $type); - } - } + // 默认分组 + $this->group = $domain; } /** - * 注册路由规则 + * 设置当前域名 * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param string $type 请求类型 - * @param array $option 路由参数 - * @param array $pattern 变量规则 + * @param RuleGroup $group 域名 * @return void */ - public static function rule($rule, $route = '', $type = '*', $option = [], $pattern = []) + public function setGroup(RuleGroup $group) { - $group = self::getGroup('name'); - if (!is_null($group)) { - // 路由分组 - $option = array_merge(self::getGroup('option'), $option); - $pattern = array_merge(self::getGroup('pattern'), $pattern); - } - - $type = strtoupper($type); - - if (strpos($type, '|')) { - $option['method'] = $type; - $type = '*'; - } - if (is_array($rule) && empty($route)) { - foreach ($rule as $key => $val) { - if (is_numeric($key)) { - $key = array_shift($val); - } - if (is_array($val)) { - $route = $val[0]; - $option1 = array_merge($option, $val[1]); - $pattern1 = array_merge($pattern, isset($val[2]) ? $val[2] : []); - } else { - $route = $val; - } - self::setRule($key, $route, $type, isset($option1) ? $option1 : $option, isset($pattern1) ? $pattern1 : $pattern, $group); - } - } else { - self::setRule($rule, $route, $type, $option, $pattern, $group); - } - + $this->group = $group; } /** - * 设置路由规则 + * 获取当前分组 * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param string $type 请求类型 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @param string $group 所属分组 - * @return void + * @return RuleGroup */ - protected static function setRule($rule, $route, $type = '*', $option = [], $pattern = [], $group = '') + public function getGroup() { - if (is_array($rule)) { - $name = $rule[0]; - $rule = $rule[1]; - } elseif (is_string($route)) { - $name = $route; - } - if (!isset($option['complete_match'])) { - if (Config::get('route_complete_match')) { - $option['complete_match'] = true; - } elseif ('$' == substr($rule, -1, 1)) { - // 是否完整匹配 - $option['complete_match'] = true; - $rule = substr($rule, 0, -1); - } - } elseif (empty($option['complete_match']) && '$' == substr($rule, -1, 1)) { - // 是否完整匹配 - $option['complete_match'] = true; - $rule = substr($rule, 0, -1); - } - - if ('/' != $rule) { - $rule = trim($rule, '/'); - } - $vars = self::parseVar($rule); - if (isset($name)) { - self::name($name, [$rule, $vars, self::$domain]); - } - if ($group) { - if ('*' != $type) { - $option['method'] = $type; - } - if (self::$domain) { - self::$rules['domain'][self::$domain]['*'][$group]['rule'][] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern]; - } else { - self::$rules['*'][$group]['rule'][] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern]; - } - } else { - if ('*' != $type && isset(self::$rules['*'][$rule])) { - unset(self::$rules['*'][$rule]); - } - if (self::$domain) { - self::$rules['domain'][self::$domain][$type][$rule] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern]; - } else { - self::$rules[$type][$rule] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern]; - } - if ('*' == $type) { - // 注册路由快捷方式 - foreach (['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'] as $method) { - if (self::$domain) { - self::$rules['domain'][self::$domain][$method][$rule] = true; - } else { - self::$rules[$method][$rule] = true; - } - } - } - } + return $this->group; } /** - * 获取当前的分组信息 + * 注册变量规则 * @access public - * @param string $type 分组信息名称 name option pattern - * @return mixed + * @param string|array $name 变量名 + * @param string $rule 变量规则 + * @return $this */ - public static function getGroup($type) + public function pattern($name, $rule = '') { - if (isset(self::$group[$type])) { - return self::$group[$type]; - } else { - return 'name' == $type ? null : []; - } + $this->group->pattern($name, $rule); + + return $this; } /** - * 设置当前的路由分组 + * 注册路由参数 * @access public - * @param string $name 分组名称 - * @param array $option 分组路由参数 - * @param array $pattern 分组变量规则 - * @return void + * @param string|array $name 参数名 + * @param mixed $value 值 + * @return $this */ - public static function setGroup($name, $option = [], $pattern = []) + public function option($name, $value = '') { - self::$group['name'] = $name; - self::$group['option'] = $option ?: []; - self::$group['pattern'] = $pattern ?: []; + $this->group->option($name, $value); + + return $this; } /** - * 注册路由分组 + * 注册域名路由 * @access public - * @param string|array $name 分组名称或者参数 - * @param array|\Closure $routes 路由地址 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @return void + * @param string|array $name 子域名 + * @param mixed $rule 路由规则 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return Domain */ - public static function group($name, $routes, $option = [], $pattern = []) + public function domain($name, $rule = '', $option = [], $pattern = []) { - if (is_array($name)) { - $option = $name; - $name = isset($option['name']) ? $option['name'] : ''; + // 支持多个域名使用相同路由规则 + $domainName = is_array($name) ? array_shift($name) : $name; + + if ('*' != $domainName && !strpos($domainName, '.')) { + $domainName .= '.' . $this->request->rootDomain(); } - // 分组 - $currentGroup = self::getGroup('name'); - if ($currentGroup) { - $name = $currentGroup . ($name ? '/' . ltrim($name, '/') : ''); + + if (!isset($this->domains[$domainName])) { + $domain = (new Domain($this, $domainName, $rule, $option, $pattern)) + ->lazy($this->lazy) + ->mergeRuleRegex($this->mergeRuleRegex); + + $this->domains[$domainName] = $domain; + } else { + $domain = $this->domains[$domainName]; + $domain->parseGroupRule($rule); } - if (!empty($name)) { - if ($routes instanceof \Closure) { - $currentOption = self::getGroup('option'); - $currentPattern = self::getGroup('pattern'); - self::setGroup($name, array_merge($currentOption, $option), array_merge($currentPattern, $pattern)); - call_user_func_array($routes, []); - self::setGroup($currentGroup, $currentOption, $currentPattern); - if ($currentGroup != $name) { - self::$rules['*'][$name]['route'] = ''; - self::$rules['*'][$name]['var'] = self::parseVar($name); - self::$rules['*'][$name]['option'] = $option; - self::$rules['*'][$name]['pattern'] = $pattern; - } - } else { - $item = []; - foreach ($routes as $key => $val) { - if (is_numeric($key)) { - $key = array_shift($val); - } - if (is_array($val)) { - $route = $val[0]; - $option1 = array_merge($option, isset($val[1]) ? $val[1] : []); - $pattern1 = array_merge($pattern, isset($val[2]) ? $val[2] : []); - } else { - $route = $val; - } - - $options = isset($option1) ? $option1 : $option; - $patterns = isset($pattern1) ? $pattern1 : $pattern; - if ('$' == substr($key, -1, 1)) { - // 是否完整匹配 - $options['complete_match'] = true; - $key = substr($key, 0, -1); - } - $vars = self::parseVar($key); - $item[] = ['rule' => $key, 'route' => $route, 'var' => $vars, 'option' => $options, 'pattern' => $patterns]; - // 设置路由标识 - self::name($route, [$key, $vars, self::$domain]); - } - self::$rules['*'][$name] = ['rule' => $item, 'route' => '', 'var' => [], 'option' => $option, 'pattern' => $pattern]; - } - foreach (['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'] as $method) { - if (!isset(self::$rules[$method][$name])) { - self::$rules[$method][$name] = true; - } elseif (is_array(self::$rules[$method][$name])) { - self::$rules[$method][$name] = array_merge(self::$rules['*'][$name], self::$rules[$method][$name]); + if (is_array($name) && !empty($name)) { + $root = $this->request->rootDomain(); + foreach ($name as $item) { + if (!strpos($item, '.')) { + $item .= '.' . $root; } - } - } elseif ($routes instanceof \Closure) { - // 闭包注册 - $currentOption = self::getGroup('option'); - $currentPattern = self::getGroup('pattern'); - self::setGroup('', array_merge($currentOption, $option), array_merge($currentPattern, $pattern)); - call_user_func_array($routes, []); - self::setGroup($currentGroup, $currentOption, $currentPattern); - } else { - // 批量注册路由 - self::rule($routes, '', '*', $option, $pattern); + $this->domains[$item] = $domainName; + } } - } - /** - * 注册路由 - * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @return void - */ - public static function any($rule, $route = '', $option = [], $pattern = []) - { - self::rule($rule, $route, '*', $option, $pattern); + // 返回域名对象 + return $domain; } /** - * 注册GET路由 + * 获取域名 * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @return void + * @return array */ - public static function get($rule, $route = '', $option = [], $pattern = []) + public function getDomains() { - self::rule($rule, $route, 'GET', $option, $pattern); + return $this->domains; } /** - * 注册POST路由 + * 设置路由绑定 * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @return void + * @param string $bind 绑定信息 + * @param string $domain 域名 + * @return $this */ - public static function post($rule, $route = '', $option = [], $pattern = []) + public function bind($bind, $domain = null) { - self::rule($rule, $route, 'POST', $option, $pattern); + $domain = is_null($domain) ? $this->domain : $domain; + + $this->bind[$domain] = $bind; + + return $this; } /** - * 注册PUT路由 + * 读取路由绑定 * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @return void + * @param string $domain 域名 + * @return string|null */ - public static function put($rule, $route = '', $option = [], $pattern = []) + public function getBind($domain = null) { - self::rule($rule, $route, 'PUT', $option, $pattern); + if (is_null($domain)) { + $domain = $this->domain; + } elseif (true === $domain) { + return $this->bind; + } elseif (!strpos($domain, '.')) { + $domain .= '.' . $this->request->rootDomain(); + } + + $subDomain = $this->request->subDomain(); + + if (strpos($subDomain, '.')) { + $name = '*' . strstr($subDomain, '.'); + } + + if (isset($this->bind[$domain])) { + $result = $this->bind[$domain]; + } elseif (isset($name) && isset($this->bind[$name])) { + $result = $this->bind[$name]; + } elseif (isset($this->bind['*'])) { + $result = $this->bind['*']; + } else { + $result = null; + } + + return $result; } /** - * 注册DELETE路由 + * 读取路由标识 * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @return void + * @param string $name 路由标识 + * @param string $domain 域名 + * @return mixed */ - public static function delete($rule, $route = '', $option = [], $pattern = []) + public function getName($name = null, $domain = null) { - self::rule($rule, $route, 'DELETE', $option, $pattern); + return $this->app['rule_name']->get($name, $domain); } /** - * 注册PATCH路由 + * 批量导入路由标识 * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @return void + * @param array $name 路由标识 + * @return $this */ - public static function patch($rule, $route = '', $option = [], $pattern = []) + public function setName($name) { - self::rule($rule, $route, 'PATCH', $option, $pattern); + $this->app['rule_name']->import($name); + return $this; } /** - * 注册资源路由 + * 导入配置文件的路由规则 * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param array $option 路由参数 - * @param array $pattern 变量规则 + * @param array $rules 路由规则 + * @param string $type 请求类型 * @return void */ - public static function resource($rule, $route = '', $option = [], $pattern = []) + public function import(array $rules, $type = '*') { - if (is_array($rule)) { - foreach ($rule as $key => $val) { - if (is_array($val)) { - list($val, $option, $pattern) = array_pad($val, 3, []); - } - self::resource($key, $val, $option, $pattern); + // 检查域名部署 + if (isset($rules['__domain__'])) { + foreach ($rules['__domain__'] as $key => $rule) { + $this->domain($key, $rule); } - } else { - if (strpos($rule, '.')) { - // 注册嵌套资源路由 - $array = explode('.', $rule); - $last = array_pop($array); - $item = []; - foreach ($array as $val) { - $item[] = $val . '/:' . (isset($option['var'][$val]) ? $option['var'][$val] : $val . '_id'); - } - $rule = implode('/', $item) . '/' . $last; + unset($rules['__domain__']); + } + + // 检查变量规则 + if (isset($rules['__pattern__'])) { + $this->pattern($rules['__pattern__']); + unset($rules['__pattern__']); + } + + // 检查路由别名 + if (isset($rules['__alias__'])) { + $this->alias($rules['__alias__']); + unset($rules['__alias__']); + } + + // 检查资源路由 + if (isset($rules['__rest__'])) { + foreach ($rules['__rest__'] as $key => $rule) { + $this->resource($key, $rule); } - // 注册资源路由 - foreach (self::$rest as $key => $val) { - if ((isset($option['only']) && !in_array($key, $option['only'])) - || (isset($option['except']) && in_array($key, $option['except']))) { - continue; - } - if (isset($last) && strpos($val[1], ':id') && isset($option['var'][$last])) { - $val[1] = str_replace(':id', ':' . $option['var'][$last], $val[1]); - } elseif (strpos($val[1], ':id') && isset($option['var'][$rule])) { - $val[1] = str_replace(':id', ':' . $option['var'][$rule], $val[1]); - } - $item = ltrim($rule . $val[1], '/'); - self::rule($item . '$', $route . '/' . $val[2], $val[0], $option, $pattern); + unset($rules['__rest__']); + } + + // 检查路由规则(包含分组) + foreach ($rules as $key => $val) { + if (is_numeric($key)) { + $key = array_shift($val); + } + + if (empty($val)) { + continue; + } + + if (is_string($key) && 0 === strpos($key, '[')) { + $key = substr($key, 1, -1); + $this->group($key, $val); + } elseif (is_array($val)) { + $this->rule($key, $val[0], $type, $val[1], isset($val[2]) ? $val[2] : []); + } else { + $this->rule($key, $val, $type); } } } /** - * 注册控制器路由 操作方法对应不同的请求后缀 + * 注册路由规则 * @access public - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @return void + * @param string $rule 路由规则 + * @param mixed $route 路由地址 + * @param string $method 请求类型 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem */ - public static function controller($rule, $route = '', $option = [], $pattern = []) + public function rule($rule, $route, $method = '*', array $option = [], array $pattern = []) { - foreach (self::$methodPrefix as $type => $val) { - self::$type($rule . '/:action', $route . '/' . $val . ':action', $option, $pattern); - } + return $this->group->addRule($rule, $route, $method, $option, $pattern); } /** - * 注册别名路由 + * 设置跨域有效路由规则 * @access public - * @param string|array $rule 路由别名 - * @param string $route 路由地址 - * @param array $option 路由参数 - * @return void + * @param Rule $rule 路由规则 + * @param string $method 请求类型 + * @return $this */ - public static function alias($rule = null, $route = '', $option = []) + public function setCrossDomainRule($rule, $method = '*') { - if (is_array($rule)) { - self::$rules['alias'] = array_merge(self::$rules['alias'], $rule); - } else { - self::$rules['alias'][$rule] = $option ? [$route, $option] : $route; + if (!isset($this->cross)) { + $this->cross = (new RuleGroup($this))->mergeRuleRegex($this->mergeRuleRegex); } + + $this->cross->addRuleItem($rule, $method); + + return $this; } /** - * 设置不同请求类型下面的方法前缀 + * 批量注册路由规则 * @access public - * @param string $method 请求类型 - * @param string $prefix 类型前缀 + * @param array $rules 路由规则 + * @param string $method 请求类型 + * @param array $option 路由参数 + * @param array $pattern 变量规则 * @return void */ - public static function setMethodPrefix($method, $prefix = '') + public function rules($rules, $method = '*', array $option = [], array $pattern = []) { - if (is_array($method)) { - self::$methodPrefix = array_merge(self::$methodPrefix, array_change_key_case($method, CASE_UPPER)); - } else { - self::$methodPrefix[strtoupper($method)] = $prefix; - } + $this->group->addRules($rules, $method, $option, $pattern); } /** - * rest方法定义和修改 + * 注册路由分组 * @access public - * @param string $name 方法名称 - * @param array $resourece 资源 - * @return void + * @param string|array $name 分组名称或者参数 + * @param array|\Closure $route 分组路由 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleGroup */ - public static function rest($name, $resource = []) + public function group($name, $route, array $option = [], array $pattern = []) { if (is_array($name)) { - self::$rest = array_merge(self::$rest, $name); - } else { - self::$rest[$name] = $resource; + $option = $name; + $name = isset($option['name']) ? $option['name'] : ''; } + + return (new RuleGroup($this, $this->group, $name, $route, $option, $pattern)) + ->lazy($this->lazy) + ->mergeRuleRegex($this->mergeRuleRegex); } /** - * 注册未匹配路由规则后的处理 + * 注册路由 * @access public - * @param string $route 路由地址 - * @param string $method 请求类型 - * @param array $option 路由参数 - * @return void + * @param string $rule 路由规则 + * @param mixed $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem */ - public static function miss($route, $method = '*', $option = []) + public function any($rule, $route = '', array $option = [], array $pattern = []) { - self::rule('__miss__', $route, $method, $option, []); + return $this->rule($rule, $route, '*', $option, $pattern); } /** - * 注册一个自动解析的URL路由 + * 注册GET路由 * @access public - * @param string $route 路由地址 - * @return void + * @param string $rule 路由规则 + * @param mixed $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem */ - public static function auto($route) + public function get($rule, $route = '', array $option = [], array $pattern = []) { - self::rule('__auto__', $route, '*', [], []); + return $this->rule($rule, $route, 'GET', $option, $pattern); } /** - * 获取或者批量设置路由定义 + * 注册POST路由 * @access public - * @param mixed $rules 请求类型或者路由定义数组 - * @return array + * @param string $rule 路由规则 + * @param mixed $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem */ - public static function rules($rules = '') + public function post($rule, $route = '', array $option = [], array $pattern = []) { - if (is_array($rules)) { - self::$rules = $rules; - } elseif ($rules) { - return true === $rules ? self::$rules : self::$rules[$rules]; - } else { - $rules = self::$rules; - unset($rules['pattern'], $rules['alias'], $rules['domain'], $rules['name']); - return $rules; - } + return $this->rule($rule, $route, 'POST', $option, $pattern); } /** - * 检测子域名部署 + * 注册PUT路由 * @access public - * @param Request $request Request请求对象 - * @param array $currentRules 当前路由规则 - * @param string $method 请求类型 - * @return void + * @param string $rule 路由规则 + * @param mixed $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem */ - public static function checkDomain($request, &$currentRules, $method = 'GET') + public function put($rule, $route = '', array $option = [], array $pattern = []) { - // 域名规则 - $rules = self::$rules['domain']; - // 开启子域名部署 支持二级和三级域名 - if (!empty($rules)) { - $host = $request->host(); - if (isset($rules[$host])) { - // 完整域名或者IP配置 - $item = $rules[$host]; - } else { - $rootDomain = Config::get('url_domain_root'); - if ($rootDomain) { - // 配置域名根 例如 thinkphp.cn 163.com.cn 如果是国家级域名 com.cn net.cn 之类的域名需要配置 - $domain = explode('.', rtrim(stristr($host, $rootDomain, true), '.')); - } else { - $domain = explode('.', $host, -2); - } - // 子域名配置 - if (!empty($domain)) { - // 当前子域名 - $subDomain = implode('.', $domain); - self::$subDomain = $subDomain; - $domain2 = array_pop($domain); - if ($domain) { - // 存在三级域名 - $domain3 = array_pop($domain); - } - if ($subDomain && isset($rules[$subDomain])) { - // 子域名配置 - $item = $rules[$subDomain]; - } elseif (isset($rules['*.' . $domain2]) && !empty($domain3)) { - // 泛三级域名 - $item = $rules['*.' . $domain2]; - $panDomain = $domain3; - } elseif (isset($rules['*']) && !empty($domain2)) { - // 泛二级域名 - if ('www' != $domain2) { - $item = $rules['*']; - $panDomain = $domain2; - } - } - } - } - if (!empty($item)) { - if (isset($item['[bind]'])) { - // 解析子域名部署规则 - list($rule, $option, $pattern) = $item['[bind]']; - if (!empty($option['https']) && !$request->isSsl()) { - // https检测 - throw new HttpException(404, 'must use https request:' . $host); - } - - if (strpos($rule, '?')) { - // 传入其它参数 - $array = parse_url($rule); - $result = $array['path']; - parse_str($array['query'], $params); - if (isset($panDomain)) { - $pos = array_search('*', $params); - if (false !== $pos) { - // 泛域名作为参数 - $params[$pos] = $panDomain; - } - } - $_GET = array_merge($_GET, $params); - } else { - $result = $rule; - } - - if (0 === strpos($result, '\\')) { - // 绑定到命名空间 例如 \app\index\behavior - self::$bind = ['type' => 'namespace', 'namespace' => $result]; - } elseif (0 === strpos($result, '@')) { - // 绑定到类 例如 @app\index\controller\User - self::$bind = ['type' => 'class', 'class' => substr($result, 1)]; - } else { - // 绑定到模块/控制器 例如 index/user - self::$bind = ['type' => 'module', 'module' => $result]; - } - self::$domainBind = true; - } else { - self::$domainRule = $item; - $currentRules = isset($item[$method]) ? $item[$method] : $item['*']; - } - } - } + return $this->rule($rule, $route, 'PUT', $option, $pattern); } /** - * 检测URL路由 + * 注册DELETE路由 * @access public - * @param Request $request Request请求对象 - * @param string $url URL地址 - * @param string $depr URL分隔符 - * @param bool $checkDomain 是否检测域名规则 - * @return false|array + * @param string $rule 路由规则 + * @param mixed $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem */ - public static function check($request, $url, $depr = '/', $checkDomain = false) + public function delete($rule, $route = '', array $option = [], array $pattern = []) { - // 分隔符替换 确保路由定义使用统一的分隔符 - if ('/' != $depr) { - $url = str_replace($depr, '/', $url); - } - - if (strpos($url, '/') && isset(self::$rules['alias'][strstr($url, '/', true)])) { - // 检测路由别名 - $result = self::checkRouteAlias($request, $url, $depr); - if (false !== $result) { - return $result; - } - } - $method = $request->method(); - // 获取当前请求类型的路由规则 - $rules = self::$rules[$method]; - // 检测域名部署 - if ($checkDomain) { - self::checkDomain($request, $rules, $method); - } - // 检测URL绑定 - $return = self::checkUrlBind($url, $rules, $depr); - if (false !== $return) { - return $return; - } - if ('/' != $url) { - $url = rtrim($url, '/'); - } - if (isset($rules[$url])) { - // 静态路由规则检测 - $rule = $rules[$url]; - if (true === $rule) { - $rule = self::getRouteExpress($url); - } - if (!empty($rule['route']) && self::checkOption($rule['option'], $url, $request)) { - return self::parseRule($url, $rule['route'], $url, $rule['option']); - } - } - - // 路由规则检测 - if (!empty($rules)) { - return self::checkRoute($request, $rules, $url, $depr); - } - return false; + return $this->rule($rule, $route, 'DELETE', $option, $pattern); } - private static function getRouteExpress($key) + /** + * 注册PATCH路由 + * @access public + * @param string $rule 路由规则 + * @param mixed $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem + */ + public function patch($rule, $route = '', array $option = [], array $pattern = []) { - return self::$domainRule ? self::$domainRule['*'][$key] : self::$rules['*'][$key]; + return $this->rule($rule, $route, 'PATCH', $option, $pattern); } /** - * 检测路由规则 - * @access private - * @param Request $request - * @param array $rules 路由规则 - * @param string $url URL地址 - * @param string $depr URL分割符 - * @param string $group 路由分组名 - * @param array $options 路由参数(分组) - * @return mixed + * 注册资源路由 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return Resource */ - private static function checkRoute($request, $rules, $url, $depr = '/', $group = '', $options = []) + public function resource($rule, $route = '', array $option = [], array $pattern = []) { - foreach ($rules as $key => $item) { - if (true === $item) { - $item = self::getRouteExpress($key); - } - if (!isset($item['rule'])) { - continue; - } - $rule = $item['rule']; - $route = $item['route']; - $vars = $item['var']; - $option = $item['option']; - $pattern = $item['pattern']; - - // 检查参数有效性 - if (!self::checkOption($option, $url, $request)) { - continue; - } - - if (isset($option['ext'])) { - // 路由ext参数 优先于系统配置的URL伪静态后缀参数 - $url = preg_replace('/\.' . $request->ext() . '$/i', '', $url); - } - - if (is_array($rule)) { - // 分组路由 - $pos = strpos(str_replace('<', ':', $key), ':'); - if (false !== $pos) { - $str = substr($key, 0, $pos); - } else { - $str = $key; - } - if (is_string($str) && $str && 0 !== strpos($url, $str)) { - continue; - } - - $result = self::checkRoute($request, $rule, $url, $depr, $key, $option); - if (false !== $result) { - return $result; - } - } elseif ($route) { - if ('__miss__' == $rule || '__auto__' == $rule) { - // 指定特殊路由 - $var = trim($rule, '__'); - ${$var} = $item; - continue; - } - if ($group) { - $rule = $group . ($rule ? '/' . ltrim($rule, '/') : ''); - } - if (isset($options['bind_model']) && isset($option['bind_model'])) { - $option['bind_model'] = array_merge($options['bind_model'], $option['bind_model']); - } - $result = self::checkRule($rule, $route, $url, $pattern, $option); - if (false !== $result) { - return $result; - } - } - } - if (isset($auto)) { - // 自动解析URL地址 - return self::parseUrl($auto['route'] . '/' . $url, $depr); - } elseif (isset($miss)) { - // 未匹配所有路由的路由规则处理 - return self::parseRule('', $miss['route'], $url, $miss['option']); - } - return false; + return (new Resource($this, $this->group, $rule, $route, $option, $pattern, $this->rest)) + ->lazy($this->lazy); } /** - * 检测路由别名 - * @access private - * @param Request $request - * @param string $url URL地址 - * @param string $depr URL分隔符 - * @return mixed + * 注册控制器路由 操作方法对应不同的请求前缀 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleGroup */ - private static function checkRouteAlias($request, $url, $depr) + public function controller($rule, $route = '', array $option = [], array $pattern = []) { - $array = explode('/', $url, 2); - $item = self::$rules['alias'][$array[0]]; + $group = new RuleGroup($this, $this->group, $rule, null, $option, $pattern); - if (is_array($item)) { - list($rule, $option) = $item; - } else { - $rule = $item; - } - // 参数有效性检查 - if (isset($option) && !self::checkOption($option, $url, $request)) { - // 路由不匹配 - return false; - } elseif (0 === strpos($rule, '\\')) { - // 路由到类 - return self::bindToClass($array[1], substr($rule, 1), $depr); - } elseif (0 === strpos($url, '@')) { - // 路由到控制器类 - return self::bindToController($array[1], substr($rule, 1), $depr); - } else { - // 路由到模块/控制器 - return self::bindToModule($array[1], $rule, $depr); + foreach ($this->methodPrefix as $type => $val) { + $group->addRule('', $val . '', $type); } + + return $group->prefix($route . '/'); } /** - * 检测URL绑定 - * @access private - * @param string $url URL地址 - * @param array $rules 路由规则 - * @param string $depr URL分隔符 - * @return mixed + * 注册视图路由 + * @access public + * @param string|array $rule 路由规则 + * @param string $template 路由模板地址 + * @param array $vars 模板变量 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem */ - private static function checkUrlBind(&$url, &$rules, $depr = '/') + public function view($rule, $template = '', array $vars = [], array $option = [], array $pattern = []) { - if (!empty(self::$bind)) { - $type = self::$bind['type']; - $bind = self::$bind[$type]; - // 记录绑定信息 - App::$debug && Log::record('[ BIND ] ' . var_export($bind, true), 'info'); - // 如果有URL绑定 则进行绑定检测 - switch ($type) { - case 'class': - // 绑定到类 - return self::bindToClass($url, $bind, $depr); - case 'namespace': - // 绑定到命名空间 - return self::bindToNamespace($url, $bind, $depr); - } - } - return false; + return $this->rule($rule, $template, 'GET', $option, $pattern)->view($vars); } /** - * 绑定到类 + * 注册重定向路由 * @access public - * @param string $url URL地址 - * @param string $class 类名(带命名空间) - * @param string $depr URL分隔符 - * @return array + * @param string|array $rule 路由规则 + * @param string $route 路由地址 + * @param array $status 状态码 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return RuleItem */ - public static function bindToClass($url, $class, $depr = '/') + public function redirect($rule, $route = '', $status = 301, array $option = [], array $pattern = []) { - $array = explode($depr, $url, 2); - $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); - if (!empty($array[1])) { - self::parseUrlParams($array[1]); - } - return ['type' => 'method', 'method' => [$class, $action]]; + return $this->rule($rule, $route, '*', $option, $pattern)->redirect()->status($status); } /** - * 绑定到命名空间 + * 注册别名路由 * @access public - * @param string $url URL地址 - * @param string $namespace 命名空间 - * @param string $depr URL分隔符 - * @return array + * @param string $rule 路由别名 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @return AliasRule */ - public static function bindToNamespace($url, $namespace, $depr = '/') + public function alias($rule, $route, array $option = []) { - $array = explode($depr, $url, 3); - $class = !empty($array[0]) ? $array[0] : Config::get('default_controller'); - $method = !empty($array[1]) ? $array[1] : Config::get('default_action'); - if (!empty($array[2])) { - self::parseUrlParams($array[2]); - } - return ['type' => 'method', 'method' => [$namespace . '\\' . $class, $method]]; + $aliasRule = new AliasRule($this, $this->group, $rule, $route, $option); + + $this->alias[$rule] = $aliasRule; + + return $aliasRule; } /** - * 绑定到控制器类 + * 获取别名路由定义 * @access public - * @param string $url URL地址 - * @param string $controller 控制器名 (支持带模块名 index/user ) - * @param string $depr URL分隔符 - * @return array + * @param string $name 路由别名 + * @return string|array|null */ - public static function bindToController($url, $controller, $depr = '/') + public function getAlias($name = null) { - $array = explode($depr, $url, 2); - $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); - if (!empty($array[1])) { - self::parseUrlParams($array[1]); + if (is_null($name)) { + return $this->alias; } - return ['type' => 'controller', 'controller' => $controller . '/' . $action]; + + return isset($this->alias[$name]) ? $this->alias[$name] : null; } /** - * 绑定到模块/控制器 + * 设置不同请求类型下面的方法前缀 * @access public - * @param string $url URL地址 - * @param string $class 控制器类名(带命名空间) - * @param string $depr URL分隔符 - * @return array + * @param string|array $method 请求类型 + * @param string $prefix 类型前缀 + * @return $this */ - public static function bindToModule($url, $controller, $depr = '/') + public function setMethodPrefix($method, $prefix = '') { - $array = explode($depr, $url, 2); - $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); - if (!empty($array[1])) { - self::parseUrlParams($array[1]); + if (is_array($method)) { + $this->methodPrefix = array_merge($this->methodPrefix, array_change_key_case($method)); + } else { + $this->methodPrefix[strtolower($method)] = $prefix; } - return ['type' => 'module', 'module' => $controller . '/' . $action]; + + return $this; } /** - * 路由参数有效性检查 - * @access private - * @param array $option 路由参数 - * @param string $url URL地址 - * @param Request $request Request对象 - * @return bool + * 获取请求类型的方法前缀 + * @access public + * @param string $method 请求类型 + * @param string $prefix 类型前缀 + * @return string|null */ - private static function checkOption($option, $url, $request) + public function getMethodPrefix($method) { - // 请求类型检测 - if ((isset($option['method']) && false === stripos($option['method'], $request->method())) - || (isset($option['ext']) && false === stripos($option['ext'], $request->ext())) // 伪静态后缀检测 - || (isset($option['deny_ext']) && false !== stripos($option['deny_ext'], $request->ext())) - || (isset($option['domain']) && !in_array($option['domain'], [$_SERVER['HTTP_HOST'], self::$subDomain])) // 域名检测 - || (!empty($option['https']) && !$request->isSsl()) // https检测 - || (!empty($option['before_behavior']) && false === Hook::exec($option['before_behavior'], '', $url)) // 行为检测 - || (!empty($option['callback']) && is_callable($option['callback']) && false === call_user_func($option['callback'])) // 自定义检测 - ) { - return false; - } - return true; + $method = strtolower($method); + + return isset($this->methodPrefix[$method]) ? $this->methodPrefix[$method] : null; } /** - * 检测路由规则 - * @access private - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param string $url URL地址 - * @param array $pattern 变量规则 - * @param array $option 路由参数 - * @return array|false + * rest方法定义和修改 + * @access public + * @param string $name 方法名称 + * @param array|bool $resource 资源 + * @return $this */ - private static function checkRule($rule, $route, $url, $pattern, $option) + public function rest($name, $resource = []) { - // 检查完整规则定义 - if (isset($pattern['__url__']) && !preg_match('/^' . $pattern['__url__'] . '/', $url)) { - return false; - } - // 检测是否设置了参数分隔符 - if ($depr = Config::get('url_params_depr')) { - $url = str_replace($depr, '/', $url); - $rule = str_replace($depr, '/', $rule); + if (is_array($name)) { + $this->rest = $resource ? $name : array_merge($this->rest, $name); + } else { + $this->rest[$name] = $resource; } - $len1 = substr_count($url, '/'); - $len2 = substr_count($rule, '/'); - // 多余参数是否合并 - $merge = !empty($option['merge_extra_vars']) ? true : false; - - if ($len1 >= $len2 || strpos($rule, '[')) { - if (!empty($option['complete_match'])) { - // 完整匹配 - if (!$merge && $len1 != $len2 && (false === strpos($rule, '[') || $len1 > $len2 || $len1 < $len2 - substr_count($rule, '['))) { - return false; - } - } - $pattern = array_merge(self::$rules['pattern'], $pattern); - if (false !== $match = self::match($url, $rule, $pattern, $merge)) { - // 匹配到路由规则 - return self::parseRule($rule, $route, $url, $option, $match, $merge); - } - } - return false; + return $this; } /** - * 解析模块的URL地址 [模块/控制器/操作?]参数1=值1&参数2=值2... + * 获取rest方法定义的参数 * @access public - * @param string $url URL地址 - * @param string $depr URL分隔符 - * @param bool $autoSearch 是否自动深度搜索控制器 - * @return array + * @param string $name 方法名称 + * @return array|null */ - public static function parseUrl($url, $depr = '/', $autoSearch = false) + public function getRest($name = null) { - if (isset(self::$bind['module'])) { - // 如果有模块/控制器绑定 - $url = self::$bind['module'] . '/' . ltrim($url, '/'); + if (is_null($name)) { + return $this->rest; } - list($path, $var) = self::parseUrlPath($url, $depr); - $route = [null, null, null]; - if (isset($path)) { - // 解析模块 - $module = Config::get('app_multi_module') ? array_shift($path) : null; - if ($autoSearch) { - // 自动搜索控制器 - $dir = APP_PATH . ($module ? $module . DS : '') . Config::get('url_controller_layer'); - $suffix = App::$suffix || Config::get('controller_suffix') ? ucfirst(Config::get('url_controller_layer')) : ''; - $item = []; - foreach ($path as $val) { - $item[] = array_shift($path); - if (is_file($dir . DS . $val . $suffix . EXT)) { - break; - } else { - $dir .= DS . $val; - } - } - $controller = implode('.', $item); - } else { - // 解析控制器 - $controller = !empty($path) ? array_shift($path) : null; - } - // 解析操作 - $action = !empty($path) ? array_shift($path) : null; - // 解析额外参数 - self::parseUrlParams(empty($path) ? '' : implode('/', $path)); - // 封装路由 - $route = [$module, $controller, $action]; - if (isset(self::$rules['name'][implode($depr, $route)])) { - throw new HttpException(404, 'invalid request:' . $url); - } - } - return ['type' => 'module', 'module' => $route]; + return isset($this->rest[$name]) ? $this->rest[$name] : null; } /** - * 解析URL的pathinfo参数和变量 - * @access private - * @param string $url URL地址 - * @param string $depr URL分隔符 - * @return array + * 注册未匹配路由规则后的处理 + * @access public + * @param string $route 路由地址 + * @param string $method 请求类型 + * @param array $option 路由参数 + * @return RuleItem */ - private static function parseUrlPath($url, $depr = '/') + public function miss($route, $method = '*', array $option = []) { - // 分隔符替换 确保路由定义使用统一的分隔符 - if ('/' != $depr) { - $url = str_replace($depr, '/', $url); - } - $url = trim($url, '/'); - $var = []; - if (false !== strpos($url, '?')) { - // [模块/控制器/操作?]参数1=值1&参数2=值2... - $info = parse_url($url); - $path = explode('/', $info['path']); - parse_str($info['query'], $var); - } elseif (strpos($url, '/')) { - // [模块/控制器/操作] - $path = explode('/', $url); - } elseif (false !== strpos($url, '=')) { - // 参数1=值1&参数2=值2... - parse_str($url, $var); - } else { - $path = [$url]; - } - return [$path, $var]; + return $this->group->addMissRule($route, $method, $option); } /** - * 检测URL和规则路由是否匹配 - * @access private - * @param string $url URL地址 - * @param string $rule 路由规则 - * @param array $pattern 变量规则 - * @param bool $merge 合并额外变量 - * @return array|false + * 注册一个自动解析的URL路由 + * @access public + * @param string $route 路由地址 + * @return RuleItem */ - private static function match($url, $rule, $pattern, $merge) + public function auto($route) { - $m2 = explode('/', $rule); - $m1 = $merge ? explode('/', $url, count($m2)) : explode('/', $url); - - $var = []; - foreach ($m2 as $key => $val) { - // val中定义了多个变量 - if (false !== strpos($val, '<') && preg_match_all('/<(\w+(\??))>/', $val, $matches)) { - $value = []; - $replace = []; - foreach ($matches[1] as $name) { - if (strpos($name, '?')) { - $name = substr($name, 0, -1); - $replace[] = '(' . (isset($pattern[$name]) ? $pattern[$name] : '\w+') . ')?'; - } else { - $replace[] = '(' . (isset($pattern[$name]) ? $pattern[$name] : '\w+') . ')'; - } - $value[] = $name; - } - $val = str_replace($matches[0], $replace, $val); - if (preg_match('/^' . $val . '$/', isset($m1[$key]) ? $m1[$key] : '', $match)) { - array_shift($match); - foreach ($value as $k => $name) { - if (isset($match[$k])) { - $var[$name] = $match[$k]; - } - } - continue; - } else { - return false; - } - } - - if (0 === strpos($val, '[:')) { - // 可选参数 - $val = substr($val, 1, -1); - $optional = true; - } else { - $optional = false; - } - if (0 === strpos($val, ':')) { - // URL变量 - $name = substr($val, 1); - if (!$optional && !isset($m1[$key])) { - return false; - } - if (isset($m1[$key]) && isset($pattern[$name]) && !preg_match('/^' . $pattern[$name] . '$/', $m1[$key])) { - // 检查变量规则 - return false; - } - $var[$name] = isset($m1[$key]) ? $m1[$key] : ''; - } elseif (!isset($m1[$key]) || 0 !== strcasecmp($val, $m1[$key])) { - return false; - } - } - // 成功匹配后返回URL中的动态变量数组 - return $var; + return $this->group->addAutoRule($route); } /** - * 解析规则路由 - * @access private - * @param string $rule 路由规则 - * @param string $route 路由地址 - * @param string $pathinfo URL地址 - * @param array $option 路由参数 - * @param array $matches 匹配的变量 - * @param bool $merge 合并额外变量 - * @return array + * 检测URL路由 + * @access public + * @param string $url URL地址 + * @param bool $must 是否强制路由 + * @return Dispatch + * @throws RouteNotFoundException */ - private static function parseRule($rule, $route, $pathinfo, $option = [], $matches = [], $merge = false) + public function check($url, $must = false) { - $request = Request::instance(); - // 解析路由规则 - if ($rule) { - $rule = explode('/', $rule); - // 获取URL地址中的参数 - $paths = $merge ? explode('/', $pathinfo, count($rule)) : explode('/', $pathinfo); - foreach ($rule as $item) { - $fun = ''; - if (0 === strpos($item, '[:')) { - $item = substr($item, 1, -1); - } - if (0 === strpos($item, ':')) { - $var = substr($item, 1); - $matches[$var] = array_shift($paths); - } else { - // 过滤URL中的静态变量 - array_shift($paths); - } - } - } else { - $paths = explode('/', $pathinfo); - } + // 自动检测域名路由 + $domain = $this->checkDomain(); + $url = str_replace($this->config['pathinfo_depr'], '|', $url); - // 获取路由地址规则 - if (is_string($route) && isset($option['prefix'])) { - // 路由地址前缀 - $route = $option['prefix'] . $route; - } - // 替换路由地址中的变量 - if (is_string($route) && !empty($matches)) { - foreach ($matches as $key => $val) { - if (false !== strpos($route, ':' . $key)) { - $route = str_replace(':' . $key, $val, $route); - unset($matches[$key]); - } - } - } - - // 绑定模型数据 - if (isset($option['bind_model'])) { - $bind = []; - foreach ($option['bind_model'] as $key => $val) { - if ($val instanceof \Closure) { - $result = call_user_func_array($val, [$matches]); - } else { - if (is_array($val)) { - $fields = explode('&', $val[1]); - $model = $val[0]; - $exception = isset($val[2]) ? $val[2] : true; - } else { - $fields = ['id']; - $model = $val; - $exception = true; - } - $where = []; - $match = true; - foreach ($fields as $field) { - if (!isset($matches[$field])) { - $match = false; - break; - } else { - $where[$field] = $matches[$field]; - } - } - if ($match) { - $query = strpos($model, '\\') ? $model::where($where) : Loader::model($model)->where($where); - $result = $query->failException($exception)->find(); - } - } - if (!empty($result)) { - $bind[$key] = $result; - } - } - $request->bind($bind); - } + $completeMatch = $this->config['route_complete_match']; - // 解析额外参数 - self::parseUrlParams(empty($paths) ? '' : implode('/', $paths), $matches); - // 记录匹配的路由信息 - $request->routeInfo(['rule' => $rule, 'route' => $route, 'option' => $option, 'var' => $matches]); + $result = $domain->check($this->request, $url, $completeMatch); - // 检测路由after行为 - if (!empty($option['after_behavior'])) { - if ($option['after_behavior'] instanceof \Closure) { - $result = call_user_func_array($option['after_behavior'], []); - } else { - foreach ((array) $option['after_behavior'] as $behavior) { - $result = Hook::exec($behavior, ''); - if (!is_null($result)) { - break; - } - } - } - // 路由规则重定向 - if ($result instanceof Response) { - return ['type' => 'response', 'response' => $result]; - } elseif (is_array($result)) { - return $result; - } + if (false === $result && !empty($this->cross)) { + // 检测跨域路由 + $result = $this->cross->check($this->request, $url, $completeMatch); } - if ($route instanceof \Closure) { - // 执行闭包 - $result = ['type' => 'function', 'function' => $route]; - } elseif (0 === strpos($route, '/') || 0 === strpos($route, 'http')) { - // 路由到重定向地址 - $result = ['type' => 'redirect', 'url' => $route, 'status' => isset($option['status']) ? $option['status'] : 301]; - } elseif (false !== strpos($route, '\\')) { - // 路由到方法 - $route = str_replace('/', '@', $route); - $method = strpos($route, '@') ? explode('@', $route) : $route; - $result = ['type' => 'method', 'method' => $method]; - } elseif (0 === strpos($route, '@')) { - // 路由到控制器 - $result = ['type' => 'controller', 'controller' => substr($route, 1)]; - } else { - // 路由到模块/控制器/操作 - $result = self::parseModule($route); - } - // 开启请求缓存 - if ($request->isGet() && !empty($option['cache'])) { - $cache = $option['cache']; - if (is_array($cache)) { - list($key, $expire) = $cache; - } else { - $key = $pathinfo; - $expire = $cache; - } - $request->cache($key, $expire); + if (false !== $result) { + // 路由匹配 + return $result; + } elseif ($must) { + // 强制路由不匹配则抛出异常 + throw new RouteNotFoundException(); } - return $result; - } - /** - * 解析URL地址为 模块/控制器/操作 - * @access private - * @param string $url URL地址 - * @param string $depr URL分隔符 - * @return array - */ - private static function parseModule($url, $depr = '/') - { - list($path, $var) = self::parseUrlPath($url, $depr); - $action = array_pop($path); - $controller = !empty($path) ? array_pop($path) : null; - $module = Config::get('app_multi_module') && !empty($path) ? array_pop($path) : null; - $method = Request::instance()->method(); - if (Config::get('use_action_prefix') && !empty(self::$methodPrefix[$method])) { - // 操作方法前缀支持 - $action = 0 !== strpos($action, self::$methodPrefix[$method]) ? self::$methodPrefix[$method] . $action : $action; - } - // 设置当前请求的路由变量 - Request::instance()->route($var); - // 路由到模块/控制器/操作 - return ['type' => 'module', 'module' => [$module, $controller, $action], 'convert' => false]; + // 默认路由解析 + return new UrlDispatch($this->request, $this->group, $url, [ + 'auto_search' => $this->autoSearchController, + ]); } /** - * 解析URL地址中的参数Request对象 - * @access private - * @param string $rule 路由规则 - * @param array $var 变量 - * @return void + * 检测域名的路由规则 + * @access protected + * @return Domain */ - private static function parseUrlParams($url, &$var = []) + protected function checkDomain() { - if ($url) { - if (Config::get('url_param_type')) { - $var += explode('/', $url); - } else { - preg_replace_callback('/(\w+)\/([^\/]+)/', function ($match) use (&$var) { - $var[$match[1]] = strip_tags($match[2]); - }, $url); + // 获取当前子域名 + $subDomain = $this->request->subDomain(); + + $item = false; + + if ($subDomain && count($this->domains) > 1) { + $domain = explode('.', $subDomain); + $domain2 = array_pop($domain); + + if ($domain) { + // 存在三级域名 + $domain3 = array_pop($domain); } - } - // 设置当前请求的参数 - Request::instance()->route($var); - } - // 分析路由规则中的变量 - private static function parseVar($rule) - { - // 提取路由规则中的变量 - $var = []; - foreach (explode('/', $rule) as $val) { - $optional = false; - if (false !== strpos($val, '<') && preg_match_all('/<(\w+(\??))>/', $val, $matches)) { - foreach ($matches[1] as $name) { - if (strpos($name, '?')) { - $name = substr($name, 0, -1); - $optional = true; - } else { - $optional = false; - } - $var[$name] = $optional ? 2 : 1; + if ($subDomain && isset($this->domains[$subDomain])) { + // 子域名配置 + $item = $this->domains[$subDomain]; + } elseif (isset($this->domains['*.' . $domain2]) && !empty($domain3)) { + // 泛三级域名 + $item = $this->domains['*.' . $domain2]; + $panDomain = $domain3; + } elseif (isset($this->domains['*']) && !empty($domain2)) { + // 泛二级域名 + if ('www' != $domain2) { + $item = $this->domains['*']; + $panDomain = $domain2; } } - if (0 === strpos($val, '[:')) { - // 可选参数 - $optional = true; - $val = substr($val, 1, -1); - } - if (0 === strpos($val, ':')) { - // URL变量 - $name = substr($val, 1); - $var[$name] = $optional ? 2 : 1; + if (isset($panDomain)) { + // 保存当前泛域名 + $this->request->setPanDomain($panDomain); } } - return $var; + + if (false === $item) { + // 检测当前完整域名 + $item = $this->domains[$this->host]; + } + + if (is_string($item)) { + $item = $this->domains[$item]; + } + + return $item; + } + + /** + * 设置全局的路由分组参数 + * @access public + * @param string $method 方法名 + * @param array $args 调用参数 + * @return RuleGroup + */ + public function __call($method, $args) + { + return call_user_func_array([$this->group, $method], $args); } } diff --git a/library/think/Session.php b/library/think/Session.php index e8f56fd935221fe58a8d8297987af967fed83b6d..e700f0e4ced46e4e91b6ad15bed52d43589b6832 100644 --- a/library/think/Session.php +++ b/library/think/Session.php @@ -1,303 +1,570 @@ - -// +---------------------------------------------------------------------- - -namespace think; - -use think\App; -use think\exception\ClassNotFoundException; - -class Session -{ - protected static $prefix = ''; - protected static $init = null; - - /** - * 设置或者获取session作用域(前缀) - * @param string $prefix - * @return string|void - */ - public static function prefix($prefix = '') - { - if (empty($prefix) && null !== $prefix) { - return self::$prefix; - } else { - self::$prefix = $prefix; - } - } - - /** - * session初始化 - * @param array $config - * @return void - * @throws \think\Exception - */ - public static function init(array $config = []) - { - if (empty($config)) { - $config = Config::get('session'); - } - // 记录初始化信息 - App::$debug && Log::record('[ SESSION ] INIT ' . var_export($config, true), 'info'); - $isDoStart = false; - if (isset($config['use_trans_sid'])) { - ini_set('session.use_trans_sid', $config['use_trans_sid'] ? 1 : 0); - } - - // 启动session - if (!empty($config['auto_start']) && PHP_SESSION_ACTIVE != session_status()) { - ini_set('session.auto_start', 0); - $isDoStart = true; - } - - if (isset($config['prefix'])) { - self::$prefix = $config['prefix']; - } - if (isset($config['var_session_id']) && isset($_REQUEST[$config['var_session_id']])) { - session_id($_REQUEST[$config['var_session_id']]); - } elseif (isset($config['id']) && !empty($config['id'])) { - session_id($config['id']); - } - if (isset($config['name'])) { - session_name($config['name']); - } - if (isset($config['path'])) { - session_save_path($config['path']); - } - if (isset($config['domain'])) { - ini_set('session.cookie_domain', $config['domain']); - } - if (isset($config['expire'])) { - ini_set('session.gc_maxlifetime', $config['expire']); - ini_set('session.cookie_lifetime', $config['expire']); - } - - if (isset($config['use_cookies'])) { - ini_set('session.use_cookies', $config['use_cookies'] ? 1 : 0); - } - if (isset($config['cache_limiter'])) { - session_cache_limiter($config['cache_limiter']); - } - if (isset($config['cache_expire'])) { - session_cache_expire($config['cache_expire']); - } - if (!empty($config['type'])) { - // 读取session驱动 - $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\session\\driver\\' . ucwords($config['type']); - - // 检查驱动类 - if (!class_exists($class) || !session_set_save_handler(new $class($config))) { - throw new ClassNotFoundException('error session handler:' . $class, $class); - } - } - if ($isDoStart) { - session_start(); - self::$init = true; - } else { - self::$init = false; - } - } - - /** - * session自动启动或者初始化 - * @return void - */ - public static function boot() - { - if (is_null(self::$init)) { - self::init(); - } elseif (false === self::$init) { - session_start(); - self::$init = true; - } - } - - /** - * session设置 - * @param string $name session名称 - * @param mixed $value session值 - * @param string|null $prefix 作用域(前缀) - * @return void - */ - public static function set($name, $value = '', $prefix = null) - { - empty(self::$init) && self::boot(); - - $prefix = !is_null($prefix) ? $prefix : self::$prefix; - if (strpos($name, '.')) { - // 二维数组赋值 - list($name1, $name2) = explode('.', $name); - if ($prefix) { - $_SESSION[$prefix][$name1][$name2] = $value; - } else { - $_SESSION[$name1][$name2] = $value; - } - } elseif ($prefix) { - $_SESSION[$prefix][$name] = $value; - } else { - $_SESSION[$name] = $value; - } - } - - /** - * session获取 - * @param string $name session名称 - * @param string|null $prefix 作用域(前缀) - * @return mixed - */ - public static function get($name = '', $prefix = null) - { - empty(self::$init) && self::boot(); - $prefix = !is_null($prefix) ? $prefix : self::$prefix; - if ('' == $name) { - // 获取全部的session - $value = $prefix ? (!empty($_SESSION[$prefix]) ? $_SESSION[$prefix] : []) : $_SESSION; - } elseif ($prefix) { - // 获取session - if (strpos($name, '.')) { - list($name1, $name2) = explode('.', $name); - $value = isset($_SESSION[$prefix][$name1][$name2]) ? $_SESSION[$prefix][$name1][$name2] : null; - } else { - $value = isset($_SESSION[$prefix][$name]) ? $_SESSION[$prefix][$name] : null; - } - } else { - if (strpos($name, '.')) { - list($name1, $name2) = explode('.', $name); - $value = isset($_SESSION[$name1][$name2]) ? $_SESSION[$name1][$name2] : null; - } else { - $value = isset($_SESSION[$name]) ? $_SESSION[$name] : null; - } - } - return $value; - } - - /** - * session获取并删除 - * @param string $name session名称 - * @param string|null $prefix 作用域(前缀) - * @return mixed - */ - public static function pull($name, $prefix = null) - { - $result = self::get($name, $prefix); - if ($result) { - self::delete($name, $prefix); - return $result; - } else { - return null; - } - } - - /** - * 删除session数据 - * @param string $name session名称 - * @param string|null $prefix 作用域(前缀) - * @return void - */ - public static function delete($name, $prefix = null) - { - empty(self::$init) && self::boot(); - $prefix = !is_null($prefix) ? $prefix : self::$prefix; - if (strpos($name, '.')) { - list($name1, $name2) = explode('.', $name); - if ($prefix) { - unset($_SESSION[$prefix][$name1][$name2]); - } else { - unset($_SESSION[$name1][$name2]); - } - } else { - if ($prefix) { - unset($_SESSION[$prefix][$name]); - } else { - unset($_SESSION[$name]); - } - } - } - - /** - * 清空session数据 - * @param string|null $prefix 作用域(前缀) - * @return void - */ - public static function clear($prefix = null) - { - empty(self::$init) && self::boot(); - $prefix = !is_null($prefix) ? $prefix : self::$prefix; - if ($prefix) { - unset($_SESSION[$prefix]); - } else { - $_SESSION = []; - } - } - - /** - * 判断session数据 - * @param string $name session名称 - * @param string|null $prefix - * @return bool - */ - public static function has($name, $prefix = null) - { - empty(self::$init) && self::boot(); - $prefix = !is_null($prefix) ? $prefix : self::$prefix; - if (strpos($name, '.')) { - // 支持数组 - list($name1, $name2) = explode('.', $name); - return $prefix ? isset($_SESSION[$prefix][$name1][$name2]) : isset($_SESSION[$name1][$name2]); - } else { - return $prefix ? isset($_SESSION[$prefix][$name]) : isset($_SESSION[$name]); - } - } - - /** - * 启动session - * @return void - */ - public static function start() - { - session_start(); - self::$init = true; - } - - /** - * 销毁session - * @return void - */ - public static function destroy() - { - if (!empty($_SESSION)) { - $_SESSION = []; - } - session_unset(); - session_destroy(); - self::$init = null; - } - - /** - * 重新生成session_id - * @param bool $delete 是否删除关联会话文件 - * @return void - */ - private static function regenerate($delete = false) - { - session_regenerate_id($delete); - } - - /** - * 暂停session - * @return void - */ - public static function pause() - { - // 暂停session - session_write_close(); - self::$init = false; - } -} + +// +---------------------------------------------------------------------- + +namespace think; + +use think\exception\ClassNotFoundException; + +class Session +{ + /** + * 配置参数 + * @var array + */ + protected $config = []; + + /** + * 前缀 + * @var string + */ + protected $prefix = ''; + + /** + * 是否初始化 + * @var bool + */ + protected $init = null; + + /** + * 锁驱动 + * @var object + */ + protected $lockDriver = null; + + /** + * 锁key + * @var string + */ + protected $sessKey = 'PHPSESSID'; + + /** + * 锁超时时间 + * @var integer + */ + protected $lockTimeout = 3; + + /** + * 是否启用锁机制 + * @var bool + */ + protected $lock = false; + + public function __construct(array $config = []) + { + $this->config = $config; + } + + /** + * 设置或者获取session作用域(前缀) + * @access public + * @param string $prefix + * @return string|void + */ + public function prefix($prefix = '') + { + empty($this->init) && $this->boot(); + + if (empty($prefix) && null !== $prefix) { + return $this->prefix; + } else { + $this->prefix = $prefix; + } + } + + public static function __make(Config $config) + { + return new static($config->pull('session')); + } + + /** + * 配置 + * @access public + * @param array $config + * @return void + */ + public function setConfig(array $config = []) + { + $this->config = array_merge($this->config, array_change_key_case($config)); + + if (isset($config['prefix'])) { + $this->prefix = $config['prefix']; + } + + if (isset($config['use_lock'])) { + $this->lock = $config['use_lock']; + } + } + + /** + * session初始化 + * @access public + * @param array $config + * @return void + * @throws \think\Exception + */ + public function init(array $config = []) + { + $config = $config ?: $this->config; + + $isDoStart = false; + if (isset($config['use_trans_sid'])) { + ini_set('session.use_trans_sid', $config['use_trans_sid'] ? 1 : 0); + } + + // 启动session + if (!empty($config['auto_start']) && PHP_SESSION_ACTIVE != session_status()) { + ini_set('session.auto_start', 0); + $isDoStart = true; + } + + if (isset($config['prefix'])) { + $this->prefix = $config['prefix']; + } + + if (isset($config['use_lock'])) { + $this->lock = $config['use_lock']; + } + + if (isset($config['var_session_id']) && isset($_REQUEST[$config['var_session_id']])) { + session_id($_REQUEST[$config['var_session_id']]); + } elseif (isset($config['id']) && !empty($config['id'])) { + session_id($config['id']); + } + + if (isset($config['name'])) { + session_name($config['name']); + } + + if (isset($config['path'])) { + session_save_path($config['path']); + } + + if (isset($config['domain'])) { + ini_set('session.cookie_domain', $config['domain']); + } + + if (isset($config['expire'])) { + ini_set('session.gc_maxlifetime', $config['expire']); + ini_set('session.cookie_lifetime', $config['expire']); + } + + if (isset($config['secure'])) { + ini_set('session.cookie_secure', $config['secure']); + } + + if (isset($config['httponly'])) { + ini_set('session.cookie_httponly', $config['httponly']); + } + + if (isset($config['use_cookies'])) { + ini_set('session.use_cookies', $config['use_cookies'] ? 1 : 0); + } + + if (isset($config['cache_limiter'])) { + session_cache_limiter($config['cache_limiter']); + } + + if (isset($config['cache_expire'])) { + session_cache_expire($config['cache_expire']); + } + + if (!empty($config['type'])) { + // 读取session驱动 + $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\session\\driver\\' . ucwords($config['type']); + + // 检查驱动类 + if (!class_exists($class) || !session_set_save_handler(new $class($config))) { + throw new ClassNotFoundException('error session handler:' . $class, $class); + } + } + + if ($isDoStart) { + session_start(); + $this->init = true; + } else { + $this->init = false; + } + + return $this; + } + + /** + * session自动启动或者初始化 + * @access public + * @return void + */ + public function boot() + { + if (is_null($this->init)) { + $this->init(); + } + + if (false === $this->init) { + if (PHP_SESSION_ACTIVE != session_status()) { + session_start(); + } + $this->init = true; + } + } + + /** + * session设置 + * @access public + * @param string $name session名称 + * @param mixed $value session值 + * @param string|null $prefix 作用域(前缀) + * @return void + */ + public function set($name, $value, $prefix = null) + { + $this->lock(); + + empty($this->init) && $this->boot(); + + $prefix = !is_null($prefix) ? $prefix : $this->prefix; + + if (strpos($name, '.')) { + // 二维数组赋值 + list($name1, $name2) = explode('.', $name); + if ($prefix) { + $_SESSION[$prefix][$name1][$name2] = $value; + } else { + $_SESSION[$name1][$name2] = $value; + } + } elseif ($prefix) { + $_SESSION[$prefix][$name] = $value; + } else { + $_SESSION[$name] = $value; + } + + $this->unlock(); + } + + /** + * session获取 + * @access public + * @param string $name session名称 + * @param string|null $prefix 作用域(前缀) + * @return mixed + */ + public function get($name = '', $prefix = null) + { + $this->lock(); + + empty($this->init) && $this->boot(); + + $prefix = !is_null($prefix) ? $prefix : $this->prefix; + + $value = $prefix ? (!empty($_SESSION[$prefix]) ? $_SESSION[$prefix] : []) : $_SESSION; + + if ('' != $name) { + $name = explode('.', $name); + + foreach ($name as $val) { + if (isset($value[$val])) { + $value = $value[$val]; + } else { + $value = null; + break; + } + } + } + + $this->unlock(); + + return $value; + } + + /** + * session 读写锁驱动实例化 + */ + protected function initDriver() + { + $config = $this->config; + + if (!empty($config['type']) && isset($config['use_lock']) && $config['use_lock']) { + // 读取session驱动 + $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\session\\driver\\' . ucwords($config['type']); + + // 检查驱动类及类中是否存在 lock 和 unlock 函数 + if (class_exists($class) && method_exists($class, 'lock') && method_exists($class, 'unlock')) { + $this->lockDriver = new $class($config); + } + } + + // 通过cookie获得session_id + if (isset($config['name']) && $config['name']) { + $this->sessKey = $config['name']; + } + + if (isset($config['lock_timeout']) && $config['lock_timeout'] > 0) { + $this->lockTimeout = $config['lock_timeout']; + } + } + + /** + * session 读写加锁 + * @access protected + * @return void + */ + protected function lock() + { + if (empty($this->lock)) { + return; + } + + $this->initDriver(); + + if (null !== $this->lockDriver && method_exists($this->lockDriver, 'lock')) { + $t = time(); + // 使用 session_id 作为互斥条件,即只对同一 session_id 的会话互斥。第一次请求没有 session_id + $sessID = isset($_COOKIE[$this->sessKey]) ? $_COOKIE[$this->sessKey] : ''; + + do { + if (time() - $t > $this->lockTimeout) { + $this->unlock(); + } + } while (!$this->lockDriver->lock($sessID, $this->lockTimeout)); + } + } + + /** + * session 读写解锁 + * @access protected + * @return void + */ + protected function unlock() + { + if (empty($this->lock)) { + return; + } + + $this->pause(); + + if ($this->lockDriver && method_exists($this->lockDriver, 'unlock')) { + $sessID = isset($_COOKIE[$this->sessKey]) ? $_COOKIE[$this->sessKey] : ''; + $this->lockDriver->unlock($sessID); + } + } + + /** + * session获取并删除 + * @access public + * @param string $name session名称 + * @param string|null $prefix 作用域(前缀) + * @return mixed + */ + public function pull($name, $prefix = null) + { + $result = $this->get($name, $prefix); + + if ($result) { + $this->delete($name, $prefix); + return $result; + } else { + return; + } + } + + /** + * session设置 下一次请求有效 + * @access public + * @param string $name session名称 + * @param mixed $value session值 + * @param string|null $prefix 作用域(前缀) + * @return void + */ + public function flash($name, $value) + { + $this->set($name, $value); + + if (!$this->has('__flash__.__time__')) { + $this->set('__flash__.__time__', $_SERVER['REQUEST_TIME_FLOAT']); + } + + $this->push('__flash__', $name); + } + + /** + * 清空当前请求的session数据 + * @access public + * @return void + */ + public function flush() + { + if (!$this->init) { + return; + } + + $item = $this->get('__flash__'); + + if (!empty($item)) { + $time = $item['__time__']; + + if ($_SERVER['REQUEST_TIME_FLOAT'] > $time) { + unset($item['__time__']); + $this->delete($item); + $this->set('__flash__', []); + } + } + } + + /** + * 删除session数据 + * @access public + * @param string|array $name session名称 + * @param string|null $prefix 作用域(前缀) + * @return void + */ + public function delete($name, $prefix = null) + { + empty($this->init) && $this->boot(); + + $prefix = !is_null($prefix) ? $prefix : $this->prefix; + + if (is_array($name)) { + foreach ($name as $key) { + $this->delete($key, $prefix); + } + } elseif (strpos($name, '.')) { + list($name1, $name2) = explode('.', $name); + if ($prefix) { + unset($_SESSION[$prefix][$name1][$name2]); + } else { + unset($_SESSION[$name1][$name2]); + } + } else { + if ($prefix) { + unset($_SESSION[$prefix][$name]); + } else { + unset($_SESSION[$name]); + } + } + } + + /** + * 清空session数据 + * @access public + * @param string|null $prefix 作用域(前缀) + * @return void + */ + public function clear($prefix = null) + { + empty($this->init) && $this->boot(); + $prefix = !is_null($prefix) ? $prefix : $this->prefix; + + if ($prefix) { + unset($_SESSION[$prefix]); + } else { + $_SESSION = []; + } + } + + /** + * 判断session数据 + * @access public + * @param string $name session名称 + * @param string|null $prefix + * @return bool + */ + public function has($name, $prefix = null) + { + empty($this->init) && $this->boot(); + + $prefix = !is_null($prefix) ? $prefix : $this->prefix; + $value = $prefix ? (!empty($_SESSION[$prefix]) ? $_SESSION[$prefix] : []) : $_SESSION; + + $name = explode('.', $name); + + foreach ($name as $val) { + if (!isset($value[$val])) { + return false; + } else { + $value = $value[$val]; + } + } + + return true; + } + + /** + * 添加数据到一个session数组 + * @access public + * @param string $key + * @param mixed $value + * @return void + */ + public function push($key, $value) + { + $array = $this->get($key); + + if (is_null($array)) { + $array = []; + } + + $array[] = $value; + + $this->set($key, $array); + } + + /** + * 启动session + * @access public + * @return void + */ + public function start() + { + session_start(); + + $this->init = true; + } + + /** + * 销毁session + * @access public + * @return void + */ + public function destroy() + { + if (!empty($_SESSION)) { + $_SESSION = []; + } + + session_unset(); + session_destroy(); + + $this->init = null; + $this->lockDriver = null; + } + + /** + * 重新生成session_id + * @access public + * @param bool $delete 是否删除关联会话文件 + * @return void + */ + public function regenerate($delete = false) + { + session_regenerate_id($delete); + } + + /** + * 暂停session + * @access public + * @return void + */ + public function pause() + { + // 暂停session + session_write_close(); + $this->init = false; + } +} diff --git a/library/think/Template.php b/library/think/Template.php index 036b367ebbd4c4188d6143a518fffa66e5e1f4fa..50dad097ed5bc550224c26203a7362f3bd94a464 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -20,13 +20,22 @@ use think\exception\TemplateNotFoundException; */ class Template { - // 模板变量 + protected $app; + /** + * 模板变量 + * @var array + */ protected $data = []; - // 引擎配置 + + /** + * 模板配置参数 + * @var array + */ protected $config = [ 'view_path' => '', // 模板路径 + 'view_base' => '', 'view_suffix' => 'html', // 默认模板文件后缀 - 'view_depr' => DS, + 'view_depr' => DIRECTORY_SEPARATOR, 'cache_suffix' => 'php', // 默认模板缓存后缀 'tpl_deny_func_list' => 'echo,exit', // 模板引擎禁用函数 'tpl_deny_php' => false, // 默认模板引擎是否禁用PHP原生代码 @@ -49,50 +58,62 @@ class Template 'cache_id' => '', // 模板缓存ID 'tpl_replace_string' => [], 'tpl_var_identify' => 'array', // .语法变量识别,array|object|'', 为空时自动识别 + 'default_filter' => 'htmlentities', // 默认过滤方法 用于普通标签输出 ]; - private $literal = []; - private $includeFile = []; // 记录所有模板包含的文件路径及更新时间 + /** + * 保留内容信息 + * @var array + */ + private $literal = []; + + /** + * 模板包含信息 + * @var array + */ + private $includeFile = []; + + /** + * 模板存储对象 + * @var object + */ protected $storage; /** * 架构函数 * @access public + * @param array $config */ - public function __construct(array $config = []) + public function __construct(App $app, array $config = []) { - $this->config['cache_path'] = TEMP_PATH; - $this->config = array_merge($this->config, $config); - $this->config['taglib_begin'] = $this->stripPreg($this->config['taglib_begin']); - $this->config['taglib_end'] = $this->stripPreg($this->config['taglib_end']); - $this->config['tpl_begin'] = $this->stripPreg($this->config['tpl_begin']); - $this->config['tpl_end'] = $this->stripPreg($this->config['tpl_end']); + $this->app = $app; + $this->config['cache_path'] = $app->getRuntimePath() . 'temp/'; + $this->config = array_merge($this->config, $config); + + $this->config['taglib_begin_origin'] = $this->config['taglib_begin']; + $this->config['taglib_end_origin'] = $this->config['taglib_end']; + + $this->config['taglib_begin'] = preg_quote($this->config['taglib_begin'], '/'); + $this->config['taglib_end'] = preg_quote($this->config['taglib_end'], '/'); + $this->config['tpl_begin'] = preg_quote($this->config['tpl_begin'], '/'); + $this->config['tpl_end'] = preg_quote($this->config['tpl_end'], '/'); // 初始化模板编译存储器 - $type = $this->config['compile_type'] ? $this->config['compile_type'] : 'File'; - $class = false !== strpos($type, '\\') ? $type : '\\think\\template\\driver\\' . ucwords($type); - $this->storage = new $class(); + $type = $this->config['compile_type'] ? $this->config['compile_type'] : 'File'; + + $this->storage = Loader::factory($type, '\\think\\template\\driver\\', null); } - /** - * 字符串替换 避免正则混淆 - * @access private - * @param string $str - * @return string - */ - private function stripPreg($str) + public static function __make(Config $config) { - return str_replace( - ['{', '}', '(', ')', '|', '[', ']', '-', '+', '*', '.', '^', '?'], - ['\{', '\}', '\(', '\)', '\|', '\[', '\]', '\-', '\+', '\*', '\.', '\^', '\?'], - $str); + return new static($config->pull('template')); } /** * 模板变量赋值 * @access public - * @param mixed $name - * @param mixed $value + * @param mixed $name + * @param mixed $value * @return void */ public function assign($name, $value = '') @@ -107,8 +128,8 @@ class Template /** * 模板引擎参数赋值 * @access public - * @param mixed $name - * @param mixed $value + * @param mixed $name + * @param mixed $value */ public function __set($name, $value) { @@ -118,7 +139,7 @@ class Template /** * 模板引擎配置项 * @access public - * @param array|string $config + * @param array|string $config * @return void|array */ public function config($config) @@ -127,8 +148,6 @@ class Template $this->config = array_merge($this->config, $config); } elseif (isset($this->config[$config])) { return $this->config[$config]; - } else { - return null; } } @@ -142,26 +161,28 @@ class Template { if ('' == $name) { return $this->data; - } else { - $data = $this->data; - foreach (explode('.', $name) as $key => $val) { - if (isset($data[$val])) { - $data = $data[$val]; - } else { - $data = null; - break; - } + } + + $data = $this->data; + + foreach (explode('.', $name) as $key => $val) { + if (isset($data[$val])) { + $data = $data[$val]; + } else { + $data = null; + break; } - return $data; } + + return $data; } /** * 渲染模板文件 * @access public - * @param string $template 模板文件 - * @param array $vars 模板变量 - * @param array $config 模板参数 + * @param string $template 模板文件 + * @param array $vars 模板变量 + * @param array $config 模板参数 * @return void */ public function fetch($template, $vars = [], $config = []) @@ -169,36 +190,49 @@ class Template if ($vars) { $this->data = $vars; } + if ($config) { $this->config($config); } + + $cache = $this->app['cache']; + if (!empty($this->config['cache_id']) && $this->config['display_cache']) { // 读取渲染缓存 - $cacheContent = Cache::get($this->config['cache_id']); + $cacheContent = $cache->get($this->config['cache_id']); + if (false !== $cacheContent) { echo $cacheContent; return; } } + $template = $this->parseTemplateFile($template); + if ($template) { - $cacheFile = $this->config['cache_path'] . $this->config['cache_prefix'] . md5($template) . '.' . ltrim($this->config['cache_suffix'], '.'); + $cacheFile = $this->config['cache_path'] . $this->config['cache_prefix'] . md5($this->config['layout_on'] . $this->config['layout_name'] . $template) . '.' . ltrim($this->config['cache_suffix'], '.'); + if (!$this->checkCache($cacheFile)) { // 缓存无效 重新模板编译 $content = file_get_contents($template); $this->compiler($content, $cacheFile); } + // 页面缓存 ob_start(); ob_implicit_flush(0); + // 读取编译存储 $this->storage->read($cacheFile, $this->data); + // 获取并清空缓存 $content = ob_get_clean(); + if (!empty($this->config['cache_id']) && $this->config['display_cache']) { // 缓存页面输出 - Cache::set($this->config['cache_id'], $content, $this->config['cache_time']); + $cache->set($this->config['cache_id'], $content, $this->config['cache_time']); } + echo $content; } } @@ -206,9 +240,9 @@ class Template /** * 渲染模板内容 * @access public - * @param string $content 模板内容 - * @param array $vars 模板变量 - * @param array $config 模板参数 + * @param string $content 模板内容 + * @param array $vars 模板变量 + * @param array $config 模板参数 * @return void */ public function display($content, $vars = [], $config = []) @@ -216,14 +250,18 @@ class Template if ($vars) { $this->data = $vars; } + if ($config) { $this->config($config); } + $cacheFile = $this->config['cache_path'] . $this->config['cache_prefix'] . md5($content) . '.' . ltrim($this->config['cache_suffix'], '.'); + if (!$this->checkCache($cacheFile)) { // 缓存无效 模板编译 $this->compiler($content, $cacheFile); } + // 读取编译存储 $this->storage->read($cacheFile, $this->data); } @@ -231,8 +269,8 @@ class Template /** * 设置布局 * @access public - * @param mixed $name 布局模板名称 false 则关闭布局 - * @param string $replace 布局模板内容替换标识 + * @param mixed $name 布局模板名称 false 则关闭布局 + * @param string $replace 布局模板内容替换标识 * @return object */ public function layout($name, $replace = '') @@ -243,14 +281,17 @@ class Template } else { // 开启布局 $this->config['layout_on'] = true; + // 名称必须为字符串 if (is_string($name)) { $this->config['layout_name'] = $name; } + if (!empty($replace)) { $this->config['layout_item'] = $replace; } } + return $this; } @@ -258,32 +299,28 @@ class Template * 检查编译缓存是否有效 * 如果无效则需要重新编译 * @access private - * @param string $cacheFile 缓存文件名 + * @param string $cacheFile 缓存文件名 * @return boolean */ private function checkCache($cacheFile) { - // 未开启缓存功能 - if (!$this->config['tpl_cache']) { - return false; - } - // 缓存文件不存在 - if (!is_file($cacheFile)) { - return false; - } - // 读取缓存文件失败 - if (!$handle = @fopen($cacheFile, "r")) { + if (!$this->config['tpl_cache'] || !is_file($cacheFile) || !$handle = @fopen($cacheFile, "r")) { return false; } + // 读取第一行 preg_match('/\/\*(.+?)\*\//', fgets($handle), $matches); + if (!isset($matches[1])) { return false; } + $includeFile = unserialize($matches[1]); + if (!is_array($includeFile)) { return false; } + // 检查模板文件是否有更新 foreach ($includeFile as $path => $time) { if (is_file($path) && filemtime($path) > $time) { @@ -291,6 +328,7 @@ class Template return false; } } + // 检查编译存储是否有效 return $this->storage->check($cacheFile, $this->config['cache_time']); } @@ -298,23 +336,24 @@ class Template /** * 检查编译缓存是否存在 * @access public - * @param string $cacheId 缓存的id + * @param string $cacheId 缓存的id * @return boolean */ public function isCache($cacheId) { if ($cacheId && $this->config['display_cache']) { // 缓存页面输出 - return Cache::has($cacheId); + return $this->app['cache']->has($cacheId); } + return false; } /** * 编译模板文件内容 * @access private - * @param string $content 模板内容 - * @param string $cacheFile 缓存文件名 + * @param string $content 模板内容 + * @param string $cacheFile 缓存文件名 * @return void */ private function compiler(&$content, $cacheFile) @@ -327,6 +366,7 @@ class Template } else { // 读取布局模板 $layoutFile = $this->parseTemplateFile($this->config['layout_name']); + if ($layoutFile) { // 替换布局的主体内容 $content = str_replace($this->config['layout_item'], $content, file_get_contents($layoutFile)); @@ -338,30 +378,34 @@ class Template // 模板解析 $this->parse($content); + if ($this->config['strip_space']) { /* 去除html空格与换行 */ $find = ['~>\s+<~', '~>(\s+\n|\r)~']; $replace = ['><', '>']; $content = preg_replace($find, $replace, $content); } + // 优化生成的php代码 $content = preg_replace('/\?>\s*<\?php\s(?!echo\b)/s', '', $content); + // 模板过滤输出 $replace = $this->config['tpl_replace_string']; $content = str_replace(array_keys($replace), array_values($replace), $content); + // 添加安全代码及模板引用记录 - $content = 'includeFile) . '*/ ?>' . "\n" . $content; + $content = 'includeFile) . '*/ ?>' . "\n" . $content; // 编译存储 $this->storage->write($cacheFile, $content); + $this->includeFile = []; - return; } /** * 模板解析入口 * 支持普通标签和TagLib解析 支持自定义标签库 * @access public - * @param string $content 要解析的模板内容 + * @param string $content 要解析的模板内容 * @return void */ public function parse(&$content) @@ -370,16 +414,22 @@ class Template if (empty($content)) { return; } + // 替换literal标签内容 $this->parseLiteral($content); + // 解析继承 $this->parseExtend($content); + // 解析布局 $this->parseLayout($content); + // 检查include语法 $this->parseInclude($content); + // 替换包含文件中literal标签内容 $this->parseLiteral($content); + // 检查PHP语法 $this->parsePhp($content); @@ -390,6 +440,7 @@ class Template // 当TAGLIB_LOAD配置为true时才会进行检测 if ($this->config['taglib_load']) { $tagLibs = $this->getIncludeTagLib($content); + if (!empty($tagLibs)) { // 对导入的TagLib进行解析 foreach ($tagLibs as $tagLibName) { @@ -397,30 +448,34 @@ class Template } } } + // 预先加载的标签库 无需在每个模板中使用taglib标签加载 但必须使用标签库XML前缀 if ($this->config['taglib_pre_load']) { $tagLibs = explode(',', $this->config['taglib_pre_load']); + foreach ($tagLibs as $tag) { $this->parseTagLib($tag, $content); } } + // 内置标签库 无需使用taglib标签导入就可以使用 并且不需使用标签库XML前缀 $tagLibs = explode(',', $this->config['taglib_build_in']); + foreach ($tagLibs as $tag) { $this->parseTagLib($tag, $content, true); } + // 解析普通模板标签 {$tagName} $this->parseTag($content); // 还原被替换的Literal标签 $this->parseLiteral($content, true); - return; } /** * 检查PHP语法 * @access private - * @param string $content 要解析的模板内容 + * @param string $content 要解析的模板内容 * @return void * @throws \think\Exception */ @@ -428,17 +483,17 @@ class Template { // 短标签的情况要将' . "\n", $content); + // PHP语法检查 if ($this->config['tpl_deny_php'] && false !== strpos($content, 'parseAttr($matches[0]); + if (!$this->config['layout_on'] || $this->config['layout_name'] != $array['name']) { // 读取布局模板 $layoutFile = $this->parseTemplateFile($array['name']); + if ($layoutFile) { $replace = isset($array['replace']) ? $array['replace'] : $this->config['layout_item']; // 替换布局的主体内容 @@ -461,7 +518,6 @@ class Template } else { $content = str_replace('{__NOLAYOUT__}', '', $content); } - return; } /** @@ -479,15 +535,19 @@ class Template $array = $this->parseAttr($match[0]); $file = $array['file']; unset($array['file']); + // 分析模板文件名并读取内容 $parseStr = $this->parseTemplateName($file); + foreach ($array as $k => $v) { // 以$开头字符串转换成模板变量 if (0 === strpos($v, '$')) { $v = $this->get(substr($v, 1)); } + $parseStr = str_replace('[' . $k . ']', $v, $parseStr); } + $content = str_replace($match[0], $parseStr, $content); // 再次对包含文件进行模板分析 $func($parseStr); @@ -495,9 +555,9 @@ class Template unset($matches); } }; + // 替换模板中的include标签 $func($content); - return; } /** @@ -511,21 +571,26 @@ class Template $regex = $this->getRegex('extend'); $array = $blocks = $baseBlocks = []; $extend = ''; - $func = function ($template) use (&$func, &$regex, &$array, &$extend, &$blocks, &$baseBlocks) { + + $func = function ($template) use (&$func, &$regex, &$array, &$extend, &$blocks, &$baseBlocks) { if (preg_match($regex, $template, $matches)) { if (!isset($array[$matches['name']])) { $array[$matches['name']] = 1; // 读取继承模板 $extend = $this->parseTemplateName($matches['name']); + // 递归检查继承 $func($extend); + // 取得block标签内容 $blocks = array_merge($blocks, $this->parseBlock($template)); + return; } } else { // 取得顶层模板block标签内容 $baseBlocks = $this->parseBlock($template, true); + if (empty($extend)) { // 无extend标签但有block标签的情况 $extend = $template; @@ -534,28 +599,35 @@ class Template }; $func($content); + if (!empty($extend)) { if ($baseBlocks) { $children = []; foreach ($baseBlocks as $name => $val) { $replace = $val['content']; + if (!empty($children[$name])) { // 如果包含有子block标签 foreach ($children[$name] as $key) { $replace = str_replace($baseBlocks[$key]['begin'] . $baseBlocks[$key]['content'] . $baseBlocks[$key]['end'], $blocks[$key]['content'], $replace); } } + if (isset($blocks[$name])) { // 带有{__block__}表示与所继承模板的相应标签合并,而不是覆盖 $replace = str_replace(['{__BLOCK__}', '{__block__}'], $replace, $blocks[$name]['content']); + if (!empty($val['parent'])) { // 如果不是最顶层的block标签 $parent = $val['parent']; + if (isset($blocks[$parent])) { $blocks[$parent]['content'] = str_replace($blocks[$name]['begin'] . $blocks[$name]['content'] . $blocks[$name]['end'], $replace, $blocks[$parent]['content']); } + $blocks[$name]['content'] = $replace; $children[$parent][] = $name; + continue; } } elseif (!empty($val['parent'])) { @@ -563,16 +635,17 @@ class Template $children[$val['parent']][] = $name; $blocks[$name] = $val; } + if (!$val['parent']) { // 替换模板中的顶级block标签 $extend = str_replace($val['begin'] . $val['content'] . $val['end'], $replace, $extend); } } } + $content = $extend; unset($blocks, $baseBlocks); } - return; } /** @@ -585,9 +658,11 @@ class Template private function parseLiteral(&$content, $restore = false) { $regex = $this->getRegex($restore ? 'restoreliteral' : 'literal'); + if (preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) { if (!$restore) { $count = count($this->literal); + // 替换literal标签 foreach ($matches as $match) { $this->literal[] = substr($match[0], strlen($match[1]), -strlen($match[2])); @@ -599,12 +674,13 @@ class Template foreach ($matches as $match) { $content = str_replace($match[0], $this->literal[$match[1]], $content); } + // 清空literal记录 $this->literal = []; } + unset($matches); } - return; } /** @@ -618,20 +694,24 @@ class Template { $regex = $this->getRegex('block'); $result = []; + if (preg_match_all($regex, $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) { $right = $keys = []; + foreach ($matches as $match) { if (empty($match['name'][0])) { if (count($right) > 0) { - $tag = array_pop($right); - $start = $tag['offset'] + strlen($tag['tag']); - $length = $match[0][1] - $start; + $tag = array_pop($right); + $start = $tag['offset'] + strlen($tag['tag']); + $length = $match[0][1] - $start; + $result[$tag['name']] = [ 'begin' => $tag['tag'], 'content' => substr($content, $start, $length), 'end' => $match[0][0], 'parent' => count($right) ? end($right)['name'] : '', ]; + $keys[$tag['name']] = $match[0][1]; } } else { @@ -643,12 +723,15 @@ class Template ]; } } + unset($right, $matches); + if ($sort) { // 按block标签结束符在模板中的位置排序 array_multisort($keys, $result); } } + return $result; } @@ -665,9 +748,9 @@ class Template if (preg_match($this->getRegex('taglib'), $content, $matches)) { // 替换TagLib标签 $content = str_replace($matches[0], '', $content); + return explode(',', $matches['name']); } - return null; } /** @@ -687,9 +770,10 @@ class Template } else { $className = '\\think\\template\\taglib\\' . ucwords($tagLib); } + $tLib = new $className($this); + $tLib->parseTag($content, $hide ? '' : $tagLib); - return; } /** @@ -703,17 +787,19 @@ class Template { $regex = '/\s+(?>(?P[\w-]+)\s*)=(?>\s*)([\"\'])(?P(?:(?!\\2).)*)\\2/is'; $array = []; + if (preg_match_all($regex, $str, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $array[$match['name']] = $match['value']; } unset($matches); } + if (!empty($name) && isset($array[$name])) { return $array[$name]; - } else { - return $array; } + + return $array; } /** @@ -726,10 +812,12 @@ class Template private function parseTag(&$content) { $regex = $this->getRegex('tag'); + if (preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $str = stripslashes($match[1]); $flag = substr($str, 0, 1); + switch ($flag) { case '$': // 解析模板变量 格式 {$varName} @@ -737,20 +825,24 @@ class Template if (false !== $pos = strpos($str, '?')) { $array = preg_split('/([!=]={1,2}|(?<]={0,1})/', substr($str, 0, $pos), 2, PREG_SPLIT_DELIM_CAPTURE); $name = $array[0]; + $this->parseVar($name); - $this->parseVarFunction($name); + //$this->parseVarFunction($name); $str = trim(substr($str, $pos + 1)); $this->parseVar($str); $first = substr($str, 0, 1); + if (strpos($name, ')')) { // $name为对象或是自动识别,或者含有函数 if (isset($array[1])) { $this->parseVar($array[2]); $name .= $array[1] . $array[2]; } + switch ($first) { case '?': + $this->parseVarFunction($name); $str = ''; break; case '=': @@ -761,32 +853,45 @@ class Template } } else { if (isset($array[1])) { + $express = true; $this->parseVar($array[2]); - $_name = ' && ' . $name . $array[1] . $array[2]; + $express = $name . $array[1] . $array[2]; } else { - $_name = ''; + $express = false; + } + + if (in_array($first, ['?', '=', ':'])) { + $str = trim(substr($str, 1)); + if ('$' == substr($str, 0, 1)) { + $str = $this->parseVarFunction($str); + } } + // $name为数组 switch ($first) { case '?': // {$varname??'xxx'} $varname有定义则输出$varname,否则输出xxx - $str = ''; + $str = 'parseVarFunction($name) . ' : ' . $str . '; ?>'; break; case '=': // {$varname?='xxx'} $varname为真时才输出xxx - $str = ''; + $str = ''; break; case ':': // {$varname?:'xxx'} $varname为真时输出$varname,否则输出xxx - $str = ''; + $str = 'parseVarFunction($name) . ' : ' . $str . '; ?>'; break; default: if (strpos($str, ':')) { // {$varname ? 'a' : 'b'} $varname为真时输出a,否则输出b - $str = ''; - } else { - $str = ''; + $array = explode(':', $str, 2); + + $array[0] = '$' == substr(trim($array[0]), 0, 1) ? $this->parseVarFunction($array[0]) : $array[0]; + $array[1] = '$' == substr(trim($array[1]), 0, 1) ? $this->parseVarFunction($array[1]) : $array[1]; + + $str = implode(' : ', $array); } + $str = ''; } } } else { @@ -825,11 +930,12 @@ class Template $str = $this->config['tpl_begin'] . $str . $this->config['tpl_end']; break; } + $content = str_replace($match[0], $str, $content); } + unset($matches); } - return; } /** @@ -842,10 +948,13 @@ class Template public function parseVar(&$varStr) { $varStr = trim($varStr); + if (preg_match_all('/\$[a-zA-Z_](?>\w*)(?:[:\.][0-9a-zA-Z_](?>\w*))+/', $varStr, $matches, PREG_OFFSET_CAPTURE)) { static $_varParseList = []; + while ($matches[0]) { $match = array_pop($matches[0]); + //如果已经解析过该变量字串,则直接返回变量值 if (isset($_varParseList[$match[0]])) { $parseStr = $_varParseList[$match[0]]; @@ -853,6 +962,7 @@ class Template if (strpos($match[0], '.')) { $vars = explode('.', $match[0]); $first = array_shift($vars); + if ('$Think' == $first) { // 所有以Think.打头的以特殊变量对待 无需模板赋值就可以输出 $parseStr = $this->parseThinkVar($vars); @@ -867,7 +977,8 @@ class Template } else { $params = ''; } - $parseStr = '\think\Request::instance()->' . $method . '(' . $params . ')'; + + $parseStr = 'app(\'request\')->' . $method . '(' . $params . ')'; } else { switch ($this->config['tpl_var_identify']) { case 'array': // 识别为数组 @@ -883,73 +994,108 @@ class Template } else { $parseStr = str_replace(':', '->', $match[0]); } + $_varParseList[$match[0]] = $parseStr; } + $varStr = substr_replace($varStr, $parseStr, $match[1], strlen($match[0])); } unset($matches); } - return; } /** * 对模板中使用了函数的变量进行解析 * 格式 {$varname|function1|function2=arg1,arg2} * @access public - * @param string $varStr 变量字符串 + * @param string $varStr 变量字符串 + * @param bool $autoescape 自动转义 * @return void */ - public function parseVarFunction(&$varStr) + public function parseVarFunction(&$varStr, $autoescape = true) { - if (false == strpos($varStr, '|')) { - return; + if (!$autoescape && false === strpos($varStr, '|')) { + return $varStr; + } elseif ($autoescape && !preg_match('/\|(\s)?raw(\||\s)?/i', $varStr)) { + $varStr .= '|' . $this->config['default_filter']; } + static $_varFunctionList = []; - $_key = md5($varStr); + + $_key = md5($varStr); + //如果已经解析过该变量字串,则直接返回变量值 if (isset($_varFunctionList[$_key])) { $varStr = $_varFunctionList[$_key]; } else { $varArray = explode('|', $varStr); + // 取得变量名称 - $name = array_shift($varArray); + $name = trim(array_shift($varArray)); + // 对变量使用函数 $length = count($varArray); + // 取得模板禁止使用函数列表 $template_deny_funs = explode(',', $this->config['tpl_deny_func_list']); + for ($i = 0; $i < $length; $i++) { $args = explode('=', $varArray[$i], 2); + // 模板函数过滤 $fun = trim($args[0]); - switch ($fun) { + if (in_array($fun, $template_deny_funs)) { + continue; + } + + switch (strtolower($fun)) { + case 'raw': + continue; + case 'date': + $name = 'date(' . $args[1] . ',!is_numeric(' . $name . ')? strtotime(' . $name . ') : ' . $name . ')'; + break; + case 'first': + $name = 'current(' . $name . ')'; + break; + case 'last': + $name = 'end(' . $name . ')'; + break; + case 'upper': + $name = 'strtoupper(' . $name . ')'; + break; + case 'lower': + $name = 'strtolower(' . $name . ')'; + break; + case 'format': + $name = 'sprintf(' . $args[1] . ',' . $name . ')'; + break; case 'default': // 特殊模板函数 if (false === strpos($name, '(')) { $name = '(isset(' . $name . ') && (' . $name . ' !== \'\')?' . $name . ':' . $args[1] . ')'; } else { - $name = '(' . $name . ' !== \'\'?' . $name . ':' . $args[1] . ')'; + $name = '(' . $name . ' ?: ' . $args[1] . ')'; } break; default: // 通用模板函数 - if (!in_array($fun, $template_deny_funs)) { - if (isset($args[1])) { - if (strstr($args[1], '###')) { - $args[1] = str_replace('###', $name, $args[1]); - $name = "$fun($args[1])"; - } else { - $name = "$fun($name,$args[1])"; - } + if (isset($args[1])) { + if (strstr($args[1], '###')) { + $args[1] = str_replace('###', $name, $args[1]); + $name = "$fun($args[1])"; } else { - if (!empty($args[0])) { - $name = "$fun($name)"; - } + $name = "$fun($name,$args[1])"; + } + } else { + if (!empty($args[0])) { + $name = "$fun($name)"; } } } } + $_varFunctionList[$_key] = $name; $varStr = $name; } - return; + return $varStr; } /** @@ -959,80 +1105,70 @@ class Template * @param array $vars 变量数组 * @return string */ - public function parseThinkVar(&$vars) + public function parseThinkVar($vars) { - $vars[0] = strtoupper(trim($vars[0])); - $parseStr = ''; - if (count($vars) >= 2) { - $vars[1] = trim($vars[1]); - switch ($vars[0]) { + $type = strtoupper(trim(array_shift($vars))); + $param = implode('.', $vars); + + if ($vars) { + switch ($type) { case 'SERVER': - $parseStr = '$_SERVER[\'' . strtoupper($vars[1]) . '\']'; + $parseStr = 'app(\'request\')->server(\'' . $param . '\')'; break; case 'GET': - $parseStr = '$_GET[\'' . $vars[1] . '\']'; + $parseStr = 'app(\'request\')->get(\'' . $param . '\')'; break; case 'POST': - $parseStr = '$_POST[\'' . $vars[1] . '\']'; + $parseStr = 'app(\'request\')->post(\'' . $param . '\')'; break; case 'COOKIE': - if (isset($vars[2])) { - $parseStr = '\\think\\Cookie::get(\'' . $vars[1] . '.' . $vars[2] . '\')'; - } else { - $parseStr = '\\think\\Cookie::get(\'' . $vars[1] . '\')'; - } + $parseStr = 'app(\'cookie\')->get(\'' . $param . '\')'; break; case 'SESSION': - if (isset($vars[2])) { - $parseStr = '\\think\\Session::get(\'' . $vars[1] . '.' . $vars[2] . '\')'; - } else { - $parseStr = '\\think\\Session::get(\'' . $vars[1] . '\')'; - } + $parseStr = 'app(\'session\')->get(\'' . $param . '\')'; break; case 'ENV': - $parseStr = '$_ENV[\'' . strtoupper($vars[1]) . '\']'; + $parseStr = 'app(\'request\')->env(\'' . $param . '\')'; break; case 'REQUEST': - $parseStr = '$_REQUEST[\'' . $vars[1] . '\']'; + $parseStr = 'app(\'request\')->request(\'' . $param . '\')'; break; case 'CONST': - $parseStr = strtoupper($vars[1]); + $parseStr = strtoupper($param); break; case 'LANG': - $parseStr = '\\think\\Lang::get(\'' . $vars[1] . '\')'; + $parseStr = 'app(\'lang\')->get(\'' . $param . '\')'; break; case 'CONFIG': - if (isset($vars[2])) { - $vars[1] .= '.' . $vars[2]; - } - $parseStr = '\\think\\Config::get(\'' . $vars[1] . '\')'; + $parseStr = 'app(\'config\')->get(\'' . $param . '\')'; break; default: $parseStr = '\'\''; break; } } else { - if (count($vars) == 1) { - switch ($vars[0]) { - case 'NOW': - $parseStr = "date('Y-m-d g:i a',time())"; - break; - case 'VERSION': - $parseStr = 'THINK_VERSION'; - break; - case 'LDELIM': - $parseStr = '\'' . ltrim($this->config['tpl_begin'], '\\') . '\''; - break; - case 'RDELIM': - $parseStr = '\'' . ltrim($this->config['tpl_end'], '\\') . '\''; - break; - default: - if (defined($vars[0])) { - $parseStr = $vars[0]; - } - } + switch ($type) { + case 'NOW': + $parseStr = "date('Y-m-d g:i a',time())"; + break; + case 'VERSION': + $parseStr = 'app()->version()'; + break; + case 'LDELIM': + $parseStr = '\'' . ltrim($this->config['tpl_begin'], '\\') . '\''; + break; + case 'RDELIM': + $parseStr = '\'' . ltrim($this->config['tpl_end'], '\\') . '\''; + break; + default: + if (defined($type)) { + $parseStr = $type; + } else { + $parseStr = ''; + } } } + return $parseStr; } @@ -1046,20 +1182,25 @@ class Template { $array = explode(',', $templateName); $parseStr = ''; + foreach ($array as $templateName) { if (empty($templateName)) { continue; } + if (0 === strpos($templateName, '$')) { //支持加载变量文件名 $templateName = $this->get(substr($templateName, 1)); } + $template = $this->parseTemplateFile($templateName); + if ($template) { // 获取模板文件内容 $parseStr .= file_get_contents($template); } } + return $parseStr; } @@ -1073,23 +1214,33 @@ class Template { if ('' == pathinfo($template, PATHINFO_EXTENSION)) { if (strpos($template, '@')) { - // 跨模块调用模板 + list($module, $template) = explode('@', $template); + } + + if (0 !== strpos($template, '/')) { $template = str_replace(['/', ':'], $this->config['view_depr'], $template); - $template = APP_PATH . str_replace('@', '/' . basename($this->config['view_path']) . '/', $template); } else { - $template = str_replace(['/', ':'], $this->config['view_depr'], $template); - $template = $this->config['view_path'] . $template; + $template = str_replace(['/', ':'], $this->config['view_depr'], substr($template, 1)); + } + + if ($this->config['view_base']) { + $module = isset($module) ? $module : $this->app['request']->module(); + $path = $this->config['view_base'] . ($module ? $module . DIRECTORY_SEPARATOR : ''); + } else { + $path = isset($module) ? $this->app->getAppPath() . $module . DIRECTORY_SEPARATOR . basename($this->config['view_path']) . DIRECTORY_SEPARATOR : $this->config['view_path']; } - $template .= '.' . ltrim($this->config['view_suffix'], '.'); + + $template = $path . $template . '.' . ltrim($this->config['view_suffix'], '.'); } if (is_file($template)) { // 记录模板文件的更新时间 $this->includeFile[$template] = filemtime($template); + return $template; - } else { - throw new TemplateNotFoundException('template not exists:' . $template, $template); } + + throw new TemplateNotFoundException('template not exists:' . $template, $template); } /** @@ -1104,6 +1255,7 @@ class Template if ('tag' == $tagName) { $begin = $this->config['tpl_begin']; $end = $this->config['tpl_end']; + if (strlen(ltrim($begin, '\\')) == 1 && strlen(ltrim($end, '\\')) == 1) { $regex = $begin . '((?:[\$]{1,2}[a-wA-w_]|[\:\~][\$a-wA-w_]|[+]{2}[\$][a-wA-w_]|[-]{2}[\$][a-wA-w_]|\/[\*\/])(?>[^' . $end . ']*))' . $end; } else { @@ -1113,6 +1265,7 @@ class Template $begin = $this->config['taglib_begin']; $end = $this->config['taglib_end']; $single = strlen(ltrim($begin, '\\')) == 1 && strlen(ltrim($end, '\\')) == 1 ? true : false; + switch ($tagName) { case 'block': if ($single) { @@ -1151,6 +1304,7 @@ class Template break; } } + return '/' . $regex . '/is'; } } diff --git a/library/think/Url.php b/library/think/Url.php index 4e1457026a087e09dfcd656c6e060589b39cb7bc..aa27b3e603add86ded335f84af37ba30fe789d96 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,51 +11,98 @@ namespace think; -use think\Config; -use think\Loader; -use think\Request; -use think\Route; - class Url { - // 生成URL地址的root - protected static $root; + /** + * 配置参数 + * @var array + */ + protected $config = []; + + /** + * ROOT地址 + * @var string + */ + protected $root; + + /** + * 绑定检查 + * @var bool + */ + protected $bindCheck; + + /** + * 应用对象 + * @var App + */ + protected $app; + + public function __construct(App $app, array $config = []) + { + $this->app = $app; + $this->config = $config; + + if (is_file($app->getRuntimePath() . 'route.php')) { + // 读取路由映射文件 + $app['route']->setName(include $app->getRuntimePath() . 'route.php'); + } + } + + /** + * 初始化 + * @access public + * @param array $config + * @return void + */ + public function init(array $config = []) + { + $this->config = array_merge($this->config, array_change_key_case($config)); + } + + public static function __make(App $app, Config $config) + { + return new static($app, $config->pull('app')); + } /** * URL生成 支持路由反射 - * @param string $url 路由地址 - * @param string|array $vars 参数(支持数组和字符串)a=val&b=val2... ['a'=>'val1', 'b'=>'val2'] - * @param string|bool $suffix 伪静态后缀,默认为true表示获取配置值 - * @param boolean|string $domain 是否显示域名 或者直接传入域名 + * @access public + * @param string $url 路由地址 + * @param string|array $vars 参数(支持数组和字符串)a=val&b=val2... ['a'=>'val1', 'b'=>'val2'] + * @param string|bool $suffix 伪静态后缀,默认为true表示获取配置值 + * @param boolean|string $domain 是否显示域名 或者直接传入域名 * @return string */ - public static function build($url = '', $vars = '', $suffix = true, $domain = false) + public function build($url = '', $vars = '', $suffix = true, $domain = false) { - if (false === $domain && Config::get('url_domain_deploy')) { - $domain = true; - } // 解析URL if (0 === strpos($url, '[') && $pos = strpos($url, ']')) { // [name] 表示使用路由命名标识生成URL $name = substr($url, 1, $pos - 1); $url = 'name' . substr($url, $pos + 1); } - $info = parse_url($url); - $url = !empty($info['path']) ? $info['path'] : ''; - if (isset($info['fragment'])) { - // 解析锚点 - $anchor = $info['fragment']; - if (false !== strpos($anchor, '?')) { - // 解析参数 - list($anchor, $info['query']) = explode('?', $anchor, 2); - } - if (false !== strpos($anchor, '@')) { + + if (false === strpos($url, '://') && 0 !== strpos($url, '/')) { + $info = parse_url($url); + $url = !empty($info['path']) ? $info['path'] : ''; + + if (isset($info['fragment'])) { + // 解析锚点 + $anchor = $info['fragment']; + + if (false !== strpos($anchor, '?')) { + // 解析参数 + list($anchor, $info['query']) = explode('?', $anchor, 2); + } + + if (false !== strpos($anchor, '@')) { + // 解析域名 + list($anchor, $domain) = explode('@', $anchor, 2); + } + } elseif (strpos($url, '@') && false === strpos($url, '\\')) { // 解析域名 - list($anchor, $domain) = explode('@', $anchor, 2); + list($url, $domain) = explode('@', $url, 2); } - } elseif (strpos($url, '@')) { - // 解析域名 - list($url, $domain) = explode('@', $url, 2); } // 解析参数 @@ -65,77 +112,140 @@ class Url } if ($url) { - $rule = Route::name(isset($name) ? $name : $url . (isset($info['query']) ? '?' . $info['query'] : '')); + $checkName = isset($name) ? $name : $url . (isset($info['query']) ? '?' . $info['query'] : ''); + $checkDomain = $domain && is_string($domain) ? $domain : null; + + $rule = $this->app['route']->getName($checkName, $checkDomain); + if (is_null($rule) && isset($info['query'])) { - $rule = Route::name($url); + $rule = $this->app['route']->getName($url); // 解析地址里面参数 合并到vars parse_str($info['query'], $params); $vars = array_merge($params, $vars); unset($info['query']); } } - if (!empty($rule) && $match = self::getRuleUrl($rule, $vars)) { + + if (!empty($rule) && $match = $this->getRuleUrl($rule, $vars)) { // 匹配路由命名标识 $url = $match[0]; + if (!empty($match[1])) { - $domain = $match[1]; + $host = $this->config['app_host'] ?: $this->app['request']->host(true); + if ($domain || $match[1] != $host) { + $domain = $match[1]; + } + } + + if (!is_null($match[2])) { + $suffix = $match[2]; } } elseif (!empty($rule) && isset($name)) { throw new \InvalidArgumentException('route name not exists:' . $name); } else { + // 检查别名路由 + $alias = $this->app['route']->getAlias(); + $matchAlias = false; + + if ($alias) { + // 别名路由解析 + foreach ($alias as $key => $item) { + $val = $item->getRoute(); + + if (0 === strpos($url, $val)) { + $url = $key . substr($url, strlen($val)); + $matchAlias = true; + break; + } + } + } + + if (!$matchAlias) { + // 路由标识不存在 直接解析 + $url = $this->parseUrl($url); + } + + // 检测URL绑定 + if (!$this->bindCheck) { + $bind = $this->app['route']->getBind($domain && is_string($domain) ? $domain : null); + + if ($bind && 0 === strpos($url, $bind)) { + $url = substr($url, strlen($bind) + 1); + } else { + $binds = $this->app['route']->getBind(true); + + foreach ($binds as $key => $val) { + if (is_string($val) && 0 === strpos($url, $val) && substr_count($val, '/') > 1) { + $url = substr($url, strlen($val) + 1); + $domain = $key; + break; + } + } + } + } + if (isset($info['query'])) { // 解析地址里面参数 合并到vars parse_str($info['query'], $params); $vars = array_merge($params, $vars); } - // 路由标识不存在 直接解析 - $url = self::parseUrl($url, $domain); } - // 检测URL绑定 - $type = Route::getBind('type'); - if ($type) { - $bind = Route::getBind($type); - if (0 === strpos($url, $bind)) { - $url = substr($url, strlen($bind) + 1); - } - } // 还原URL分隔符 - $depr = Config::get('pathinfo_depr'); + $depr = $this->config['pathinfo_depr']; $url = str_replace('/', $depr, $url); // URL后缀 - $suffix = in_array($url, ['/', '']) ? '' : self::parseSuffix($suffix); + if ('/' == substr($url, -1) || '' == $url) { + $suffix = ''; + } else { + $suffix = $this->parseSuffix($suffix); + } + // 锚点 $anchor = !empty($anchor) ? '#' . $anchor : ''; + // 参数组装 if (!empty($vars)) { // 添加参数 - if (Config::get('url_common_param')) { - $vars = urldecode(http_build_query($vars)); + if ($this->config['url_common_param']) { + $vars = http_build_query($vars); $url .= $suffix . '?' . $vars . $anchor; } else { + $paramType = $this->config['url_param_type']; + foreach ($vars as $var => $val) { if ('' !== trim($val)) { - $url .= $depr . $var . $depr . urlencode($val); + if ($paramType) { + $url .= $depr . urlencode($val); + } else { + $url .= $depr . $var . $depr . urlencode($val); + } } } + $url .= $suffix . $anchor; } } else { $url .= $suffix . $anchor; } + // 检测域名 - $domain = self::parseDomain($url, $domain); + $domain = $this->parseDomain($url, $domain); + // URL组装 - $url = $domain . (self::$root ?: Request::instance()->root()) . '/' . ltrim($url, '/'); + $url = $domain . rtrim($this->root ?: $this->app['request']->root(), '/') . '/' . ltrim($url, '/'); + + $this->bindCheck = false; + return $url; } // 直接解析URL地址 - protected static function parseUrl($url, $domain) + protected function parseUrl($url) { - $request = Request::instance(); + $request = $this->app['request']; + if (0 === strpos($url, '/')) { // 直接作为路由地址解析 $url = substr($url, 1); @@ -147,47 +257,46 @@ class Url $url = substr($url, 1); } else { // 解析到 模块/控制器/操作 - $module = $request->module(); - $domains = Route::rules('domain'); - if (isset($domains[$domain]['[bind]'][0])) { - $bindModule = $domains[$domain]['[bind]'][0]; - if ($bindModule && !in_array($bindModule[0], ['\\', '@'])) { - $module = ''; - } - } else { - $module = $module ? $module . '/' : ''; - } + $module = $request->module(); + $module = $module ? $module . '/' : ''; + $controller = $request->controller(); - $controller = Loader::parseName($request->controller()); if ('' == $url) { - // 空字符串输出当前的 模块/控制器/操作 - $url = $module . $controller . '/' . $request->action(); + $action = $request->action(); } else { $path = explode('/', $url); - $action = Config::get('url_convert') ? strtolower(array_pop($path)) : array_pop($path); - $controller = empty($path) ? $controller : (Config::get('url_convert') ? Loader::parseName(array_pop($path)) : array_pop($path)); + $action = array_pop($path); + $controller = empty($path) ? $controller : array_pop($path); $module = empty($path) ? $module : array_pop($path) . '/'; - $url = $module . $controller . '/' . $action; } + + if ($this->config['url_convert']) { + $action = strtolower($action); + $controller = Loader::parseName($controller); + } + + $url = $module . $controller . '/' . $action; } + return $url; } // 检测域名 - protected static function parseDomain(&$url, $domain) + protected function parseDomain(&$url, $domain) { if (!$domain) { return ''; } - $request = Request::instance(); + + $rootDomain = $this->app['request']->rootDomain(); if (true === $domain) { // 自动判断域名 - $domain = $request->host(); - if (Config::get('url_domain_deploy')) { - // 根域名 - $urlDomainRoot = Config::get('url_domain_root'); - $domains = Route::rules('domain'); - $route_domain = array_keys($domains); + $domain = $this->config['app_host'] ?: $this->app['request']->host(true); + + $domains = $this->app['route']->getDomains(); + + if ($domains) { + $route_domain = array_keys($domains); foreach ($route_domain as $domain_prefix) { if (0 === strpos($domain_prefix, '*.') && strpos($domain, ltrim($domain_prefix, '*.')) !== false) { foreach ($domains as $key => $rule) { @@ -195,15 +304,17 @@ class Url if (is_string($rule) && false === strpos($key, '*') && 0 === strpos($url, $rule)) { $url = ltrim($url, $rule); $domain = $key; + // 生成对应子域名 - if (!empty($urlDomainRoot)) { - $domain .= $urlDomainRoot; + if (!empty($rootDomain)) { + $domain .= $rootDomain; } break; - } else if (false !== strpos($key, '*')) { - if (!empty($urlDomainRoot)) { - $domain .= $urlDomainRoot; + } elseif (false !== strpos($key, '*')) { + if (!empty($rootDomain)) { + $domain .= $rootDomain; } + break; } } @@ -211,59 +322,71 @@ class Url } } } elseif (!strpos($domain, '.')) { - $rootDomain = Config::get('url_domain_root'); - if (empty($rootDomain)) { - $host = $request->host(); - $rootDomain = substr_count($host, '.') > 1 ? substr(strstr($host, '.'), 1) : $host; - } $domain .= '.' . $rootDomain; } - return ($request->isSsl() ? 'https://' : 'http://') . $domain; + + if (false !== strpos($domain, '://')) { + $scheme = ''; + } else { + $scheme = $this->app['request']->isSsl() || $this->config['is_https'] ? 'https://' : 'http://'; + + } + + return $scheme . $domain; } // 解析URL后缀 - protected static function parseSuffix($suffix) + protected function parseSuffix($suffix) { if ($suffix) { - $suffix = true === $suffix ? Config::get('url_html_suffix') : $suffix; + $suffix = true === $suffix ? $this->config['url_html_suffix'] : $suffix; + if ($pos = strpos($suffix, '|')) { $suffix = substr($suffix, 0, $pos); } } + return (empty($suffix) || 0 === strpos($suffix, '.')) ? $suffix : '.' . $suffix; } // 匹配路由地址 - public static function getRuleUrl($rule, &$vars = []) + public function getRuleUrl($rule, &$vars = []) { foreach ($rule as $item) { - list($url, $pattern, $domain) = $item; + list($url, $pattern, $domain, $suffix) = $item; if (empty($pattern)) { - return [$url, $domain]; + return [rtrim($url, '?/-'), $domain, $suffix]; } + + $type = $this->config['url_common_param']; + foreach ($pattern as $key => $val) { if (isset($vars[$key])) { - $url = str_replace(['[:' . $key . ']', '<' . $key . '?>', ':' . $key . '', '<' . $key . '>'], $vars[$key], $url); + $url = str_replace(['[:' . $key . ']', '<' . $key . '?>', ':' . $key, '<' . $key . '>'], $type ? $vars[$key] : urlencode($vars[$key]), $url); unset($vars[$key]); - $result = [$url, $domain]; + $url = str_replace(['/?', '-?'], ['/', '-'], $url); + $result = [rtrim($url, '?/-'), $domain, $suffix]; } elseif (2 == $val) { $url = str_replace(['/[:' . $key . ']', '[:' . $key . ']', '<' . $key . '?>'], '', $url); - $result = [$url, $domain]; + $url = str_replace(['/?', '-?'], ['/', '-'], $url); + $result = [rtrim($url, '?/-'), $domain, $suffix]; } else { break; } } + if (isset($result)) { return $result; } } + return false; } // 指定当前生成URL地址的root - public static function root($root) + public function root($root) { - self::$root = $root; - Request::instance()->root($root); + $this->root = $root; + $this->app['request']->setRoot($root); } } diff --git a/library/think/Validate.php b/library/think/Validate.php index 5fa15424ca71897fd3d21a369bd68f50f1685918..de46956cf20b756345d856a0c7091ca1429bfea6 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,145 +11,224 @@ namespace think; -use think\File; -use think\Request; -use think\Session; +use think\exception\ClassNotFoundException; +use think\validate\ValidateRule; class Validate { - // 实例 - protected static $instance; - // 自定义的验证类型 + /** + * 自定义验证类型 + * @var array + */ protected static $type = []; - // 验证类型别名 + /** + * 验证类型别名 + * @var array + */ protected $alias = [ '>' => 'gt', '>=' => 'egt', '<' => 'lt', '<=' => 'elt', '=' => 'eq', 'same' => 'eq', ]; - // 当前验证的规则 + /** + * 当前验证规则 + * @var array + */ protected $rule = []; - // 验证提示信息 + /** + * 验证提示信息 + * @var array + */ protected $message = []; - // 验证规则默认提示信息 - protected static $typeMsg = [ - 'require' => ':attribute不能为空', - 'number' => ':attribute必须是数字', - 'float' => ':attribute必须是浮点数', - 'boolean' => ':attribute必须是布尔值', - 'email' => ':attribute格式不符', - 'array' => ':attribute必须是数组', - 'accepted' => ':attribute必须是yes、on或者1', - 'date' => ':attribute格式不符合', - 'file' => ':attribute不是有效的上传文件', - 'image' => ':attribute不是有效的图像文件', - 'alpha' => ':attribute只能是字母', - 'alphaNum' => ':attribute只能是字母和数字', - 'alphaDash' => ':attribute只能是字母、数字和下划线_及破折号-', - 'activeUrl' => ':attribute不是有效的域名或者IP', - 'chs' => ':attribute只能是汉字', - 'chsAlpha' => ':attribute只能是汉字、字母', - 'chsAlphaNum' => ':attribute只能是汉字、字母和数字', - 'chsDash' => ':attribute只能是汉字、字母、数字和下划线_及破折号-', - 'url' => ':attribute不是有效的URL地址', - 'ip' => ':attribute不是有效的IP地址', - 'dateFormat' => ':attribute必须使用日期格式 :rule', - 'in' => ':attribute必须在 :rule 范围内', - 'notIn' => ':attribute不能在 :rule 范围内', - 'between' => ':attribute只能在 :1 - :2 之间', - 'notBetween' => ':attribute不能在 :1 - :2 之间', - 'length' => ':attribute长度不符合要求 :rule', - 'max' => ':attribute长度不能超过 :rule', - 'min' => ':attribute长度不能小于 :rule', - 'after' => ':attribute日期不能小于 :rule', - 'before' => ':attribute日期不能超过 :rule', - 'expire' => '不在有效期内 :rule', - 'allowIp' => '不允许的IP访问', - 'denyIp' => '禁止的IP访问', - 'confirm' => ':attribute和字段 :rule 不一致', - 'different' => ':attribute和字段 :rule 不能相同', - 'egt' => ':attribute必须大于等于 :rule', - 'gt' => ':attribute必须大于 :rule', - 'elt' => ':attribute必须小于等于 :rule', - 'lt' => ':attribute必须小于 :rule', - 'eq' => ':attribute必须等于 :rule', - 'unique' => ':attribute已存在', - 'regex' => ':attribute不符合指定规则', - 'method' => '无效的请求类型', - 'token' => '令牌数据无效', - 'fileSize' => '上传文件大小不符', - 'fileExt' => '上传文件后缀不符', - 'fileMime' => '上传文件类型不符', + /** + * 验证字段描述 + * @var array + */ + protected $field = []; + /** + * 默认规则提示 + * @var array + */ + protected static $typeMsg = [ + 'require' => ':attribute require', + 'must' => ':attribute must', + 'number' => ':attribute must be numeric', + 'integer' => ':attribute must be integer', + 'float' => ':attribute must be float', + 'boolean' => ':attribute must be bool', + 'email' => ':attribute not a valid email address', + 'mobile' => ':attribute not a valid mobile', + 'array' => ':attribute must be a array', + 'accepted' => ':attribute must be yes,on or 1', + 'date' => ':attribute not a valid datetime', + 'file' => ':attribute not a valid file', + 'image' => ':attribute not a valid image', + 'alpha' => ':attribute must be alpha', + 'alphaNum' => ':attribute must be alpha-numeric', + 'alphaDash' => ':attribute must be alpha-numeric, dash, underscore', + 'activeUrl' => ':attribute not a valid domain or ip', + 'chs' => ':attribute must be chinese', + 'chsAlpha' => ':attribute must be chinese or alpha', + 'chsAlphaNum' => ':attribute must be chinese,alpha-numeric', + 'chsDash' => ':attribute must be chinese,alpha-numeric,underscore, dash', + 'url' => ':attribute not a valid url', + 'ip' => ':attribute not a valid ip', + 'dateFormat' => ':attribute must be dateFormat of :rule', + 'in' => ':attribute must be in :rule', + 'notIn' => ':attribute be notin :rule', + 'between' => ':attribute must between :1 - :2', + 'notBetween' => ':attribute not between :1 - :2', + 'length' => 'size of :attribute must be :rule', + 'max' => 'max size of :attribute must be :rule', + 'min' => 'min size of :attribute must be :rule', + 'after' => ':attribute cannot be less than :rule', + 'before' => ':attribute cannot exceed :rule', + 'expire' => ':attribute not within :rule', + 'allowIp' => 'access IP is not allowed', + 'denyIp' => 'access IP denied', + 'confirm' => ':attribute out of accord with :2', + 'different' => ':attribute cannot be same with :2', + 'egt' => ':attribute must greater than or equal :rule', + 'gt' => ':attribute must greater than :rule', + 'elt' => ':attribute must less than or equal :rule', + 'lt' => ':attribute must less than :rule', + 'eq' => ':attribute must equal :rule', + 'unique' => ':attribute has exists', + 'regex' => ':attribute not conform to the rules', + 'method' => 'invalid Request method', + 'token' => 'invalid token', + 'fileSize' => 'filesize not match', + 'fileExt' => 'extensions to upload is not allowed', + 'fileMime' => 'mimetype to upload is not allowed', ]; - // 当前验证场景 + /** + * 当前验证场景 + * @var array + */ protected $currentScene = null; - // 正则表达式 regex = ['zip'=>'\d{6}',...] - protected $regex = []; + /** + * Filter_var 规则 + * @var array + */ + protected $filter = [ + 'email' => FILTER_VALIDATE_EMAIL, + 'ip' => [FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6], + 'integer' => FILTER_VALIDATE_INT, + 'url' => FILTER_VALIDATE_URL, + 'macAddr' => FILTER_VALIDATE_MAC, + 'float' => FILTER_VALIDATE_FLOAT, + ]; + + /** + * 内置正则验证规则 + * @var array + */ + protected $regex = [ + 'alphaDash' => '/^[A-Za-z0-9\-\_]+$/', + 'chs' => '/^[\x{4e00}-\x{9fa5}]+$/u', + 'chsAlpha' => '/^[\x{4e00}-\x{9fa5}a-zA-Z]+$/u', + 'chsAlphaNum' => '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u', + 'chsDash' => '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-]+$/u', + 'mobile' => '/^1[3-9][0-9]\d{8}$/', + 'idCard' => '/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/', + 'zip' => '/\d{6}/', + ]; - // 验证场景 scene = ['edit'=>'name1,name2,...'] + /** + * 验证场景定义 + * @var array + */ protected $scene = []; - // 验证失败错误信息 + /** + * 验证失败错误信息 + * @var array + */ protected $error = []; - // 批量验证 + /** + * 是否批量验证 + * @var bool + */ protected $batch = false; + /** + * 场景需要验证的规则 + * @var array + */ + protected $only = []; + + /** + * 场景需要移除的验证规则 + * @var array + */ + protected $remove = []; + + /** + * 场景需要追加的验证规则 + * @var array + */ + protected $append = []; + /** * 架构函数 * @access public - * @param array $rules 验证规则 - * @param array $message 验证提示信息 + * @param array $rules 验证规则 + * @param array $message 验证提示信息 + * @param array $field 验证字段描述信息 */ - public function __construct(array $rules = [], $message = []) + public function __construct(array $rules = [], array $message = [], array $field = []) { - $this->rule = array_merge($this->rule, $rules); + $this->rule = $rules + $this->rule; $this->message = array_merge($this->message, $message); + $this->field = array_merge($this->field, $field); } /** - * 实例化验证 + * 创建一个验证器类 * @access public - * @param array $rules 验证规则 - * @param array $message 验证提示信息 + * @param array $rules 验证规则 + * @param array $message 验证提示信息 + * @param array $field 验证字段描述信息 * @return Validate */ - public static function make($rules = [], $message = []) + public static function make(array $rules = [], array $message = [], array $field = []) { - if (is_null(self::$instance)) { - self::$instance = new self($rules, $message); - } - return self::$instance; + return new self($rules, $message, $field); } /** * 添加字段验证规则 * @access protected - * @param string|array $name 字段名称或者规则数组 - * @param mixed $rule 验证规则 - * @return Validate + * @param string|array $name 字段名称或者规则数组 + * @param mixed $rule 验证规则或者字段描述信息 + * @return $this */ public function rule($name, $rule = '') { if (is_array($name)) { - $this->rule = array_merge($this->rule, $name); + $this->rule = $name + $this->rule; + if (is_array($rule)) { + $this->field = array_merge($this->field, $rule); + } } else { $this->rule[$name] = $rule; } + return $this; } /** - * 注册验证(类型)规则 + * 注册扩展验证(类型)规则 * @access public - * @param string $type 验证规则类型 - * @param mixed $callback callback方法(或闭包) + * @param string $type 验证规则类型 + * @param mixed $callback callback方法(或闭包) * @return void */ public static function extend($type, $callback = null) @@ -162,10 +241,10 @@ class Validate } /** - * 获取验证规则的默认提示信息 - * @access protected - * @param string|array $type 验证规则类型名称或者数组 - * @param string $msg 验证提示信息 + * 设置验证规则的默认提示信息 + * @access public + * @param string|array $type 验证规则类型名称或者数组 + * @param string $msg 验证提示信息 * @return void */ public static function setTypeMsg($type, $msg = null) @@ -180,8 +259,8 @@ class Validate /** * 设置提示信息 * @access public - * @param string|array $name 字段名称 - * @param string $message 提示信息 + * @param string|array $name 字段名称 + * @param string $message 提示信息 * @return Validate */ public function message($name, $message = '') @@ -191,48 +270,119 @@ class Validate } else { $this->message[$name] = $message; } + return $this; } /** * 设置验证场景 * @access public - * @param string|array $name 场景名或者场景设置数组 - * @param mixed $fields 要验证的字段 - * @return Validate + * @param string $name 场景名 + * @return $this */ - public function scene($name, $fields = null) + public function scene($name) { - if (is_array($name)) { - $this->scene = array_merge($this->scene, $name); - }if (is_null($fields)) { - // 设置当前场景 - $this->currentScene = $name; - } else { - // 设置验证场景 - $this->scene[$name] = $fields; - } + // 设置当前场景 + $this->currentScene = $name; + return $this; } + /** + * 判断是否存在某个验证场景 + * @access public + * @param string $name 场景名 + * @return bool + */ + public function hasScene($name) + { + return isset($this->scene[$name]) || method_exists($this, 'scene' . $name); + } + /** * 设置批量验证 * @access public - * @param bool $batch 是否批量验证 - * @return Validate + * @param bool $batch 是否批量验证 + * @return $this */ public function batch($batch = true) { $this->batch = $batch; + + return $this; + } + + /** + * 指定需要验证的字段列表 + * @access public + * @param array $fields 字段名 + * @return $this + */ + public function only($fields) + { + $this->only = $fields; + + return $this; + } + + /** + * 移除某个字段的验证规则 + * @access public + * @param string|array $field 字段名 + * @param mixed $rule 验证规则 true 移除所有规则 + * @return $this + */ + public function remove($field, $rule = true) + { + if (is_array($field)) { + foreach ($field as $key => $rule) { + if (is_int($key)) { + $this->remove($rule); + } else { + $this->remove($key, $rule); + } + } + } else { + if (is_string($rule)) { + $rule = explode('|', $rule); + } + + $this->remove[$field] = $rule; + } + + return $this; + } + + /** + * 追加某个字段的验证规则 + * @access public + * @param string|array $field 字段名 + * @param mixed $rule 验证规则 + * @return $this + */ + public function append($field, $rule = null) + { + if (is_array($field)) { + foreach ($field as $key => $rule) { + $this->append($key, $rule); + } + } else { + if (is_string($rule)) { + $rule = explode('|', $rule); + } + + $this->append[$field] = $rule; + } + return $this; } /** * 数据自动验证 * @access public - * @param array $data 数据 - * @param mixed $rules 验证规则 - * @param string $scene 验证场景 + * @param array $data 数据 + * @param mixed $rules 验证规则 + * @param string $scene 验证场景 * @return bool */ public function check($data, $rules = [], $scene = '') @@ -244,63 +394,41 @@ class Validate $rules = $this->rule; } - // 分析验证规则 - $scene = $this->getScene($scene); - if (is_array($scene)) { - // 处理场景验证字段 - $change = []; - $array = []; - foreach ($scene as $k => $val) { - if (is_numeric($k)) { - $array[] = $val; - } else { - $array[] = $k; - $change[$k] = $val; - } + // 获取场景定义 + $this->getScene($scene); + + foreach ($this->append as $key => $rule) { + if (!isset($rules[$key])) { + $rules[$key] = $rule; } } - foreach ($rules as $key => $item) { - // field => rule1|rule2... field=>['rule1','rule2',...] - if (is_numeric($key)) { - // [field,rule1|rule2,msg1|msg2] - $key = $item[0]; - $rule = $item[1]; - if (isset($item[2])) { - $msg = is_string($item[2]) ? explode('|', $item[2]) : $item[2]; - } else { - $msg = []; - } - } else { - $rule = $item; - $msg = []; - } + foreach ($rules as $key => $rule) { + // field => 'rule1|rule2...' field => ['rule1','rule2',...] if (strpos($key, '|')) { // 字段|描述 用于指定属性名称 list($key, $title) = explode('|', $key); } else { - $title = $key; + $title = isset($this->field[$key]) ? $this->field[$key] : $key; } // 场景检测 - if (!empty($scene)) { - if ($scene instanceof \Closure && !call_user_func_array($scene, [$key, $data])) { - continue; - } elseif (is_array($scene)) { - if (!in_array($key, $array)) { - continue; - } elseif (isset($change[$key])) { - // 重载某个验证规则 - $rule = $change[$key]; - } - } + if (!empty($this->only) && !in_array($key, $this->only)) { + continue; } // 获取数据 支持二维数组 $value = $this->getDataValue($data, $key); // 字段验证 - $result = $this->checkItem($key, $value, $rule, $data, $title, $msg); + if ($rule instanceof \Closure) { + $result = call_user_func_array($rule, [$value, $data]); + } elseif ($rule instanceof ValidateRule) { + // 验证因子 + $result = $this->checkItem($key, $value, $rule->getRule(), $data, $rule->getTitle() ?: $title, $rule->getMsg()); + } else { + $result = $this->checkItem($key, $value, $rule, $data, $title); + } if (true !== $result) { // 没有返回true 则表示验证失败 @@ -317,176 +445,286 @@ class Validate } } } + return !empty($this->error) ? false : true; } + /** + * 根据验证规则验证数据 + * @access public + * @param mixed $value 字段值 + * @param mixed $rules 验证规则 + * @return bool + */ + public function checkRule($value, $rules) + { + if ($rules instanceof \Closure) { + return call_user_func_array($rules, [$value]); + } elseif ($rules instanceof ValidateRule) { + $rules = $rules->getRule(); + } elseif (is_string($rules)) { + $rules = explode('|', $rules); + } + + foreach ($rules as $key => $rule) { + if ($rule instanceof \Closure) { + $result = call_user_func_array($rule, [$value]); + } else { + // 判断验证类型 + list($type, $rule) = $this->getValidateType($key, $rule); + + $callback = isset(self::$type[$type]) ? self::$type[$type] : [$this, $type]; + + $result = call_user_func_array($callback, [$value, $rule]); + } + + if (true !== $result) { + return $result; + } + } + + return true; + } + /** * 验证单个字段规则 * @access protected - * @param string $field 字段名 - * @param mixed $value 字段值 - * @param mixed $rules 验证规则 - * @param array $data 数据 - * @param string $title 字段描述 - * @param array $msg 提示信息 + * @param string $field 字段名 + * @param mixed $value 字段值 + * @param mixed $rules 验证规则 + * @param array $data 数据 + * @param string $title 字段描述 + * @param array $msg 提示信息 * @return mixed */ protected function checkItem($field, $value, $rules, $data, $title = '', $msg = []) { - if ($rules instanceof \Closure) { - // 匿名函数验证 支持传入当前字段和所有字段两个数据 - $result = call_user_func_array($rules, [$value, $data]); - } else { - // 支持多规则验证 require|in:a,b,c|... 或者 ['require','in'=>'a,b,c',...] - if (is_string($rules)) { - $rules = explode('|', $rules); - } - $i = 0; - foreach ($rules as $key => $rule) { - if ($rule instanceof \Closure) { - $result = call_user_func_array($rule, [$value, $data]); + if (isset($this->remove[$field]) && true === $this->remove[$field] && empty($this->append[$field])) { + // 字段已经移除 无需验证 + return true; + } + + // 支持多规则验证 require|in:a,b,c|... 或者 ['require','in'=>'a,b,c',...] + if (is_string($rules)) { + $rules = explode('|', $rules); + } + + if (isset($this->append[$field])) { + // 追加额外的验证规则 + $rules = array_merge($rules, $this->append[$field]); + } + + $i = 0; + foreach ($rules as $key => $rule) { + if ($rule instanceof \Closure) { + $result = call_user_func_array($rule, [$value, $data]); + $info = is_numeric($key) ? '' : $key; + } else { + // 判断验证类型 + list($type, $rule, $info) = $this->getValidateType($key, $rule); + + if (isset($this->append[$field]) && in_array($info, $this->append[$field])) { + + } elseif (isset($this->remove[$field]) && in_array($info, $this->remove[$field])) { + // 规则已经移除 + $i++; + continue; + } + + if ('must' == $info || 0 === strpos($info, 'require') || (!is_null($value) && '' !== $value)) { + // 验证类型 + $callback = isset(self::$type[$type]) ? self::$type[$type] : [$this, $type]; + // 验证数据 + $result = call_user_func_array($callback, [$value, $rule, $data, $field, $title]); } else { - // 判断验证类型 - if (is_numeric($key) && strpos($rule, ':')) { - list($type, $rule) = explode(':', $rule, 2); - if (isset($this->alias[$type])) { - // 判断别名 - $type = $this->alias[$type]; - } - $info = $type; - } elseif (is_numeric($key)) { - $type = 'is'; - $info = $rule; - } else { - $info = $type = $key; - } + $result = true; + } + } - // 如果不是require 有数据才会行验证 - if (0 === strpos($info, 'require') || (!is_null($value) && '' !== $value)) { - // 验证类型 - $callback = isset(self::$type[$type]) ? self::$type[$type] : [$this, $type]; - // 验证数据 - $result = call_user_func_array($callback, [$value, $rule, $data, $field]); - } else { - $result = true; + if (false === $result) { + // 验证失败 返回错误信息 + if (!empty($msg[$i])) { + $message = $msg[$i]; + if (is_string($message) && strpos($message, '{%') === 0) { + $message = Lang::get(substr($message, 2, -1)); } + } else { + $message = $this->getRuleMsg($field, $title, $info, $rule); } - if (false === $result) { - // 验证失败 返回错误信息 - if (isset($msg[$i])) { - $message = $msg[$i]; - } else { - $message = $this->getRuleMsg($field, $title, $info, $rule); - } - return $message; - } elseif (true !== $result) { - // 返回自定义错误信息 - return $result; + return $message; + } elseif (true !== $result) { + // 返回自定义错误信息 + if (is_string($result) && false !== strpos($result, ':')) { + $result = str_replace( + [':attribute', ':rule'], + [$title, (string) $rule], + $result); } - $i++; + + return $result; } + $i++; } - return true !== $result ? $result : true; + + return $result; + } + + /** + * 获取当前验证类型及规则 + * @access public + * @param mixed $key + * @param mixed $rule + * @return array + */ + protected function getValidateType($key, $rule) + { + // 判断验证类型 + if (!is_numeric($key)) { + return [$key, $rule, $key]; + } + + if (strpos($rule, ':')) { + list($type, $rule) = explode(':', $rule, 2); + if (isset($this->alias[$type])) { + // 判断别名 + $type = $this->alias[$type]; + } + $info = $type; + } elseif (method_exists($this, $rule)) { + $type = $rule; + $info = $rule; + $rule = ''; + } else { + $type = 'is'; + $info = $rule; + } + + return [$type, $rule, $info]; } /** * 验证是否和某个字段的值一致 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 - * @param array $data 数据 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 + * @param string $field 字段名 * @return bool */ - protected function confirm($value, $rule, $data) + public function confirm($value, $rule, $data = [], $field = '') { - return $this->getDataValue($data, $rule) == $value; + if ('' == $rule) { + if (strpos($field, '_confirm')) { + $rule = strstr($field, '_confirm', true); + } else { + $rule = $field . '_confirm'; + } + } + + return $this->getDataValue($data, $rule) === $value; } /** * 验证是否和某个字段的值是否不同 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 - * @param array $data 数据 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return bool */ - protected function different($value, $rule, $data) + public function different($value, $rule, $data = []) { return $this->getDataValue($data, $rule) != $value; } /** * 验证是否大于等于某个值 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return bool */ - protected function egt($value, $rule) + public function egt($value, $rule, $data = []) { - return $value >= $rule; + return $value >= $this->getDataValue($data, $rule); } /** * 验证是否大于某个值 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return bool */ - protected function gt($value, $rule) + public function gt($value, $rule, $data) { - return $value > $rule; + return $value > $this->getDataValue($data, $rule); } /** * 验证是否小于等于某个值 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return bool */ - protected function elt($value, $rule) + public function elt($value, $rule, $data = []) { - return $value <= $rule; + return $value <= $this->getDataValue($data, $rule); } /** * 验证是否小于某个值 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return bool */ - protected function lt($value, $rule) + public function lt($value, $rule, $data = []) { - return $value < $rule; + return $value < $this->getDataValue($data, $rule); } /** * 验证是否等于某个值 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function eq($value, $rule) + public function eq($value, $rule) { return $value == $rule; } + /** + * 必须验证 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @return bool + */ + public function must($value, $rule = null) + { + return !empty($value) || '0' == $value; + } + /** * 验证字段值是否为有效格式 - * @access protected - * @param mixed $value 字段值 - * @param string $rule 验证规则 - * @param array $data 验证数据 + * @access public + * @param mixed $value 字段值 + * @param string $rule 验证规则 + * @param array $data 验证数据 * @return bool */ - protected function is($value, $rule, $data = []) + public function is($value, $rule, $data = []) { - switch ($rule) { + switch (Loader::parseName($rule, 1, false)) { case 'require': // 必须 $result = !empty($value) || '0' == $value; @@ -499,64 +737,20 @@ class Validate // 是否是一个有效日期 $result = false !== strtotime($value); break; - case 'alpha': - // 只允许字母 - $result = $this->regex($value, '/^[A-Za-z]+$/'); - break; - case 'alphaNum': - // 只允许字母和数字 - $result = $this->regex($value, '/^[A-Za-z0-9]+$/'); - break; - case 'alphaDash': - // 只允许字母、数字和下划线 破折号 - $result = $this->regex($value, '/^[A-Za-z0-9\-\_]+$/'); - break; - case 'chs': - // 只允许汉字 - $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}]+$/u'); - break; - case 'chsAlpha': - // 只允许汉字、字母 - $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z]+$/u'); - break; - case 'chsAlphaNum': - // 只允许汉字、字母和数字 - $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u'); - break; - case 'chsDash': - // 只允许汉字、字母、数字和下划线_及破折号- - $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-]+$/u'); - break; case 'activeUrl': // 是否为有效的网址 $result = checkdnsrr($value); break; - case 'ip': - // 是否为IP地址 - $result = $this->filter($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6); - break; - case 'url': - // 是否为一个URL地址 - $result = $this->filter($value, FILTER_VALIDATE_URL); - break; - case 'float': - // 是否为float - $result = $this->filter($value, FILTER_VALIDATE_FLOAT); + case 'boolean': + case 'bool': + // 是否为布尔值 + $result = in_array($value, [true, false, 0, 1, '0', '1'], true); break; case 'number': - $result = is_numeric($value); + $result = ctype_digit((string) $value); break; - case 'integer': - // 是否为整型 - $result = $this->filter($value, FILTER_VALIDATE_INT); - break; - case 'email': - // 是否为邮箱地址 - $result = $this->filter($value, FILTER_VALIDATE_EMAIL); - break; - case 'boolean': - // 是否为布尔值 - $result = in_array($value, [0, 1, true, false]); + case 'alphaNum': + $result = ctype_alnum($value); break; case 'array': // 是否为数组 @@ -575,11 +769,19 @@ class Validate if (isset(self::$type[$rule])) { // 注册的验证规则 $result = call_user_func_array(self::$type[$rule], [$value]); + } elseif (function_exists('ctype_' . $rule)) { + // ctype验证规则 + $ctypeFun = 'ctype_' . $rule; + $result = $ctypeFun($value); + } elseif (isset($this->filter[$rule])) { + // Filter_var验证规则 + $result = $this->filter($value, $this->filter[$rule]); } else { // 正则验证 $result = $this->regex($value, $rule); } } + return $result; } @@ -588,165 +790,176 @@ class Validate { if (function_exists('exif_imagetype')) { return exif_imagetype($image); - } else { + } + + try { $info = getimagesize($image); - return $info[2]; + return $info ? $info[2] : false; + } catch (\Exception $e) { + return false; } } /** * 验证是否为合格的域名或者IP 支持A,MX,NS,SOA,PTR,CNAME,AAAA,A6, SRV,NAPTR,TXT 或者 ANY类型 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function activeUrl($value, $rule) + public function activeUrl($value, $rule = 'MX') { + if (!in_array($rule, ['A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY'])) { + $rule = 'MX'; + } + return checkdnsrr($value, $rule); } /** * 验证是否有效IP - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 ipv4 ipv6 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 ipv4 ipv6 * @return bool */ - protected function ip($value, $rule) + public function ip($value, $rule = 'ipv4') { if (!in_array($rule, ['ipv4', 'ipv6'])) { $rule = 'ipv4'; } - return $this->filter($value, FILTER_VALIDATE_IP, 'ipv6' == $rule ? FILTER_FLAG_IPV6 : FILTER_FLAG_IPV4); + + return $this->filter($value, [FILTER_VALIDATE_IP, 'ipv6' == $rule ? FILTER_FLAG_IPV6 : FILTER_FLAG_IPV4]); } /** * 验证上传文件后缀 - * @access protected - * @param mixed $file 上传文件 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $file 上传文件 + * @param mixed $rule 验证规则 * @return bool */ - protected function fileExt($file, $rule) + public function fileExt($file, $rule) { - if (!($file instanceof File)) { - return false; - } - if (is_string($rule)) { - $rule = explode(',', $rule); - } if (is_array($file)) { foreach ($file as $item) { - if (!$item->checkExt($rule)) { + if (!($item instanceof File) || !$item->checkExt($rule)) { return false; } } return true; - } else { + } elseif ($file instanceof File) { return $file->checkExt($rule); } + + return false; } /** * 验证上传文件类型 - * @access protected - * @param mixed $file 上传文件 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $file 上传文件 + * @param mixed $rule 验证规则 * @return bool */ - protected function fileMime($file, $rule) + public function fileMime($file, $rule) { - if (!($file instanceof File)) { - return false; - } - if (is_string($rule)) { - $rule = explode(',', $rule); - } if (is_array($file)) { foreach ($file as $item) { - if (!$item->checkMime($rule)) { + if (!($item instanceof File) || !$item->checkMime($rule)) { return false; } } return true; - } else { + } elseif ($file instanceof File) { return $file->checkMime($rule); } + + return false; } /** * 验证上传文件大小 - * @access protected - * @param mixed $file 上传文件 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $file 上传文件 + * @param mixed $rule 验证规则 * @return bool */ - protected function fileSize($file, $rule) + public function fileSize($file, $rule) { - if (!($file instanceof File)) { - return false; - } if (is_array($file)) { foreach ($file as $item) { - if (!$item->checkSize($rule)) { + if (!($item instanceof File) || !$item->checkSize($rule)) { return false; } } return true; - } else { + } elseif ($file instanceof File) { return $file->checkSize($rule); } + + return false; } /** * 验证图片的宽高及类型 - * @access protected - * @param mixed $file 上传文件 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $file 上传文件 + * @param mixed $rule 验证规则 * @return bool */ - protected function image($file, $rule) + public function image($file, $rule) { if (!($file instanceof File)) { return false; } - $rule = explode(',', $rule); - list($width, $height, $type) = getimagesize($file->getRealPath()); - if (isset($rule[2])) { - $imageType = strtolower($rule[2]); - if ('jpeg' == $imageType) { - $imageType = 'jpg'; - } - if (image_type_to_extension($type, false) != $imageType) { - return false; + + if ($rule) { + $rule = explode(',', $rule); + + list($width, $height, $type) = getimagesize($file->getRealPath()); + + if (isset($rule[2])) { + $imageType = strtolower($rule[2]); + + if ('jpeg' == $imageType) { + $imageType = 'jpg'; + } + + if (image_type_to_extension($type, false) != $imageType) { + return false; + } } + + list($w, $h) = $rule; + + return $w == $width && $h == $height; } - list($w, $h) = $rule; - return $w == $width && $h == $height; + + return in_array($this->getImageType($file->getRealPath()), [1, 2, 3, 6]); } /** * 验证请求类型 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function method($value, $rule) + public function method($value, $rule) { - $method = Request::instance()->method(); + $method = Container::get('request')->method(); return strtoupper($rule) == $method; } /** * 验证时间和日期是否符合指定格式 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function dateFormat($value, $rule) + public function dateFormat($value, $rule) { $info = date_parse_from_format($rule, $value); return 0 == $info['warning_count'] && 0 == $info['error_count']; @@ -754,196 +967,216 @@ class Validate /** * 验证是否唯一 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 格式:数据表,字段名,排除ID,主键名 - * @param array $data 数据 - * @param string $field 验证字段名 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 格式:数据表,字段名,排除ID,主键名 + * @param array $data 数据 + * @param string $field 验证字段名 * @return bool */ - protected function unique($value, $rule, $data, $field) + public function unique($value, $rule, $data, $field) { if (is_string($rule)) { $rule = explode(',', $rule); } - $db = Db::name($rule[0]); + + if (false !== strpos($rule[0], '\\')) { + // 指定模型类 + $db = new $rule[0]; + } else { + try { + $db = Container::get('app')->model($rule[0]); + } catch (ClassNotFoundException $e) { + $db = Db::name($rule[0]); + } + } + $key = isset($rule[1]) ? $rule[1] : $field; if (strpos($key, '^')) { // 支持多个字段验证 $fields = explode('^', $key); foreach ($fields as $key) { - $map[$key] = $data[$key]; + $map[] = [$key, '=', $data[$key]]; } - } elseif (strpos($key, '=')) { - parse_str($key, $map); } else { - $map[$key] = $data[$field]; + $map[] = [$key, '=', $data[$field]]; } - $pk = strval(isset($rule[3]) ? $rule[3] : $db->getPk()); - if (isset($rule[2])) { - $map[$pk] = ['neq', $rule[2]]; - } elseif (isset($data[$pk])) { - $map[$pk] = ['neq', $data[$pk]]; + $pk = !empty($rule[3]) ? $rule[3] : $db->getPk(); + + if (is_string($pk)) { + if (isset($rule[2])) { + $map[] = [$pk, '<>', $rule[2]]; + } elseif (isset($data[$pk])) { + $map[] = [$pk, '<>', $data[$pk]]; + } } if ($db->where($map)->field($pk)->find()) { return false; } + return true; } /** * 使用行为类验证 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 - * @param array $data 数据 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return mixed */ - protected function behavior($value, $rule, $data) + public function behavior($value, $rule, $data) { - return Hook::exec($rule, '', $data); + return Container::get('hook')->exec($rule, $data); } /** * 使用filter_var方式验证 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function filter($value, $rule) + public function filter($value, $rule) { if (is_string($rule) && strpos($rule, ',')) { list($rule, $param) = explode(',', $rule); } elseif (is_array($rule)) { $param = isset($rule[1]) ? $rule[1] : null; + $rule = $rule[0]; } else { $param = null; } + return false !== filter_var($value, is_int($rule) ? $rule : filter_id($rule), $param); } /** * 验证某个字段等于某个值的时候必须 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 - * @param array $data 数据 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return bool */ - protected function requireIf($value, $rule, $data) + public function requireIf($value, $rule, $data) { list($field, $val) = explode(',', $rule); + if ($this->getDataValue($data, $field) == $val) { - return !empty($value); - } else { - return true; + return !empty($value) || '0' == $value; } + + return true; } /** * 通过回调方法验证某个字段是否必须 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 - * @param array $data 数据 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return bool */ - protected function requireCallback($value, $rule, $data) + public function requireCallback($value, $rule, $data) { - $result = call_user_func_array($rule, [$value, $data]); + $result = call_user_func_array([$this, $rule], [$value, $data]); + if ($result) { - return !empty($value); - } else { - return true; + return !empty($value) || '0' == $value; } + + return true; } /** * 验证某个字段有值的情况下必须 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 - * @param array $data 数据 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return bool */ - protected function requireWith($value, $rule, $data) + public function requireWith($value, $rule, $data) { $val = $this->getDataValue($data, $rule); + if (!empty($val)) { - return !empty($value); - } else { - return true; + return !empty($value) || '0' == $value; } + + return true; } /** * 验证是否在范围内 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function in($value, $rule) + public function in($value, $rule) { return in_array($value, is_array($rule) ? $rule : explode(',', $rule)); } /** * 验证是否不在某个范围 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function notIn($value, $rule) + public function notIn($value, $rule) { return !in_array($value, is_array($rule) ? $rule : explode(',', $rule)); } /** * between验证数据 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function between($value, $rule) + public function between($value, $rule) { if (is_string($rule)) { $rule = explode(',', $rule); } list($min, $max) = $rule; + return $value >= $min && $value <= $max; } /** * 使用notbetween验证数据 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function notBetween($value, $rule) + public function notBetween($value, $rule) { if (is_string($rule)) { $rule = explode(',', $rule); } list($min, $max) = $rule; + return $value < $min || $value > $max; } /** * 验证数据长度 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function length($value, $rule) + public function length($value, $rule) { if (is_array($value)) { $length = count($value); @@ -957,20 +1190,20 @@ class Validate // 长度区间 list($min, $max) = explode(',', $rule); return $length >= $min && $length <= $max; - } else { - // 指定长度 - return $length == $rule; } + + // 指定长度 + return $length == $rule; } /** * 验证数据最大长度 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function max($value, $rule) + public function max($value, $rule) { if (is_array($value)) { $length = count($value); @@ -979,17 +1212,18 @@ class Validate } else { $length = mb_strlen((string) $value); } + return $length <= $rule; } /** * 验证数据最小长度 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function min($value, $rule) + public function min($value, $rule) { if (is_array($value)) { $length = count($value); @@ -998,46 +1232,49 @@ class Validate } else { $length = mb_strlen((string) $value); } + return $length >= $rule; } /** * 验证日期 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function after($value, $rule) + public function after($value, $rule) { return strtotime($value) >= strtotime($rule); } /** * 验证日期 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function before($value, $rule) + public function before($value, $rule) { return strtotime($value) <= strtotime($rule); } /** * 验证有效期 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 * @return bool */ - protected function expire($value, $rule) + public function expire($value, $rule) { if (is_string($rule)) { $rule = explode(',', $rule); } + list($start, $end) = $rule; + if (!is_numeric($start)) { $start = strtotime($start); } @@ -1045,76 +1282,83 @@ class Validate if (!is_numeric($end)) { $end = strtotime($end); } + return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end; } /** * 验证IP许可 - * @access protected - * @param string $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param string $value 字段值 + * @param mixed $rule 验证规则 * @return mixed */ - protected function allowIp($value, $rule) + public function allowIp($value, $rule) { - return in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule)); + return in_array($value, is_array($rule) ? $rule : explode(',', $rule)); } /** * 验证IP禁用 - * @access protected - * @param string $value 字段值 - * @param mixed $rule 验证规则 + * @access public + * @param string $value 字段值 + * @param mixed $rule 验证规则 * @return mixed */ - protected function denyIp($value, $rule) + public function denyIp($value, $rule) { - return !in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule)); + return !in_array($value, is_array($rule) ? $rule : explode(',', $rule)); } /** * 使用正则验证数据 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 正则规则或者预定义正则名 - * @return mixed + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 正则规则或者预定义正则名 + * @return bool */ - protected function regex($value, $rule) + public function regex($value, $rule) { if (isset($this->regex[$rule])) { $rule = $this->regex[$rule]; } + if (0 !== strpos($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) { // 不是正则表达式则两端补上/ $rule = '/^' . $rule . '$/'; } - return 1 === preg_match($rule, (string) $value); + + return is_scalar($value) && 1 === preg_match($rule, (string) $value); } /** * 验证表单令牌 - * @access protected - * @param mixed $value 字段值 - * @param mixed $rule 验证规则 - * @param array $data 数据 + * @access public + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 * @return bool */ - protected function token($value, $rule, $data) + public function token($value, $rule, $data) { - $rule = !empty($rule) ? $rule : '__token__'; - if (!isset($data[$rule]) || !Session::has($rule)) { + $rule = !empty($rule) ? $rule : '__token__'; + $session = Container::get('session'); + + if (!isset($data[$rule]) || !$session->has($rule)) { // 令牌数据无效 return false; } // 令牌验证 - if (isset($data[$rule]) && Session::get($rule) === $data[$rule]) { + if (isset($data[$rule]) && $session->get($rule) === $data[$rule]) { // 防止重复提交 - Session::delete($rule); // 验证完成销毁session + $session->delete($rule); // 验证完成销毁session return true; } + // 开启TOKEN重置 - Session::delete($rule); + $session->delete($rule); + return false; } @@ -1127,46 +1371,61 @@ class Validate /** * 获取数据值 * @access protected - * @param array $data 数据 - * @param string $key 数据标识 支持二维 + * @param array $data 数据 + * @param string $key 数据标识 支持二维 * @return mixed */ protected function getDataValue($data, $key) { - if (strpos($key, '.')) { + if (is_numeric($key)) { + $value = $key; + } elseif (strpos($key, '.')) { // 支持二维数组验证 list($name1, $name2) = explode('.', $key); $value = isset($data[$name1][$name2]) ? $data[$name1][$name2] : null; } else { $value = isset($data[$key]) ? $data[$key] : null; } + return $value; } /** * 获取验证规则的错误提示信息 * @access protected - * @param string $attribute 字段英文名 - * @param string $title 字段描述名 - * @param string $type 验证规则名称 - * @param mixed $rule 验证规则数据 + * @param string $attribute 字段英文名 + * @param string $title 字段描述名 + * @param string $type 验证规则名称 + * @param mixed $rule 验证规则数据 * @return string */ protected function getRuleMsg($attribute, $title, $type, $rule) { + $lang = Container::get('lang'); + if (isset($this->message[$attribute . '.' . $type])) { $msg = $this->message[$attribute . '.' . $type]; + } elseif (isset($this->message[$attribute][$type])) { + $msg = $this->message[$attribute][$type]; } elseif (isset($this->message[$attribute])) { $msg = $this->message[$attribute]; } elseif (isset(self::$typeMsg[$type])) { $msg = self::$typeMsg[$type]; + } elseif (0 === strpos($type, 'require')) { + $msg = self::$typeMsg['require']; } else { - $msg = $title . '规则错误'; + $msg = $title . $lang->get('not conform to the rules'); } - // TODO 多语言支持 - if (is_string($msg) && false !== strpos($msg, ':')) { + + if (is_string($msg) && 0 === strpos($msg, '{%')) { + $msg = $lang->get(substr($msg, 2, -1)); + } elseif ($lang->has($msg)) { + $msg = $lang->get($msg); + } + + if (is_string($msg) && is_scalar($rule) && false !== strpos($msg, ':')) { // 变量替换 - if (strpos($rule, ',')) { + if (is_string($rule) && strpos($rule, ',')) { $array = array_pad(explode(',', $rule), 3, ''); } else { $array = array_pad([], 3, ''); @@ -1176,14 +1435,15 @@ class Validate [$title, (string) $rule, $array[0], $array[1], $array[2]], $msg); } + return $msg; } /** * 获取数据验证的场景 * @access protected - * @param string $scene 验证场景 - * @return array + * @param string $scene 验证场景 + * @return void */ protected function getScene($scene = '') { @@ -1192,25 +1452,41 @@ class Validate $scene = $this->currentScene; } - if (!empty($scene) && isset($this->scene[$scene])) { + if (empty($scene)) { + return; + } + + $this->only = $this->append = $this->remove = []; + + if (method_exists($this, 'scene' . $scene)) { + call_user_func([$this, 'scene' . $scene]); + } elseif (isset($this->scene[$scene])) { // 如果设置了验证适用场景 $scene = $this->scene[$scene]; + if (is_string($scene)) { $scene = explode(',', $scene); } - } else { - $scene = []; + + $this->only = $scene; } - return $scene; } - public static function __callStatic($method, $params) + /** + * 动态方法 直接调用is方法进行验证 + * @access public + * @param string $method 方法名 + * @param array $args 调用参数 + * @return bool + */ + public function __call($method, $args) { - $class = new static; - if (method_exists($class, $method)) { - return call_user_func_array([$class, $method], $params); - } else { - throw new \BadMethodCallException('method not exists:' . __CLASS__ . '->' . $method); + if ('is' == strtolower(substr($method, 0, 2))) { + $method = substr($method, 2); } + + array_push($args, lcfirst($method)); + + return call_user_func_array([$this, 'is'], $args); } } diff --git a/library/think/View.php b/library/think/View.php index da087036dcd2376c785cb4be141aedc7acedc9ea..4212438f9a7751dce537ced52c744c5b4b9e7217 100644 --- a/library/think/View.php +++ b/library/think/View.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,48 +13,72 @@ namespace think; class View { - // 视图实例 - protected static $instance; - // 模板引擎实例 + /** + * 模板引擎实例 + * @var object + */ public $engine; - // 模板变量 + + /** + * 模板变量 + * @var array + */ protected $data = []; - // 视图输出替换 - protected $replace = []; /** - * 架构函数 + * 内容过滤 + * @var mixed + */ + protected $filter; + + /** + * 全局模板变量 + * @var array + */ + protected static $var = []; + + /** + * 初始化 * @access public - * @param array $engine 模板引擎参数 - * @param array $replace 字符串替换参数 + * @param mixed $engine 模板引擎参数 + * @return $this */ - public function __construct($engine = [], $replace = []) + public function init($engine = []) { // 初始化模板引擎 - $this->engine((array) $engine); - $this->replace = $replace; + $this->engine($engine); + + return $this; + } + + public static function __make(Config $config) + { + return (new static())->init($config->pull('template')); } /** - * 初始化视图 + * 模板变量静态赋值 * @access public - * @param array $engine 模板引擎参数 - * @param array $replace 字符串替换参数 - * @return object + * @param mixed $name 变量名 + * @param mixed $value 变量值 + * @return $this */ - public static function instance($engine = [], $replace = []) + public function share($name, $value = '') { - if (is_null(self::$instance)) { - self::$instance = new self($engine, $replace); + if (is_array($name)) { + self::$var = array_merge(self::$var, $name); + } else { + self::$var[$name] = $value; } - return self::$instance; + + return $this; } /** * 模板变量赋值 * @access public - * @param mixed $name 变量名 - * @param mixed $value 变量值 + * @param mixed $name 变量名 + * @param mixed $value 变量值 * @return $this */ public function assign($name, $value = '') @@ -64,13 +88,14 @@ class View } else { $this->data[$name] = $value; } + return $this; } /** * 设置当前模板解析的引擎 * @access public - * @param array|string $options 引擎参数 + * @param array|string $options 引擎参数 * @return $this */ public function engine($options = []) @@ -82,98 +107,108 @@ class View $type = !empty($options['type']) ? $options['type'] : 'Think'; } - $class = false !== strpos($type, '\\') ? $type : '\\think\\view\\driver\\' . ucfirst($type); if (isset($options['type'])) { unset($options['type']); } - $this->engine = new $class($options); + + $this->engine = Loader::factory($type, '\\think\\view\\driver\\', $options); + return $this; } /** * 配置模板引擎 - * @access private - * @param string|array $name 参数名 - * @param mixed $value 参数值 - * @return void + * @access public + * @param string|array $name 参数名 + * @param mixed $value 参数值 + * @return $this */ public function config($name, $value = null) { $this->engine->config($name, $value); + + return $this; + } + + /** + * 检查模板是否存在 + * @access public + * @param string|array $name 参数名 + * @return bool + */ + public function exists($name) + { + return $this->engine->exists($name); + } + + /** + * 视图过滤 + * @access public + * @param Callable $filter 过滤方法或闭包 + * @return $this + */ + public function filter($filter) + { + $this->filter = $filter; return $this; } /** * 解析和获取模板内容 用于输出 - * @param string $template 模板文件名或者内容 - * @param array $vars 模板输出变量 - * @param array $replace 替换内容 - * @param array $config 模板参数 - * @param bool $renderContent 是否渲染内容 + * @access public + * @param string $template 模板文件名或者内容 + * @param array $vars 模板输出变量 + * @param array $config 模板参数 + * @param bool $renderContent 是否渲染内容 * @return string - * @throws Exception + * @throws \Exception */ - public function fetch($template = '', $vars = [], $replace = [], $config = [], $renderContent = false) + public function fetch($template = '', $vars = [], $config = [], $renderContent = false) { // 模板变量 - $vars = array_merge($this->data, $vars); + $vars = array_merge(self::$var, $this->data, $vars); // 页面缓存 ob_start(); ob_implicit_flush(0); // 渲染输出 - $method = $renderContent ? 'display' : 'fetch'; - $this->engine->$method($template, $vars, $config); + try { + $method = $renderContent ? 'display' : 'fetch'; + $this->engine->$method($template, $vars, $config); + } catch (\Exception $e) { + ob_end_clean(); + throw $e; + } // 获取并清空缓存 $content = ob_get_clean(); - // 内容过滤标签 - Hook::listen('view_filter', $content); - // 允许用户自定义模板的字符串替换 - $replace = array_merge($this->replace, $replace); - if (!empty($replace)) { - $content = strtr($content, $replace); - } - return $content; - } - /** - * 视图内容替换 - * @access public - * @param string|array $content 被替换内容(支持批量替换) - * @param string $replace 替换内容 - * @return $this - */ - public function replace($content, $replace = '') - { - if (is_array($content)) { - $this->replace = array_merge($this->replace, $content); - } else { - $this->replace[$content] = $replace; + if ($this->filter) { + $content = call_user_func_array($this->filter, [$content]); } - return $this; + + return $content; } /** * 渲染内容输出 * @access public - * @param string $content 内容 - * @param array $vars 模板输出变量 - * @param array $replace 替换内容 - * @param array $config 模板参数 + * @param string $content 内容 + * @param array $vars 模板输出变量 + * @param array $config 模板参数 * @return mixed */ - public function display($content, $vars = [], $replace = [], $config = []) + public function display($content, $vars = [], $config = []) { - return $this->fetch($content, $vars, $replace, $config, true); + return $this->fetch($content, $vars, $config, true); } /** * 模板变量赋值 * @access public - * @param string $name 变量名 - * @param mixed $value 变量值 + * @param string $name 变量名 + * @param mixed $value 变量值 */ public function __set($name, $value) { @@ -183,7 +218,7 @@ class View /** * 取得模板显示变量的值 * @access protected - * @param string $name 模板变量 + * @param string $name 模板变量 * @return mixed */ public function __get($name) @@ -194,7 +229,7 @@ class View /** * 检测模板变量是否设置 * @access public - * @param string $name 模板变量名 + * @param string $name 模板变量名 * @return bool */ public function __isset($name) diff --git a/library/think/cache/Driver.php b/library/think/cache/Driver.php index e0aeb7bc2e84628c3a46acfb3ba15d7a3a57d025..f0ec7baf407407b4976fd7dfc1249f29ac7233b6 100644 --- a/library/think/cache/Driver.php +++ b/library/think/cache/Driver.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,19 +11,53 @@ namespace think\cache; +use think\Container; + /** * 缓存基础类 */ abstract class Driver { + /** + * 驱动句柄 + * @var object + */ protected $handler = null; + + /** + * 缓存读取次数 + * @var integer + */ + protected $readTimes = 0; + + /** + * 缓存写入次数 + * @var integer + */ + protected $writeTimes = 0; + + /** + * 缓存参数 + * @var array + */ protected $options = []; + + /** + * 缓存标签 + * @var string + */ protected $tag; + /** + * 序列化方法 + * @var array + */ + protected static $serialize = ['serialize', 'unserialize', 'think_serialize:', 16]; + /** * 判断缓存是否存在 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return bool */ abstract public function has($name); @@ -31,8 +65,8 @@ abstract class Driver /** * 读取缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $default 默认值 + * @param string $name 缓存变量名 + * @param mixed $default 默认值 * @return mixed */ abstract public function get($name, $default = false); @@ -40,9 +74,9 @@ abstract class Driver /** * 写入缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $value 存储数据 - * @param int $expire 有效时间 0为永久 + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param int $expire 有效时间 0为永久 * @return boolean */ abstract public function set($name, $value, $expire = null); @@ -50,8 +84,8 @@ abstract class Driver /** * 自增缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ abstract public function inc($name, $step = 1); @@ -59,8 +93,8 @@ abstract class Driver /** * 自减缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ abstract public function dec($name, $step = 1); @@ -68,7 +102,7 @@ abstract class Driver /** * 删除缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return boolean */ abstract public function rm($name); @@ -76,15 +110,30 @@ abstract class Driver /** * 清除缓存 * @access public - * @param string $tag 标签名 + * @param string $tag 标签名 * @return boolean */ abstract public function clear($tag = null); + /** + * 获取有效期 + * @access protected + * @param integer|\DateTime $expire 有效期 + * @return integer + */ + protected function getExpireTime($expire) + { + if ($expire instanceof \DateTime) { + $expire = $expire->getTimestamp() - time(); + } + + return $expire; + } + /** * 获取实际的缓存标识 - * @access public - * @param string $name 缓存名 + * @access protected + * @param string $name 缓存名 * @return string */ protected function getCacheKey($name) @@ -95,86 +144,192 @@ abstract class Driver /** * 读取缓存并删除 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return mixed */ public function pull($name) { $result = $this->get($name, false); + if ($result) { $this->rm($name); return $result; } else { - return null; + return; + } + } + + /** + * 如果不存在则写入缓存 + * @access public + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param int $expire 有效时间 0为永久 + * @return mixed + */ + public function remember($name, $value, $expire = null) + { + if (!$this->has($name)) { + $time = time(); + while ($time + 5 > time() && $this->has($name . '_lock')) { + // 存在锁定则等待 + usleep(200000); + } + + try { + // 锁定 + $this->set($name . '_lock', true); + + if ($value instanceof \Closure) { + // 获取缓存数据 + $value = Container::getInstance()->invokeFunction($value); + } + + // 缓存数据 + $this->set($name, $value, $expire); + + // 解锁 + $this->rm($name . '_lock'); + } catch (\Exception $e) { + $this->rm($name . '_lock'); + throw $e; + } catch (\throwable $e) { + $this->rm($name . '_lock'); + throw $e; + } + } else { + $value = $this->get($name); } + + return $value; } /** * 缓存标签 * @access public - * @param string $name 标签名 - * @param string|array $keys 缓存标识 - * @param bool $overlay 是否覆盖 + * @param string $name 标签名 + * @param string|array $keys 缓存标识 + * @param bool $overlay 是否覆盖 * @return $this */ public function tag($name, $keys = null, $overlay = false) { - if (is_null($keys)) { + if (is_null($name)) { + + } elseif (is_null($keys)) { $this->tag = $name; } else { $key = 'tag_' . md5($name); + if (is_string($keys)) { $keys = explode(',', $keys); } + $keys = array_map([$this, 'getCacheKey'], $keys); + if ($overlay) { $value = $keys; } else { $value = array_unique(array_merge($this->getTagItem($name), $keys)); } - $this->set($key, implode(',', $value)); + + $this->set($key, implode(',', $value), 0); } + return $this; } /** * 更新标签 - * @access public - * @param string $name 缓存标识 + * @access protected + * @param string $name 缓存标识 * @return void */ protected function setTagItem($name) { if ($this->tag) { $key = 'tag_' . md5($this->tag); + $prev = $this->tag; $this->tag = null; + if ($this->has($key)) { - $value = $this->get($key); - $value .= ',' . $name; + $value = explode(',', $this->get($key)); + $value[] = $name; + $value = implode(',', array_unique($value)); } else { $value = $name; } - $this->set($key, $value); + + $this->set($key, $value, 0); + $this->tag = $prev; } } /** * 获取标签包含的缓存标识 - * @access public - * @param string $tag 缓存标签 + * @access protected + * @param string $tag 缓存标签 * @return array */ protected function getTagItem($tag) { $key = 'tag_' . md5($tag); $value = $this->get($key); + if ($value) { - return explode(',', $value); + return array_filter(explode(',', $value)); } else { return []; } } + /** + * 序列化数据 + * @access protected + * @param mixed $data + * @return string + */ + protected function serialize($data) + { + if (is_scalar($data) || !$this->options['serialize']) { + return $data; + } + + $serialize = self::$serialize[0]; + + return self::$serialize[2] . $serialize($data); + } + + /** + * 反序列化数据 + * @access protected + * @param string $data + * @return mixed + */ + protected function unserialize($data) + { + if ($this->options['serialize'] && 0 === strpos($data, self::$serialize[2])) { + $unserialize = self::$serialize[1]; + + return $unserialize(substr($data, self::$serialize[3])); + } else { + return $data; + } + } + + /** + * 注册序列化机制 + * @access public + * @param callable $serialize 序列化方法 + * @param callable $unserialize 反序列化方法 + * @param string $prefix 序列化前缀标识 + * @return $this + */ + public static function registerSerialize($serialize, $unserialize, $prefix = 'think_serialize:') + { + self::$serialize = [$serialize, $unserialize, $prefix, strlen($prefix)]; + } + /** * 返回句柄对象,可执行其它高级方法 * @@ -185,4 +340,14 @@ abstract class Driver { return $this->handler; } + + public function getReadTimes() + { + return $this->readTimes; + } + + public function getWriteTimes() + { + return $this->writeTimes; + } } diff --git a/library/think/cache/driver/File.php b/library/think/cache/driver/File.php index 5c98d799c30309ade0b4b8c7676d4fdc2204cb52..7c5661e3d7c1e7972bbd7dce12e5cc3c1b2dfe33 100644 --- a/library/think/cache/driver/File.php +++ b/library/think/cache/driver/File.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,6 +12,7 @@ namespace think\cache\driver; use think\cache\Driver; +use think\Container; /** * 文件类型缓存类 @@ -21,12 +22,16 @@ class File extends Driver { protected $options = [ 'expire' => 0, - 'cache_subdir' => false, + 'cache_subdir' => true, 'prefix' => '', - 'path' => CACHE_PATH, + 'path' => '', + 'hash_type' => 'md5', 'data_compress' => false, + 'serialize' => true, ]; + protected $expire; + /** * 架构函数 * @param array $options @@ -36,9 +41,13 @@ class File extends Driver if (!empty($options)) { $this->options = array_merge($this->options, $options); } - if (substr($this->options['path'], -1) != DS) { - $this->options['path'] .= DS; + + if (empty($this->options['path'])) { + $this->options['path'] = Container::get('app')->getRuntimePath() . 'cache' . DIRECTORY_SEPARATOR; + } elseif (substr($this->options['path'], -1) != DIRECTORY_SEPARATOR) { + $this->options['path'] .= DIRECTORY_SEPARATOR; } + $this->init(); } @@ -50,77 +59,96 @@ class File extends Driver private function init() { // 创建项目缓存目录 - if (!is_dir($this->options['path'])) { - if (mkdir($this->options['path'], 0755, true)) { + try { + if (!is_dir($this->options['path']) && mkdir($this->options['path'], 0755, true)) { return true; } + } catch (\Exception $e) { } + return false; } /** * 取得变量的存储文件名 * @access protected - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 + * @param bool $auto 是否自动创建目录 * @return string */ - protected function getCacheKey($name) + protected function getCacheKey($name, $auto = false) { - $name = md5($name); + $name = hash($this->options['hash_type'], $name); + if ($this->options['cache_subdir']) { // 使用子目录 - $name = substr($name, 0, 2) . DS . substr($name, 2); + $name = substr($name, 0, 2) . DIRECTORY_SEPARATOR . substr($name, 2); } + if ($this->options['prefix']) { - $name = $this->options['prefix'] . DS . $name; + $name = $this->options['prefix'] . DIRECTORY_SEPARATOR . $name; } + $filename = $this->options['path'] . $name . '.php'; $dir = dirname($filename); - if (!is_dir($dir)) { - mkdir($dir, 0755, true); + + if ($auto && !is_dir($dir)) { + try { + mkdir($dir, 0755, true); + } catch (\Exception $e) { + } } + return $filename; } /** * 判断缓存是否存在 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return bool */ public function has($name) { - return $this->get($name) ? true : false; + return false !== $this->get($name) ? true : false; } /** * 读取缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $default 默认值 + * @param string $name 缓存变量名 + * @param mixed $default 默认值 * @return mixed */ public function get($name, $default = false) { + $this->readTimes++; + $filename = $this->getCacheKey($name); + if (!is_file($filename)) { return $default; } - $content = file_get_contents($filename); + + $content = file_get_contents($filename); + $this->expire = null; + if (false !== $content) { $expire = (int) substr($content, 8, 12); - if (0 != $expire && $_SERVER['REQUEST_TIME'] > filemtime($filename) + $expire) { + if (0 != $expire && time() > filemtime($filename) + $expire) { //缓存过期删除缓存文件 $this->unlink($filename); return $default; } - $content = substr($content, 20, -3); + + $this->expire = $expire; + $content = substr($content, 32); + if ($this->options['data_compress'] && function_exists('gzcompress')) { //启用数据压缩 $content = gzuncompress($content); } - $content = unserialize($content); - return $content; + return $this->unserialize($content); } else { return $default; } @@ -129,27 +157,36 @@ class File extends Driver /** * 写入缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $value 存储数据 - * @param int $expire 有效时间 0为永久 + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param int|\DateTime $expire 有效时间 0为永久 * @return boolean */ public function set($name, $value, $expire = null) { + $this->writeTimes++; + if (is_null($expire)) { $expire = $this->options['expire']; } - $filename = $this->getCacheKey($name); + + $expire = $this->getExpireTime($expire); + $filename = $this->getCacheKey($name, true); + if ($this->tag && !is_file($filename)) { $first = true; } - $data = serialize($value); + + $data = $this->serialize($value); + if ($this->options['data_compress'] && function_exists('gzcompress')) { //数据压缩 $data = gzcompress($data, 3); } - $data = ""; + + $data = "\n" . $data; $result = file_put_contents($filename, $data); + if ($result) { isset($first) && $this->setTagItem($filename); clearstatcache(); @@ -162,52 +199,63 @@ class File extends Driver /** * 自增缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function inc($name, $step = 1) { if ($this->has($name)) { - $value = $this->get($name) + $step; + $value = $this->get($name) + $step; + $expire = $this->expire; } else { - $value = $step; + $value = $step; + $expire = 0; } - return $this->set($name, $value, 0) ? $value : false; + + return $this->set($name, $value, $expire) ? $value : false; } /** * 自减缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function dec($name, $step = 1) { if ($this->has($name)) { - $value = $this->get($name) - $step; + $value = $this->get($name) - $step; + $expire = $this->expire; } else { - $value = $step; + $value = -$step; + $expire = 0; } - return $this->set($name, $value, 0) ? $value : false; + + return $this->set($name, $value, $expire) ? $value : false; } /** * 删除缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return boolean */ public function rm($name) { - return $this->unlink($this->getCacheKey($name)); + $this->writeTimes++; + + try { + return $this->unlink($this->getCacheKey($name)); + } catch (\Exception $e) { + } } /** * 清除缓存 * @access public - * @param string $tag 标签名 + * @param string $tag 标签名 * @return boolean */ public function clear($tag = null) @@ -221,20 +269,30 @@ class File extends Driver $this->rm('tag_' . md5($tag)); return true; } - $files = (array) glob($this->options['path'] . ($this->options['prefix'] ? $this->options['prefix'] . DS : '') . '*'); + + $this->writeTimes++; + + $files = (array) glob($this->options['path'] . ($this->options['prefix'] ? $this->options['prefix'] . DIRECTORY_SEPARATOR : '') . '*'); + foreach ($files as $path) { if (is_dir($path)) { - array_map('unlink', glob($path . '/*.php')); + $matches = glob($path . DIRECTORY_SEPARATOR . '*.php'); + if (is_array($matches)) { + array_map('unlink', $matches); + } + rmdir($path); } else { unlink($path); } } + return true; } /** * 判断文件是否存在后,删除 - * @param $path + * @access private + * @param string $path * @return bool * @author byron sampson * @return boolean diff --git a/library/think/cache/driver/Lite.php b/library/think/cache/driver/Lite.php index b9d100971e5c25120738d896a09304c0557f7b75..544663c057ed6ac4ec512260125c6590ca954162 100644 --- a/library/think/cache/driver/Lite.php +++ b/library/think/cache/driver/Lite.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -29,15 +29,16 @@ class Lite extends Driver * 架构函数 * @access public * - * @param array $options + * @param array $options */ public function __construct($options = []) { if (!empty($options)) { $this->options = array_merge($this->options, $options); } - if (substr($this->options['path'], -1) != DS) { - $this->options['path'] .= DS; + + if (substr($this->options['path'], -1) != DIRECTORY_SEPARATOR) { + $this->options['path'] .= DIRECTORY_SEPARATOR; } } @@ -45,7 +46,7 @@ class Lite extends Driver /** * 取得变量的存储文件名 * @access protected - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return string */ protected function getCacheKey($name) @@ -56,7 +57,7 @@ class Lite extends Driver /** * 判断缓存是否存在 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return mixed */ public function has($name) @@ -67,21 +68,26 @@ class Lite extends Driver /** * 读取缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $default 默认值 + * @param string $name 缓存变量名 + * @param mixed $default 默认值 * @return mixed */ public function get($name, $default = false) { + $this->readTimes++; + $filename = $this->getCacheKey($name); + if (is_file($filename)) { // 判断是否过期 $mtime = filemtime($filename); - if ($mtime < $_SERVER['REQUEST_TIME']) { + + if ($mtime < time()) { // 清除已经过期的文件 unlink($filename); return $default; } + return include $filename; } else { return $default; @@ -90,39 +96,49 @@ class Lite extends Driver /** * 写入缓存 - * @access public - * @param string $name 缓存变量名 - * @param mixed $value 存储数据 - * @param int $expire 有效时间 0为永久 + * @access public + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param int|\DateTime $expire 有效时间 0为永久 * @return bool */ public function set($name, $value, $expire = null) { + $this->writeTimes++; + if (is_null($expire)) { $expire = $this->options['expire']; } - // 模拟永久 - if (0 === $expire) { - $expire = 10 * 365 * 24 * 3600; + + if ($expire instanceof \DateTime) { + $expire = $expire->getTimestamp(); + } else { + $expire = 0 === $expire ? 10 * 365 * 24 * 3600 : $expire; + $expire = time() + $expire; } + $filename = $this->getCacheKey($name); + if ($this->tag && !is_file($filename)) { $first = true; } + $ret = file_put_contents($filename, ("setTagItem($filename); - touch($filename, $_SERVER['REQUEST_TIME'] + $expire); + touch($filename, $expire); } + return $ret; } /** * 自增缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function inc($name, $step = 1) @@ -132,14 +148,15 @@ class Lite extends Driver } else { $value = $step; } + return $this->set($name, $value, 0) ? $value : false; } /** * 自减缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function dec($name, $step = 1) @@ -147,26 +164,29 @@ class Lite extends Driver if ($this->has($name)) { $value = $this->get($name) - $step; } else { - $value = $step; + $value = -$step; } + return $this->set($name, $value, 0) ? $value : false; } /** * 删除缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return boolean */ public function rm($name) { + $this->writeTimes++; + return unlink($this->getCacheKey($name)); } /** * 清除缓存 - * @access public - * @param string $tag 标签名 + * @access public + * @param string $tag 标签名 * @return bool */ public function clear($tag = null) @@ -177,9 +197,13 @@ class Lite extends Driver foreach ($keys as $key) { unlink($key); } + $this->rm('tag_' . md5($tag)); return true; } - array_map("unlink", glob($this->options['path'] . ($this->options['prefix'] ? $this->options['prefix'] . DS : '') . '*.php')); + + $this->writeTimes++; + + array_map("unlink", glob($this->options['path'] . ($this->options['prefix'] ? $this->options['prefix'] . DIRECTORY_SEPARATOR : '') . '*.php')); } } diff --git a/library/think/cache/driver/Memcache.php b/library/think/cache/driver/Memcache.php index bddf71573472e7586978fa86aa522b911925135e..ea2c0e234e4d6350a415ce5cae138955a54b4484 100644 --- a/library/think/cache/driver/Memcache.php +++ b/library/think/cache/driver/Memcache.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,7 +12,6 @@ namespace think\cache\driver; use think\cache\Driver; -use think\Exception; class Memcache extends Driver { @@ -23,12 +22,13 @@ class Memcache extends Driver 'timeout' => 0, // 超时时间(单位:毫秒) 'persistent' => true, 'prefix' => '', + 'serialize' => true, ]; /** * 架构函数 - * @param array $options 缓存参数 * @access public + * @param array $options 缓存参数 * @throws \BadFunctionCallException */ public function __construct($options = []) @@ -36,16 +36,21 @@ class Memcache extends Driver if (!extension_loaded('memcache')) { throw new \BadFunctionCallException('not support: memcache'); } + if (!empty($options)) { $this->options = array_merge($this->options, $options); } + $this->handler = new \Memcache; + // 支持集群 $hosts = explode(',', $this->options['host']); $ports = explode(',', $this->options['port']); + if (empty($ports[0])) { $ports[0] = 11211; } + // 建立连接 foreach ((array) $hosts as $i => $host) { $port = isset($ports[$i]) ? $ports[$i] : $ports[0]; @@ -58,93 +63,115 @@ class Memcache extends Driver /** * 判断缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return bool */ public function has($name) { $key = $this->getCacheKey($name); + return $this->handler->get($key) ? true : false; } /** * 读取缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $default 默认值 + * @param string $name 缓存变量名 + * @param mixed $default 默认值 * @return mixed */ public function get($name, $default = false) { + $this->readTimes++; + $result = $this->handler->get($this->getCacheKey($name)); - return false !== $result ? $result : $default; + + return false !== $result ? $this->unserialize($result) : $default; } /** * 写入缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $value 存储数据 - * @param integer $expire 有效时间(秒) + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param int|DateTime $expire 有效时间(秒) * @return bool */ public function set($name, $value, $expire = null) { + $this->writeTimes++; + if (is_null($expire)) { $expire = $this->options['expire']; } + if ($this->tag && !$this->has($name)) { $first = true; } - $key = $this->getCacheKey($name); + + $key = $this->getCacheKey($name); + $expire = $this->getExpireTime($expire); + $value = $this->serialize($value); + if ($this->handler->set($key, $value, 0, $expire)) { isset($first) && $this->setTagItem($key); return true; } + return false; } /** * 自增缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function inc($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); - return $this->handler->increment($key, $step); + + if ($this->handler->get($key)) { + return $this->handler->increment($key, $step); + } + + return $this->handler->set($key, $step); } /** * 自减缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function dec($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); $value = $this->handler->get($key) - $step; $res = $this->handler->set($key, $value); - if (!$res) { - return false; - } else { - return $value; - } + + return !$res ? false : $value; } /** * 删除缓存 - * @param string $name 缓存变量名 - * @param bool|false $ttl + * @access public + * @param string $name 缓存变量名 + * @param bool|false $ttl * @return bool */ public function rm($name, $ttl = false) { + $this->writeTimes++; + $key = $this->getCacheKey($name); + return false === $ttl ? $this->handler->delete($key) : $this->handler->delete($key, $ttl); @@ -153,7 +180,7 @@ class Memcache extends Driver /** * 清除缓存 * @access public - * @param string $tag 标签名 + * @param string $tag 标签名 * @return bool */ public function clear($tag = null) @@ -164,9 +191,13 @@ class Memcache extends Driver foreach ($keys as $key) { $this->handler->delete($key); } + $this->rm('tag_' . md5($tag)); return true; } + + $this->writeTimes++; + return $this->handler->flush(); } } diff --git a/library/think/cache/driver/Memcached.php b/library/think/cache/driver/Memcached.php index 4c4505b0822fb4bed8e58acf8c6e38ad2af3a076..d04fac0877796387b5e4eb2eede0320edbf1488f 100644 --- a/library/think/cache/driver/Memcached.php +++ b/library/think/cache/driver/Memcached.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -16,49 +16,58 @@ use think\cache\Driver; class Memcached extends Driver { protected $options = [ - 'host' => '127.0.0.1', - 'port' => 11211, - 'expire' => 0, - 'timeout' => 0, // 超时时间(单位:毫秒) - 'prefix' => '', - 'username' => '', //账号 - 'password' => '', //密码 - 'option' => [], + 'host' => '127.0.0.1', + 'port' => 11211, + 'expire' => 0, + 'timeout' => 0, // 超时时间(单位:毫秒) + 'prefix' => '', + 'username' => '', //账号 + 'password' => '', //密码 + 'option' => [], + 'serialize' => true, ]; /** * 架构函数 - * @param array $options 缓存参数 * @access public + * @param array $options 缓存参数 */ public function __construct($options = []) { if (!extension_loaded('memcached')) { throw new \BadFunctionCallException('not support: memcached'); } + if (!empty($options)) { $this->options = array_merge($this->options, $options); } + $this->handler = new \Memcached; + if (!empty($this->options['option'])) { $this->handler->setOptions($this->options['option']); } + // 设置连接超时时间(单位:毫秒) if ($this->options['timeout'] > 0) { $this->handler->setOption(\Memcached::OPT_CONNECT_TIMEOUT, $this->options['timeout']); } + // 支持集群 $hosts = explode(',', $this->options['host']); $ports = explode(',', $this->options['port']); if (empty($ports[0])) { $ports[0] = 11211; } + // 建立连接 $servers = []; foreach ((array) $hosts as $i => $host) { $servers[] = [$host, (isset($ports[$i]) ? $ports[$i] : $ports[0]), 1]; } + $this->handler->addServers($servers); + if ('' != $this->options['username']) { $this->handler->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); $this->handler->setSaslAuthData($this->options['username'], $this->options['password']); @@ -68,94 +77,115 @@ class Memcached extends Driver /** * 判断缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return bool */ public function has($name) { $key = $this->getCacheKey($name); + return $this->handler->get($key) ? true : false; } /** * 读取缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $default 默认值 + * @param string $name 缓存变量名 + * @param mixed $default 默认值 * @return mixed */ public function get($name, $default = false) { + $this->readTimes++; + $result = $this->handler->get($this->getCacheKey($name)); - return false !== $result ? $result : $default; + + return false !== $result ? $this->unserialize($result) : $default; } /** * 写入缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $value 存储数据 - * @param integer $expire 有效时间(秒) + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param integer|\DateTime $expire 有效时间(秒) * @return bool */ public function set($name, $value, $expire = null) { + $this->writeTimes++; + if (is_null($expire)) { $expire = $this->options['expire']; } + if ($this->tag && !$this->has($name)) { $first = true; } + $key = $this->getCacheKey($name); - $expire = 0 == $expire ? 0 : $_SERVER['REQUEST_TIME'] + $expire; + $expire = $this->getExpireTime($expire); + $value = $this->serialize($value); + if ($this->handler->set($key, $value, $expire)) { isset($first) && $this->setTagItem($key); return true; } + return false; } /** * 自增缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function inc($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); - return $this->handler->increment($key, $step); + + if ($this->handler->get($key)) { + return $this->handler->increment($key, $step); + } + + return $this->handler->set($key, $step); } /** * 自减缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function dec($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); $value = $this->handler->get($key) - $step; $res = $this->handler->set($key, $value); - if (!$res) { - return false; - } else { - return $value; - } + + return !$res ? false : $value; } /** * 删除缓存 - * @param string $name 缓存变量名 - * @param bool|false $ttl + * @access public + * @param string $name 缓存变量名 + * @param bool|false $ttl * @return bool */ public function rm($name, $ttl = false) { + $this->writeTimes++; + $key = $this->getCacheKey($name); + return false === $ttl ? $this->handler->delete($key) : $this->handler->delete($key, $ttl); @@ -164,7 +194,7 @@ class Memcached extends Driver /** * 清除缓存 * @access public - * @param string $tag 标签名 + * @param string $tag 标签名 * @return bool */ public function clear($tag = null) @@ -172,10 +202,15 @@ class Memcached extends Driver if ($tag) { // 指定标签清除 $keys = $this->getTagItem($tag); + $this->handler->deleteMulti($keys); $this->rm('tag_' . md5($tag)); + return true; } + + $this->writeTimes++; + return $this->handler->flush(); } } diff --git a/library/think/cache/driver/Redis.php b/library/think/cache/driver/Redis.php index e7f7876261c014b39c48f32d5f4c200d07b38ee3..d20d3b1d18a5598e24d660313a2d78a053a52c94 100644 --- a/library/think/cache/driver/Redis.php +++ b/library/think/cache/driver/Redis.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -31,132 +31,166 @@ class Redis extends Driver 'expire' => 0, 'persistent' => false, 'prefix' => '', + 'serialize' => true, ]; /** * 架构函数 - * @param array $options 缓存参数 * @access public + * @param array $options 缓存参数 */ public function __construct($options = []) { - if (!extension_loaded('redis')) { - throw new \BadFunctionCallException('not support: redis'); - } if (!empty($options)) { $this->options = array_merge($this->options, $options); } - $func = $this->options['persistent'] ? 'pconnect' : 'connect'; - $this->handler = new \Redis; - $this->handler->$func($this->options['host'], $this->options['port'], $this->options['timeout']); - if ('' != $this->options['password']) { - $this->handler->auth($this->options['password']); - } + if (extension_loaded('redis')) { + $this->handler = new \Redis; + + if ($this->options['persistent']) { + $this->handler->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']); + } else { + $this->handler->connect($this->options['host'], $this->options['port'], $this->options['timeout']); + } + + if ('' != $this->options['password']) { + $this->handler->auth($this->options['password']); + } - if (0 != $this->options['select']) { - $this->handler->select($this->options['select']); + if (0 != $this->options['select']) { + $this->handler->select($this->options['select']); + } + } elseif (class_exists('\Predis\Client')) { + $params = []; + foreach ($this->options as $key => $val) { + if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication'])) { + $params[$key] = $val; + unset($this->options[$key]); + } + } + $this->handler = new \Predis\Client($this->options, $params); + } else { + throw new \BadFunctionCallException('not support: redis'); } } /** * 判断缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return bool */ public function has($name) { - return $this->handler->get($this->getCacheKey($name)) ? true : false; + return $this->handler->exists($this->getCacheKey($name)); } /** * 读取缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $default 默认值 + * @param string $name 缓存变量名 + * @param mixed $default 默认值 * @return mixed */ public function get($name, $default = false) { + $this->readTimes++; + $value = $this->handler->get($this->getCacheKey($name)); - if (is_null($value)) { + + if (is_null($value) || false === $value) { return $default; } - $jsonData = json_decode($value, true); - // 检测是否为JSON数据 true 返回JSON解析数组, false返回源数据 byron sampson - return (null === $jsonData) ? $value : $jsonData; + + return $this->unserialize($value); } /** * 写入缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $value 存储数据 - * @param integer $expire 有效时间(秒) + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param integer|\DateTime $expire 有效时间(秒) * @return boolean */ public function set($name, $value, $expire = null) { + $this->writeTimes++; + if (is_null($expire)) { $expire = $this->options['expire']; } + if ($this->tag && !$this->has($name)) { $first = true; } - $key = $this->getCacheKey($name); - //对数组/对象数据进行缓存处理,保证数据完整性 byron sampson - $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value; - if (is_int($expire) && $expire) { + + $key = $this->getCacheKey($name); + $expire = $this->getExpireTime($expire); + + $value = $this->serialize($value); + + if ($expire) { $result = $this->handler->setex($key, $expire, $value); } else { $result = $this->handler->set($key, $value); } + isset($first) && $this->setTagItem($key); + return $result; } /** * 自增缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function inc($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); + return $this->handler->incrby($key, $step); } /** * 自减缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function dec($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); + return $this->handler->decrby($key, $step); } /** * 删除缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return boolean */ public function rm($name) { + $this->writeTimes++; + return $this->handler->delete($this->getCacheKey($name)); } /** * 清除缓存 * @access public - * @param string $tag 标签名 + * @param string $tag 标签名 * @return boolean */ public function clear($tag = null) @@ -164,12 +198,17 @@ class Redis extends Driver if ($tag) { // 指定标签清除 $keys = $this->getTagItem($tag); + foreach ($keys as $key) { $this->handler->delete($key); } + $this->rm('tag_' . md5($tag)); return true; } + + $this->writeTimes++; + return $this->handler->flushDB(); } diff --git a/library/think/cache/driver/Sqlite.php b/library/think/cache/driver/Sqlite.php index 6dbd41fed15393aab11c7f489837528c8ca0ede6..7e78ec12d2e72d149b35373550864eafffcb39fc 100644 --- a/library/think/cache/driver/Sqlite.php +++ b/library/think/cache/driver/Sqlite.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,7 +12,6 @@ namespace think\cache\driver; use think\cache\Driver; -use think\Exception; /** * Sqlite缓存驱动 @@ -26,30 +25,34 @@ class Sqlite extends Driver 'prefix' => '', 'expire' => 0, 'persistent' => false, + 'serialize' => true, ]; /** * 架构函数 - * @param array $options 缓存参数 - * @throws \BadFunctionCallException * @access public + * @param array $options 缓存参数 + * @throws \BadFunctionCallException */ public function __construct($options = []) { if (!extension_loaded('sqlite')) { throw new \BadFunctionCallException('not support: sqlite'); } + if (!empty($options)) { $this->options = array_merge($this->options, $options); } - $func = $this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open'; + + $func = $this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open'; + $this->handler = $func($this->options['db']); } /** * 获取实际的缓存标识 * @access public - * @param string $name 缓存名 + * @param string $name 缓存名 * @return string */ protected function getCacheKey($name) @@ -60,78 +63,101 @@ class Sqlite extends Driver /** * 判断缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return bool */ public function has($name) { - $name = $this->getCacheKey($name); - $sql = 'SELECT value FROM ' . $this->options['table'] . ' WHERE var=\'' . $name . '\' AND (expire=0 OR expire >' . $_SERVER['REQUEST_TIME'] . ') LIMIT 1'; + $name = $this->getCacheKey($name); + + $sql = 'SELECT value FROM ' . $this->options['table'] . ' WHERE var=\'' . $name . '\' AND (expire=0 OR expire >' . time() . ') LIMIT 1'; $result = sqlite_query($this->handler, $sql); + return sqlite_num_rows($result); } /** * 读取缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $default 默认值 + * @param string $name 缓存变量名 + * @param mixed $default 默认值 * @return mixed */ public function get($name, $default = false) { - $name = $this->getCacheKey($name); - $sql = 'SELECT value FROM ' . $this->options['table'] . ' WHERE var=\'' . $name . '\' AND (expire=0 OR expire >' . $_SERVER['REQUEST_TIME'] . ') LIMIT 1'; + $this->readTimes++; + + $name = $this->getCacheKey($name); + + $sql = 'SELECT value FROM ' . $this->options['table'] . ' WHERE var=\'' . $name . '\' AND (expire=0 OR expire >' . time() . ') LIMIT 1'; + $result = sqlite_query($this->handler, $sql); + if (sqlite_num_rows($result)) { $content = sqlite_fetch_single($result); if (function_exists('gzcompress')) { //启用数据压缩 $content = gzuncompress($content); } - return unserialize($content); + + return $this->unserialize($content); } + return $default; } /** * 写入缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $value 存储数据 - * @param integer $expire 有效时间(秒) + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param integer|\DateTime $expire 有效时间(秒) * @return boolean */ public function set($name, $value, $expire = null) { - $name = $this->getCacheKey($name); - $value = sqlite_escape_string(serialize($value)); + $this->writeTimes++; + + $name = $this->getCacheKey($name); + + $value = sqlite_escape_string($this->serialize($value)); + if (is_null($expire)) { $expire = $this->options['expire']; } - $expire = (0 == $expire) ? 0 : ($_SERVER['REQUEST_TIME'] + $expire); //缓存有效期为0表示永久缓存 + + if ($expire instanceof \DateTime) { + $expire = $expire->getTimestamp(); + } else { + $expire = (0 == $expire) ? 0 : (time() + $expire); //缓存有效期为0表示永久缓存 + } + if (function_exists('gzcompress')) { //数据压缩 $value = gzcompress($value, 3); } + if ($this->tag) { $tag = $this->tag; $this->tag = null; } else { $tag = ''; } + $sql = 'REPLACE INTO ' . $this->options['table'] . ' (var, value, expire, tag) VALUES (\'' . $name . '\', \'' . $value . '\', \'' . $expire . '\', \'' . $tag . '\')'; + if (sqlite_query($this->handler, $sql)) { return true; } + return false; } /** * 自增缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function inc($name, $step = 1) @@ -141,14 +167,15 @@ class Sqlite extends Driver } else { $value = $step; } + return $this->set($name, $value, 0) ? $value : false; } /** * 自减缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function dec($name, $step = 1) @@ -156,29 +183,34 @@ class Sqlite extends Driver if ($this->has($name)) { $value = $this->get($name) - $step; } else { - $value = $step; + $value = -$step; } + return $this->set($name, $value, 0) ? $value : false; } /** * 删除缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return boolean */ public function rm($name) { + $this->writeTimes++; + $name = $this->getCacheKey($name); - $sql = 'DELETE FROM ' . $this->options['table'] . ' WHERE var=\'' . $name . '\''; + + $sql = 'DELETE FROM ' . $this->options['table'] . ' WHERE var=\'' . $name . '\''; sqlite_query($this->handler, $sql); + return true; } /** * 清除缓存 * @access public - * @param string $tag 标签名 + * @param string $tag 标签名 * @return boolean */ public function clear($tag = null) @@ -189,8 +221,13 @@ class Sqlite extends Driver sqlite_query($this->handler, $sql); return true; } + + $this->writeTimes++; + $sql = 'DELETE FROM ' . $this->options['table']; + sqlite_query($this->handler, $sql); + return true; } } diff --git a/library/think/cache/driver/Wincache.php b/library/think/cache/driver/Wincache.php index a9cc7d22aae823c70c02350d49f1af005cbe84a9..10966e786cf8af77ea66c82f35fca7768c05f287 100644 --- a/library/think/cache/driver/Wincache.php +++ b/library/think/cache/driver/Wincache.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,7 +12,6 @@ namespace think\cache\driver; use think\cache\Driver; -use think\Exception; /** * Wincache缓存驱动 @@ -21,21 +20,23 @@ use think\Exception; class Wincache extends Driver { protected $options = [ - 'prefix' => '', - 'expire' => 0, + 'prefix' => '', + 'expire' => 0, + 'serialize' => true, ]; /** * 架构函数 - * @param array $options 缓存参数 - * @throws Exception * @access public + * @param array $options 缓存参数 + * @throws \BadFunctionCallException */ public function __construct($options = []) { if (!function_exists('wincache_ucache_info')) { throw new \BadFunctionCallException('not support: WinCache'); } + if (!empty($options)) { $this->options = array_merge($this->options, $options); } @@ -44,93 +45,115 @@ class Wincache extends Driver /** * 判断缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return bool */ public function has($name) { + $this->readTimes++; + $key = $this->getCacheKey($name); + return wincache_ucache_exists($key); } /** * 读取缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $default 默认值 + * @param string $name 缓存变量名 + * @param mixed $default 默认值 * @return mixed */ public function get($name, $default = false) { + $this->readTimes++; + $key = $this->getCacheKey($name); - return wincache_ucache_exists($key) ? wincache_ucache_get($key) : $default; + + return wincache_ucache_exists($key) ? $this->unserialize(wincache_ucache_get($key)) : $default; } /** * 写入缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $value 存储数据 - * @param integer $expire 有效时间(秒) + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param integer|\DateTime $expire 有效时间(秒) * @return boolean */ public function set($name, $value, $expire = null) { + $this->writeTimes++; + if (is_null($expire)) { $expire = $this->options['expire']; } - $key = $this->getCacheKey($name); + + $key = $this->getCacheKey($name); + $expire = $this->getExpireTime($expire); + $value = $this->serialize($value); + if ($this->tag && !$this->has($name)) { $first = true; } + if (wincache_ucache_set($key, $value, $expire)) { isset($first) && $this->setTagItem($key); return true; } + return false; } /** * 自增缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function inc($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); + return wincache_ucache_inc($key, $step); } /** * 自减缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function dec($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); + return wincache_ucache_dec($key, $step); } /** * 删除缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return boolean */ public function rm($name) { + $this->writeTimes++; + return wincache_ucache_delete($this->getCacheKey($name)); } /** * 清除缓存 * @access public - * @param string $tag 标签名 + * @param string $tag 标签名 * @return boolean */ public function clear($tag = null) @@ -143,6 +166,7 @@ class Wincache extends Driver $this->rm('tag_' . md5($tag)); return true; } else { + $this->writeTimes++; return wincache_ucache_clear(); } } diff --git a/library/think/cache/driver/Xcache.php b/library/think/cache/driver/Xcache.php index 6b18b3fc9e3697f34ad3a7c86619583325bca85e..6d1bf3f6cf0c047613af49521c271e8950e49877 100644 --- a/library/think/cache/driver/Xcache.php +++ b/library/think/cache/driver/Xcache.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,7 +12,6 @@ namespace think\cache\driver; use think\cache\Driver; -use think\Exception; /** * Xcache缓存驱动 @@ -21,14 +20,15 @@ use think\Exception; class Xcache extends Driver { protected $options = [ - 'prefix' => '', - 'expire' => 0, + 'prefix' => '', + 'expire' => 0, + 'serialize' => true, ]; /** * 架构函数 - * @param array $options 缓存参数 * @access public + * @param array $options 缓存参数 * @throws \BadFunctionCallException */ public function __construct($options = []) @@ -36,6 +36,7 @@ class Xcache extends Driver if (!function_exists('xcache_info')) { throw new \BadFunctionCallException('not support: Xcache'); } + if (!empty($options)) { $this->options = array_merge($this->options, $options); } @@ -44,93 +45,113 @@ class Xcache extends Driver /** * 判断缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return bool */ public function has($name) { $key = $this->getCacheKey($name); + return xcache_isset($key); } /** * 读取缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $default 默认值 + * @param string $name 缓存变量名 + * @param mixed $default 默认值 * @return mixed */ public function get($name, $default = false) { + $this->readTimes++; + $key = $this->getCacheKey($name); - return xcache_isset($key) ? xcache_get($key) : $default; + + return xcache_isset($key) ? $this->unserialize(xcache_get($key)) : $default; } /** * 写入缓存 * @access public - * @param string $name 缓存变量名 - * @param mixed $value 存储数据 - * @param integer $expire 有效时间(秒) + * @param string $name 缓存变量名 + * @param mixed $value 存储数据 + * @param integer|\DateTime $expire 有效时间(秒) * @return boolean */ public function set($name, $value, $expire = null) { + $this->writeTimes++; + if (is_null($expire)) { $expire = $this->options['expire']; } + if ($this->tag && !$this->has($name)) { $first = true; } - $key = $this->getCacheKey($name); + + $key = $this->getCacheKey($name); + $expire = $this->getExpireTime($expire); + $value = $this->serialize($value); + if (xcache_set($key, $value, $expire)) { isset($first) && $this->setTagItem($key); return true; } + return false; } /** * 自增缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function inc($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); + return xcache_inc($key, $step); } /** * 自减缓存(针对数值缓存) * @access public - * @param string $name 缓存变量名 - * @param int $step 步长 + * @param string $name 缓存变量名 + * @param int $step 步长 * @return false|int */ public function dec($name, $step = 1) { + $this->writeTimes++; + $key = $this->getCacheKey($name); + return xcache_dec($key, $step); } /** * 删除缓存 * @access public - * @param string $name 缓存变量名 + * @param string $name 缓存变量名 * @return boolean */ public function rm($name) { + $this->writeTimes++; + return xcache_unset($this->getCacheKey($name)); } /** * 清除缓存 * @access public - * @param string $tag 标签名 + * @param string $tag 标签名 * @return boolean */ public function clear($tag = null) @@ -144,6 +165,9 @@ class Xcache extends Driver $this->rm('tag_' . md5($tag)); return true; } + + $this->writeTimes++; + if (function_exists('xcache_unset_by_prefix')) { return xcache_unset_by_prefix($this->options['prefix']); } else { diff --git a/library/think/config/driver/Ini.php b/library/think/config/driver/Ini.php index d8dc558d432bf965e93ce270dc977623294b9288..b2a647d1156e75cb5698e4ba693ccd03b5485c1b 100644 --- a/library/think/config/driver/Ini.php +++ b/library/think/config/driver/Ini.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,12 +13,19 @@ namespace think\config\driver; class Ini { - public function parse($config) + protected $config; + + public function __construct($config) + { + $this->config = $config; + } + + public function parse() { - if (is_file($config)) { - return parse_ini_file($config, true); + if (is_file($this->config)) { + return parse_ini_file($this->config, true); } else { - return parse_ini_string($config, true); + return parse_ini_string($this->config, true); } } } diff --git a/library/think/config/driver/Json.php b/library/think/config/driver/Json.php index ec2419f913af6c72e0bc123f9ef13d579666cdd3..0d77c8edc4a94af0cc45aafb4d29c0fc6bcb55d1 100644 --- a/library/think/config/driver/Json.php +++ b/library/think/config/driver/Json.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,12 +13,19 @@ namespace think\config\driver; class Json { - public function parse($config) + protected $config; + + public function __construct($config) { if (is_file($config)) { $config = file_get_contents($config); } - $result = json_decode($config, true); - return $result; + + $this->config = $config; + } + + public function parse() + { + return json_decode($this->config, true); } } diff --git a/library/think/config/driver/Xml.php b/library/think/config/driver/Xml.php index 5bc93015ad3dc41e8dad1218e814ca9c4ff0ecc4..9d6963384e918417c745cbf75521676c4c75f0c6 100644 --- a/library/think/config/driver/Xml.php +++ b/library/think/config/driver/Xml.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,19 +13,28 @@ namespace think\config\driver; class Xml { - public function parse($config) + protected $config; + + public function __construct($config) + { + $this->config = $config; + } + + public function parse() { - if (is_file($config)) { - $content = simplexml_load_file($config); + if (is_file($this->config)) { + $content = simplexml_load_file($this->config); } else { - $content = simplexml_load_string($config); + $content = simplexml_load_string($this->config); } + $result = (array) $content; foreach ($result as $key => $val) { if (is_object($val)) { $result[$key] = (array) $val; } } + return $result; } } diff --git a/library/think/console/Input.php b/library/think/console/Input.php index 269196eb7436b9d022e8a80abf3b9acbd42164f0..2482dfdc01b8c58fce4a59cefec880416f37eb3e 100644 --- a/library/think/console/Input.php +++ b/library/think/console/Input.php @@ -252,7 +252,7 @@ class Input return $token; } - return null; + return; } /** diff --git a/library/think/console/command/Build.php b/library/think/console/command/Build.php index 39806c3f4c25cccc67ddfda2b0033f2b07c52adc..2b83199b1638ccde292d170620fbb798b7881c79 100644 --- a/library/think/console/command/Build.php +++ b/library/think/console/command/Build.php @@ -15,6 +15,8 @@ use think\console\Command; use think\console\Input; use think\console\input\Option; use think\console\Output; +use think\facade\App; +use think\facade\Build as AppBuild; class Build extends Command { @@ -35,7 +37,7 @@ class Build extends Command protected function execute(Input $input, Output $output) { if ($input->hasOption('module')) { - \think\Build::module($input->getOption('module')); + AppBuild::module($input->getOption('module')); $output->writeln("Successed"); return; } @@ -43,13 +45,15 @@ class Build extends Command if ($input->hasOption('config')) { $build = include $input->getOption('config'); } else { - $build = include APP_PATH . 'build.php'; + $build = include App::getAppPath() . 'build.php'; } + if (empty($build)) { $output->writeln("Build Config Is Empty"); return; } - \think\Build::run($build); + + AppBuild::run($build); $output->writeln("Successed"); } diff --git a/library/think/console/command/Clear.php b/library/think/console/command/Clear.php index 020febd3a06af525f95dd56275ad6ae88d21e450..1442575931741f4117ea5c09fb6d162d594ea531 100644 --- a/library/think/console/command/Clear.php +++ b/library/think/console/command/Clear.php @@ -14,6 +14,8 @@ use think\console\Command; use think\console\Input; use think\console\input\Option; use think\console\Output; +use think\facade\App; +use think\facade\Cache; class Clear extends Command { @@ -23,22 +25,46 @@ class Clear extends Command $this ->setName('clear') ->addOption('path', 'd', Option::VALUE_OPTIONAL, 'path to clear', null) + ->addOption('cache', 'c', Option::VALUE_NONE, 'clear cache file') + ->addOption('route', 'u', Option::VALUE_NONE, 'clear route cache') + ->addOption('log', 'l', Option::VALUE_NONE, 'clear log file') + ->addOption('dir', 'r', Option::VALUE_NONE, 'clear empty dir') ->setDescription('Clear runtime file'); } protected function execute(Input $input, Output $output) { - $path = $input->getOption('path') ?: RUNTIME_PATH; - $files = scandir($path); - if ($files) { - foreach ($files as $file) { - if ('.' != $file && '..' != $file && is_dir($path . $file)) { - array_map('unlink', glob($path . $file . '/*.*')); - } elseif (is_file($path . $file)) { - unlink($path . $file); - } + if ($input->getOption('route')) { + Cache::clear('route_cache'); + } else { + if ($input->getOption('cache')) { + $path = App::getRuntimePath() . 'cache'; + } elseif ($input->getOption('log')) { + $path = App::getRuntimePath() . 'log'; + } else { + $path = $input->getOption('path') ?: App::getRuntimePath(); } + + $rmdir = $input->getOption('dir') ? true : false; + $this->clear(rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, $rmdir); } + $output->writeln("Clear Successed"); } + + protected function clear($path, $rmdir) + { + $files = is_dir($path) ? scandir($path) : []; + + foreach ($files as $file) { + if ('.' != $file && '..' != $file && is_dir($path . $file)) { + array_map('unlink', glob($path . $file . DIRECTORY_SEPARATOR . '*.*')); + if ($rmdir) { + rmdir($path . $file); + } + } elseif ('.gitignore' != $file && is_file($path . $file)) { + unlink($path . $file); + } + } + } } diff --git a/library/think/console/command/Help.php b/library/think/console/command/Help.php index eb0858a368052fcf17323487eee5879613664d19..bae2c653312f35f38f72a976d96a7346c621261f 100644 --- a/library/think/console/command/Help.php +++ b/library/think/console/command/Help.php @@ -16,7 +16,6 @@ use think\console\Input; use think\console\input\Argument as InputArgument; use think\console\input\Option as InputOption; use think\console\Output; -use think\console\helper\Descriptor as DescriptorHelper; class Help extends Command { @@ -67,4 +66,4 @@ EOF $this->command = null; } -} \ No newline at end of file +} diff --git a/library/think/console/command/Lists.php b/library/think/console/command/Lists.php index ffbee07c2d0d8b9d5075c483ad51ac7ef51e9f27..084ddaa231ce3b1dd8c0b602387b49da80344c74 100644 --- a/library/think/console/command/Lists.php +++ b/library/think/console/command/Lists.php @@ -71,4 +71,4 @@ EOF new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list') ]); } -} \ No newline at end of file +} diff --git a/library/think/console/command/Make.php b/library/think/console/command/Make.php index b508f8d0b6fc77e104c13203dba55ba1922f35ee..7474f26684bcf280cfbbc42eccaa71827c5c49c5 100644 --- a/library/think/console/command/Make.php +++ b/library/think/console/command/Make.php @@ -11,11 +11,13 @@ namespace think\console\command; -use think\Config; use think\console\Command; use think\console\Input; use think\console\input\Argument; use think\console\Output; +use think\facade\App; +use think\facade\Config; +use think\facade\Env; abstract class Make extends Command { @@ -44,7 +46,7 @@ abstract class Make extends Command } if (!is_dir(dirname($pathname))) { - mkdir(strtolower(dirname($pathname)), 0755, true); + mkdir(dirname($pathname), 0755, true); } file_put_contents($pathname, $this->buildClass($classname)); @@ -64,23 +66,23 @@ abstract class Make extends Command return str_replace(['{%className%}', '{%namespace%}', '{%app_namespace%}'], [ $class, $namespace, - Config::get('app_namespace') + App::getNamespace(), ], $stub); } protected function getPathName($name) { - $name = str_replace(Config::get('app_namespace') . '\\', '', $name); + $name = str_replace(App::getNamespace() . '\\', '', $name); - return APP_PATH . str_replace('\\', '/', $name) . '.php'; + return Env::get('app_path') . ltrim(str_replace('\\', '/', $name), '/') . '.php'; } protected function getClassName($name) { - $appNamespace = Config::get('app_namespace'); + $appNamespace = App::getNamespace(); - if (strpos($name, $appNamespace . '\\') === 0) { + if (strpos($name, $appNamespace . '\\') !== false) { return $name; } diff --git a/library/think/console/command/RunServer.php b/library/think/console/command/RunServer.php new file mode 100644 index 0000000000000000000000000000000000000000..4dd610b6e76d99396c5c194b8c36a846e1e84fbd --- /dev/null +++ b/library/think/console/command/RunServer.php @@ -0,0 +1,54 @@ + +// +---------------------------------------------------------------------- +namespace think\console\command; + +use think\console\Command; +use think\console\Input; +use think\console\input\Option; +use think\console\Output; +use think\facade\App; + +class RunServer extends Command +{ + + public function configure() + { + $this->setName('run') + ->addOption('host', 'H', Option::VALUE_OPTIONAL, + 'The host to server the application on', '127.0.0.1') + ->addOption('port', 'p', Option::VALUE_OPTIONAL, + 'The port to server the application on', 8000) + ->addOption('root', 'r', Option::VALUE_OPTIONAL, + 'The document root of the application', App::getRootPath() . 'public') + ->setDescription('PHP Built-in Server for ThinkPHP'); + } + + public function execute(Input $input, Output $output) + { + $host = $input->getOption('host'); + $port = $input->getOption('port'); + $root = $input->getOption('root'); + + $command = sprintf( + 'php -S %s:%d -t %s %s', + $host, + $port, + escapeshellarg($root), + escapeshellarg($root . DIRECTORY_SEPARATOR . 'router.php') + ); + + $output->writeln(sprintf('ThinkPHP Development server is started On ', $host, $port)); + $output->writeln(sprintf('You can exit with `CTRL-C`')); + $output->writeln(sprintf('Document root is: %s', $root)); + passthru($command); + } + +} diff --git a/library/think/console/command/make/Controller.php b/library/think/console/command/make/Controller.php index afa7be9052e4975e4c693d66d8fd02ffd2e8df8b..e4cc5bb572af841f98771c37ad2ad2684af7c688 100644 --- a/library/think/console/command/make/Controller.php +++ b/library/think/console/command/make/Controller.php @@ -11,9 +11,9 @@ namespace think\console\command\make; -use think\Config; use think\console\command\Make; use think\console\input\Option; +use think\facade\Config; class Controller extends Make { @@ -24,17 +24,24 @@ class Controller extends Make { parent::configure(); $this->setName('make:controller') + ->addOption('api', null, Option::VALUE_NONE, 'Generate an api controller class.') ->addOption('plain', null, Option::VALUE_NONE, 'Generate an empty controller class.') ->setDescription('Create a new resource controller class'); } protected function getStub() { + $stubPath = __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR; + + if ($this->input->getOption('api')) { + return $stubPath . 'controller.api.stub'; + } + if ($this->input->getOption('plain')) { - return __DIR__ . '/stubs/controller.plain.stub'; + return $stubPath . 'controller.plain.stub'; } - return __DIR__ . '/stubs/controller.stub'; + return $stubPath . 'controller.stub'; } protected function getClassName($name) diff --git a/tests/thinkphp/library/think/config/driver/jsonTest.php b/library/think/console/command/make/Middleware.php similarity index 41% rename from tests/thinkphp/library/think/config/driver/jsonTest.php rename to library/think/console/command/make/Middleware.php index 9d438d403629870608cd73c41ed0ccd730d002ca..bfe821b03a3e73b72902f6fcb93d7516f1077713 100644 --- a/tests/thinkphp/library/think/config/driver/jsonTest.php +++ b/library/think/console/command/make/Middleware.php @@ -2,32 +2,35 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- -// | Author: liu21st +// | Author: 刘志淳 // +---------------------------------------------------------------------- -/** - * Xml配置测试 - * @author 7IN0SAN9 - */ +namespace think\console\command\make; -namespace tests\thinkphp\library\think\config\driver; +use think\console\command\Make; -use think\config; - -class jsonTest extends \PHPUnit_Framework_TestCase +class Middleware extends Make { - public function testParse() + protected $type = "Middleware"; + + protected function configure() + { + parent::configure(); + $this->setName('make:middleware') + ->setDescription('Create a new middleware class'); + } + + protected function getStub() + { + return __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'middleware.stub'; + } + + protected function getNamespace($appNamespace, $module) { - Config::parse('{"jsonstring":1}', 'json'); - $this->assertEquals(1, Config::get('jsonstring')); - Config::reset(); - Config::parse(__DIR__ . '/fixtures/config.json'); - $this->assertTrue(Config::has('jsonstring')); - $this->assertEquals(1, Config::get('jsonstring')); - Config::reset(); + return parent::getNamespace($appNamespace, 'http') . '\middleware'; } } diff --git a/library/think/console/command/make/Model.php b/library/think/console/command/make/Model.php index d4e9b5dd08cbffb16e811a01070fb9219dbccd0f..03e6b3fcd35ae7da3ec4c2eb2e31743e0a5c545e 100644 --- a/library/think/console/command/make/Model.php +++ b/library/think/console/command/make/Model.php @@ -26,7 +26,7 @@ class Model extends Make protected function getStub() { - return __DIR__ . '/stubs/model.stub'; + return __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'model.stub'; } protected function getNamespace($appNamespace, $module) diff --git a/library/think/console/command/make/Validate.php b/library/think/console/command/make/Validate.php new file mode 100644 index 0000000000000000000000000000000000000000..e7e39e635b0d91918c8adb25b1789cda78006afc --- /dev/null +++ b/library/think/console/command/make/Validate.php @@ -0,0 +1,40 @@ + +// +---------------------------------------------------------------------- + +namespace think\console\command\make; + +use think\console\command\Make; + +class Validate extends Make +{ + + protected $type = "Validate"; + + protected function configure() + { + parent::configure(); + $this->setName('make:validate') + ->setDescription('Create a validate class'); + } + + protected function getStub() + { + $stubPath = __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR; + + return $stubPath . 'validate.stub'; + } + + protected function getNamespace($appNamespace, $module) + { + return parent::getNamespace($appNamespace, $module) . '\validate'; + } + +} diff --git a/library/think/console/command/make/stubs/controller.api.stub b/library/think/console/command/make/stubs/controller.api.stub new file mode 100644 index 0000000000000000000000000000000000000000..aed9edfbd66a830b4d00e5b00dcbe6fce7d7d1f1 --- /dev/null +++ b/library/think/console/command/make/stubs/controller.api.stub @@ -0,0 +1,64 @@ + ['规则1','规则2'...] + * + * @var array + */ + protected $rule = []; + + /** + * 定义错误信息 + * 格式:'字段名.规则名' => '错误信息' + * + * @var array + */ + protected $message = []; +} diff --git a/library/think/console/command/optimize/Autoload.php b/library/think/console/command/optimize/Autoload.php index 0481e1795ec9a44d5520d0bbdd9f7919c5c9746a..c5eab03ce2114367fbde8ebfdd8cf255b47c3bf9 100644 --- a/library/think/console/command/optimize/Autoload.php +++ b/library/think/console/command/optimize/Autoload.php @@ -10,10 +10,10 @@ // +---------------------------------------------------------------------- namespace think\console\command\optimize; -use think\App; use think\console\Command; use think\console\Input; use think\console\Output; +use think\Container; class Autoload extends Command { @@ -32,17 +32,16 @@ class Autoload extends Command /** * 类库映射 */ - + return [ EOF; - + $app = Container::get('app'); $namespacesToScan = [ - App::$namespace . '\\' => realpath(rtrim(APP_PATH)), - 'think\\' => LIB_PATH . 'think', - 'behavior\\' => LIB_PATH . 'behavior', - 'traits\\' => LIB_PATH . 'traits', - '' => realpath(rtrim(EXTEND_PATH)) + $app->getNamespace() . '\\' => realpath(rtrim($app->getAppPath())), + 'think\\' => $app->getAppPath() . 'library/think', + 'traits\\' => $app->getAppPath() . 'library/traits', + '' => realpath(rtrim($app->getRootPath() . 'extend')), ]; krsort($namespacesToScan); @@ -53,7 +52,7 @@ EOF; continue; } - $namespaceFilter = $namespace === '' ? null : $namespace; + $namespaceFilter = '' === $namespace ? null : $namespace; $classMap = $this->addClassMapCode($dir, $namespaceFilter, $classMap); } @@ -62,12 +61,12 @@ EOF; $classmapFile .= ' ' . var_export($class, true) . ' => ' . $code; } $classmapFile .= "];\n"; - - if (!is_dir(RUNTIME_PATH)) { - @mkdir(RUNTIME_PATH, 0755, true); + $runtimePath = $app->getRuntimePath(); + if (!is_dir($runtimePath)) { + @mkdir($runtimePath, 0755, true); } - file_put_contents(RUNTIME_PATH . 'classmap' . EXT, $classmapFile); + file_put_contents($runtimePath . 'classmap.php', $classmapFile); $output->writeln('Succeed!'); } @@ -84,7 +83,7 @@ EOF; $this->output->writeln( 'Warning: Ambiguous class resolution, "' . $class . '"' . ' was found in both "' . str_replace(["',\n"], [ - '' + '', ], $classMap[$class]) . '" and "' . $path . '", the first will be used.' ); } @@ -94,29 +93,29 @@ EOF; protected function getPathCode($path) { - $baseDir = ''; - $appPath = $this->normalizePath(realpath(APP_PATH)); - $libPath = $this->normalizePath(realpath(LIB_PATH)); - $extendPath = $this->normalizePath(realpath(EXTEND_PATH)); + $app = Container::get('app'); + $appPath = $this->normalizePath(realpath($app->getAppPath())); + $libPath = $this->normalizePath(realpath($app->getThinkPath() . 'library')); + $extendPath = $this->normalizePath(realpath($app->getRootPath() . 'extend')); $path = $this->normalizePath($path); if (strpos($path, $libPath . '/') === 0) { - $path = substr($path, strlen(LIB_PATH)); - $baseDir = 'LIB_PATH'; + $path = substr($path, strlen($app->getThinkPath() . 'library')); + $baseDir = "'" . $libPath . "/'"; } elseif (strpos($path, $appPath . '/') === 0) { $path = substr($path, strlen($appPath) + 1); - $baseDir = 'APP_PATH'; + $baseDir = "'" . $appPath . "/'"; } elseif (strpos($path, $extendPath . '/') === 0) { $path = substr($path, strlen($extendPath) + 1); - $baseDir = 'EXTEND_PATH'; + $baseDir = "'" . $extendPath . "/'"; } - if ($path !== false) { + if (false !== $path) { $baseDir .= " . "; } - return $baseDir . (($path !== false) ? var_export($path, true) : ""); + return $baseDir . ((false !== $path) ? var_export($path, true) : ""); } protected function normalizePath($path) @@ -239,7 +238,7 @@ EOF; // strip leading non-php code if needed if (substr($contents, 0, 2) !== 'hasArgument('module')) { - $module = $input->getArgument('module') . DS; + if ($input->getArgument('module')) { + $module = $input->getArgument('module') . DIRECTORY_SEPARATOR; } else { $module = ''; } - $content = 'buildCacheContent($module); - - if (!is_dir(RUNTIME_PATH . $module)) { - @mkdir(RUNTIME_PATH . $module, 0755, true); + $content = 'buildCacheContent($module); + $runtimePath = App::getRuntimePath(); + if (!is_dir($runtimePath . $module)) { + @mkdir($runtimePath . $module, 0755, true); } - file_put_contents(RUNTIME_PATH . $module . 'init' . EXT, $content); + file_put_contents($runtimePath . $module . 'init.php', $content); $output->writeln('Succeed!'); } protected function buildCacheContent($module) { - $content = ''; - $path = realpath(APP_PATH . $module) . DS; - + $content = '// This cache file is automatically generated at:' . date('Y-m-d H:i:s') . PHP_EOL; + $path = realpath(App::getAppPath() . $module) . DIRECTORY_SEPARATOR; if ($module) { - // 加载模块配置 - $config = ThinkConfig::load(CONF_PATH . $module . 'config' . CONF_EXT); + $configPath = is_dir($path . 'config') ? $path . 'config' : App::getConfigPath() . $module; + } else { + $configPath = App::getConfigPath(); + } + $ext = App::getConfigExt(); + $config = Container::get('config'); - // 读取数据库配置文件 - $filename = CONF_PATH . $module . 'database' . CONF_EXT; - ThinkConfig::load($filename, 'database'); + $files = is_dir($configPath) ? scandir($configPath) : []; - // 加载应用状态配置 - if ($config['app_status']) { - $config = ThinkConfig::load(CONF_PATH . $module . $config['app_status'] . CONF_EXT); - } - // 读取扩展配置文件 - if (is_dir(CONF_PATH . $module . 'extra')) { - $dir = CONF_PATH . $module . 'extra'; - $files = scandir($dir); - foreach ($files as $file) { - if (strpos($file, CONF_EXT)) { - $filename = $dir . DS . $file; - ThinkConfig::load($filename, pathinfo($file, PATHINFO_FILENAME)); - } - } + foreach ($files as $file) { + if ('.' . pathinfo($file, PATHINFO_EXTENSION) === $ext) { + $filename = $configPath . DIRECTORY_SEPARATOR . $file; + $config->load($filename, pathinfo($file, PATHINFO_FILENAME)); } } // 加载行为扩展文件 - if (is_file(CONF_PATH . $module . 'tags' . EXT)) { - $content .= '\think\Hook::import(' . (var_export(include CONF_PATH . $module . 'tags' . EXT, true)) . ');' . PHP_EOL; + if (is_file($path . 'tags.php')) { + $tags = include $path . 'tags.php'; + if (is_array($tags)) { + $content .= PHP_EOL . '\think\facade\Hook::import(' . (var_export($tags, true)) . ');' . PHP_EOL; + } } // 加载公共文件 - if (is_file($path . 'common' . EXT)) { - $content .= substr(php_strip_whitespace($path . 'common' . EXT), 5) . PHP_EOL; + if (is_file($path . 'common.php')) { + $common = substr(php_strip_whitespace($path . 'common.php'), 6); + if ($common) { + $content .= PHP_EOL . $common . PHP_EOL; + } } - $content .= '\think\Config::set(' . var_export(ThinkConfig::get(), true) . ');'; + if ('' == $module) { + $content .= PHP_EOL . substr(php_strip_whitespace(App::getThinkPath() . 'helper.php'), 6) . PHP_EOL; + + if (is_file($path . 'middleware.php')) { + $middleware = include $path . 'middleware.php'; + if (is_array($middleware)) { + $content .= PHP_EOL . '\think\Container::get("middleware")->import(' . var_export($middleware, true) . ');' . PHP_EOL; + } + } + } + + if (is_file($path . 'provider.php')) { + $provider = include $path . 'provider.php'; + if (is_array($provider)) { + $content .= PHP_EOL . '\think\Container::getInstance()->bindTo(' . var_export($provider, true) . ');' . PHP_EOL; + } + } + + $content .= PHP_EOL . '\think\facade\Config::set(' . var_export($config->get(), true) . ');' . PHP_EOL; + return $content; } } diff --git a/library/think/console/command/optimize/Route.php b/library/think/console/command/optimize/Route.php index 911e4c1474e9a5a8d5f10da300b1d90d4f1c28a1..b6ad5b52de9c32928f865e8be286a800bd3ddf27 100644 --- a/library/think/console/command/optimize/Route.php +++ b/library/think/console/command/optimize/Route.php @@ -6,13 +6,14 @@ // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- -// | Author: liu21st +// | Author: yunwuxin <448901948@qq.com> // +---------------------------------------------------------------------- namespace think\console\command\optimize; use think\console\Command; use think\console\Input; use think\console\Output; +use think\Container; class Route extends Command { @@ -27,44 +28,41 @@ class Route extends Command protected function execute(Input $input, Output $output) { - file_put_contents(RUNTIME_PATH . 'route.php', $this->buildRouteCache()); + $filename = Container::get('app')->getRuntimePath() . 'route.php'; + if (is_file($filename)) { + unlink($filename); + } + file_put_contents($filename, $this->buildRouteCache()); $output->writeln('Succeed!'); } protected function buildRouteCache() { - $files = \think\Config::get('route_config_file'); + Container::get('route')->setName([]); + Container::get('route')->lazy(false); + // 路由检测 + $path = Container::get('app')->getRoutePath(); + + $files = is_dir($path) ? scandir($path) : []; + foreach ($files as $file) { - if (is_file(CONF_PATH . $file . CONF_EXT)) { - $config = include CONF_PATH . $file . CONF_EXT; - if (is_array($config)) { - \think\Route::import($config); + if (strpos($file, '.php')) { + $filename = $path . DIRECTORY_SEPARATOR . $file; + // 导入路由配置 + $rules = include $filename; + if (is_array($rules)) { + Container::get('route')->import($rules); } } } - $rules = \think\Route::rules(true); - array_walk_recursive($rules, [$this, 'buildClosure']); + + if (Container::get('config')->get('route_annotation')) { + include Container::get('build')->buildRoute(); + } + $content = 'getName(), true) . ';'; return $content; } - protected function buildClosure(&$value) - { - if ($value instanceof \Closure) { - $reflection = new \ReflectionFunction($value); - $startLine = $reflection->getStartLine(); - $endLine = $reflection->getEndLine(); - $file = $reflection->getFileName(); - $item = file($file); - $content = ''; - for ($i = $startLine - 1; $i <= $endLine - 1; $i++) { - $content .= $item[$i]; - } - $start = strpos($content, 'function'); - $end = strrpos($content, '}'); - $value = '[__start__' . substr($content, $start, $end - $start + 1) . '__end__]'; - } - } } diff --git a/library/think/console/command/optimize/Schema.php b/library/think/console/command/optimize/Schema.php index a1f40cd9aec124ffb474c8dc53f6957c269f0dec..61620badd69740b240d89545a51feb4dcf69c336 100644 --- a/library/think/console/command/optimize/Schema.php +++ b/library/think/console/command/optimize/Schema.php @@ -10,12 +10,12 @@ // +---------------------------------------------------------------------- namespace think\console\command\optimize; -use think\App; use think\console\Command; use think\console\Input; use think\console\input\Option; use think\console\Output; use think\Db; +use think\facade\App; class Schema extends Command { @@ -33,46 +33,54 @@ class Schema extends Command protected function execute(Input $input, Output $output) { - if (!is_dir(RUNTIME_PATH . 'schema')) { - @mkdir(RUNTIME_PATH . 'schema', 0755, true); + if (!is_dir(App::getRuntimePath() . 'schema')) { + @mkdir(App::getRuntimePath() . 'schema', 0755, true); } + if ($input->hasOption('module')) { $module = $input->getOption('module'); // 读取模型 - $list = scandir(APP_PATH . $module . DS . 'model'); - $app = App::$namespace; + $path = App::getAppPath() . $module . DIRECTORY_SEPARATOR . 'model'; + $list = is_dir($path) ? scandir($path) : []; + $namespace = App::getNamespace(); + foreach ($list as $file) { - if ('.' == $file || '..' == $file) { + if (0 === strpos($file, '.')) { continue; } - $class = '\\' . $app . '\\' . $module . '\\model\\' . pathinfo($file, PATHINFO_FILENAME); + $class = '\\' . $namespace . '\\' . $module . '\\model\\' . pathinfo($file, PATHINFO_FILENAME); $this->buildModelSchema($class); } + $output->writeln('Succeed!'); return; - } else if ($input->hasOption('table')) { + } elseif ($input->hasOption('table')) { $table = $input->getOption('table'); if (!strpos($table, '.')) { $dbName = Db::getConfig('database'); } + $tables[] = $table; } elseif ($input->hasOption('db')) { $dbName = $input->getOption('db'); - $tables = Db::getTables($dbName); - } elseif (!\think\Config::get('app_multi_module')) { - $app = App::$namespace; - $list = scandir(APP_PATH . 'model'); + $tables = Db::getConnection()->getTables($dbName); + } elseif (!\think\facade\Config::get('app_multi_module')) { + $namespace = App::getNamespace(); + $path = App::getAppPath() . 'model'; + $list = is_dir($path) ? scandir($path) : []; + foreach ($list as $file) { - if ('.' == $file || '..' == $file) { + if (0 === strpos($file, '.')) { continue; } - $class = '\\' . $app . '\\model\\' . pathinfo($file, PATHINFO_FILENAME); + $class = '\\' . $namespace . '\\model\\' . pathinfo($file, PATHINFO_FILENAME); $this->buildModelSchema($class); } + $output->writeln('Succeed!'); return; } else { - $tables = Db::getTables(); + $tables = Db::getConnection()->getTables(); } $db = isset($dbName) ? $dbName . '.' : ''; @@ -90,7 +98,8 @@ class Schema extends Command $content = 'getFields($table); $content .= var_export($info, true) . ';'; - file_put_contents(RUNTIME_PATH . 'schema' . DS . $dbName . '.' . $table . EXT, $content); + + file_put_contents(App::getRuntimePath() . 'schema' . DIRECTORY_SEPARATOR . $dbName . '.' . $table . '.php', $content); } } @@ -101,11 +110,12 @@ class Schema extends Command } else { $dbName = $db; } + foreach ($tables as $table) { $content = 'getFields($db . $table); $content .= var_export($info, true) . ';'; - file_put_contents(RUNTIME_PATH . 'schema' . DS . $dbName . $table . EXT, $content); + file_put_contents(App::getRuntimePath() . 'schema' . DIRECTORY_SEPARATOR . $dbName . $table . '.php', $content); } } } diff --git a/library/think/console/output/Ask.php b/library/think/console/output/Ask.php index 4d360bce9a38b0bb3bdbfaef6767414fc0251e30..3933eb296b33364547da562fdecb48974df7181d 100644 --- a/library/think/console/output/Ask.php +++ b/library/think/console/output/Ask.php @@ -337,4 +337,4 @@ class Ask return self::$stty = $exitcode === 0; } -} \ No newline at end of file +} diff --git a/library/think/console/output/driver/Console.php b/library/think/console/output/driver/Console.php index af4341b7e20a9f1ea38f4dcdf6268f33ec2b58e4..e041b5250dfc458c6fa6842db2d800e3a5218afc 100644 --- a/library/think/console/output/driver/Console.php +++ b/library/think/console/output/driver/Console.php @@ -168,7 +168,7 @@ class Console return $this->terminalDimensions; } - if ('\\' === DS) { + if ('\\' === DIRECTORY_SEPARATOR) { if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) { return [(int) $matches[1], (int) $matches[2]]; } @@ -196,7 +196,7 @@ class Console private function getSttyColumns() { if (!function_exists('proc_open')) { - return null; + return; } $descriptorspec = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']]; @@ -209,7 +209,7 @@ class Console return $info; } - return null; + return; } /** @@ -219,7 +219,7 @@ class Console private function getMode() { if (!function_exists('proc_open')) { - return null; + return; } $descriptorspec = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']]; @@ -234,7 +234,7 @@ class Console return $matches[2] . 'x' . $matches[1]; } } - return null; + return; } private function stringWidth($string) @@ -356,10 +356,10 @@ class Console { if (DIRECTORY_SEPARATOR === '\\') { return - '10.0.10586' === PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . '.' . PHP_WINDOWS_VERSION_BUILD - || false !== getenv('ANSICON') - || 'ON' === getenv('ConEmuANSI') - || 'xterm' === getenv('TERM'); + '10.0.10586' === PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . '.' . PHP_WINDOWS_VERSION_BUILD + || false !== getenv('ANSICON') + || 'ON' === getenv('ConEmuANSI') + || 'xterm' === getenv('TERM'); } return function_exists('posix_isatty') && @posix_isatty($stream); diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php deleted file mode 100644 index a75cfd375a853f45c7730947d64f363d69fc83ec..0000000000000000000000000000000000000000 --- a/library/think/controller/Rest.php +++ /dev/null @@ -1,99 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace think\controller; - -use think\App; -use think\Request; -use think\Response; - -abstract class Rest -{ - - protected $method; // 当前请求类型 - protected $type; // 当前资源类型 - // 输出类型 - protected $restMethodList = 'get|post|put|delete'; - protected $restDefaultMethod = 'get'; - protected $restTypeList = 'html|xml|json|rss'; - protected $restDefaultType = 'html'; - protected $restOutputType = [ // REST允许输出的资源类型列表 - 'xml' => 'application/xml', - 'json' => 'application/json', - 'html' => 'text/html', - ]; - - /** - * 架构函数 取得模板对象实例 - * @access public - */ - public function __construct() - { - // 资源类型检测 - $request = Request::instance(); - $ext = $request->ext(); - if ('' == $ext) { - // 自动检测资源类型 - $this->type = $request->type(); - } elseif (!preg_match('/\(' . $this->restTypeList . '\)$/i', $ext)) { - // 资源类型非法 则用默认资源类型访问 - $this->type = $this->restDefaultType; - } else { - $this->type = $ext; - } - // 请求方式检测 - $method = strtolower($request->method()); - if (false === stripos($this->restMethodList, $method)) { - // 请求方式非法 则用默认请求方法 - $method = $this->restDefaultMethod; - } - $this->method = $method; - } - - /** - * REST 调用 - * @access public - * @param string $method 方法名 - * @return mixed - * @throws \Exception - */ - public function _empty($method) - { - if (method_exists($this, $method . '_' . $this->method . '_' . $this->type)) { - // RESTFul方法支持 - $fun = $method . '_' . $this->method . '_' . $this->type; - } elseif ($this->method == $this->restDefaultMethod && method_exists($this, $method . '_' . $this->type)) { - $fun = $method . '_' . $this->type; - } elseif ($this->type == $this->restDefaultType && method_exists($this, $method . '_' . $this->method)) { - $fun = $method . '_' . $this->method; - } - if (isset($fun)) { - return App::invokeMethod([$this, $fun]); - } else { - // 抛出异常 - throw new \Exception('error action :' . $method); - } - } - - /** - * 输出返回数据 - * @access protected - * @param mixed $data 要返回的数据 - * @param String $type 返回类型 JSON XML - * @param integer $code HTTP状态码 - * @return Response - */ - protected function response($data, $type = 'json', $code = 200) - { - return Response::create($data, $type)->code($code); - } - -} diff --git a/library/think/controller/Yar.php b/library/think/controller/Yar.php deleted file mode 100644 index fcf5ced1b3ec38d1cfda7194ca859a4e034fb2a7..0000000000000000000000000000000000000000 --- a/library/think/controller/Yar.php +++ /dev/null @@ -1,51 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace think\controller; - -/** - * ThinkPHP Yar控制器类 - */ -abstract class Yar -{ - - /** - * 架构函数 - * @access public - */ - public function __construct() - { - //控制器初始化 - if (method_exists($this, '_initialize')) { - $this->_initialize(); - } - - //判断扩展是否存在 - if (!extension_loaded('yar')) { - throw new \Exception('not support yar'); - } - - //实例化Yar_Server - $server = new \Yar_Server($this); - // 启动server - $server->handle(); - } - - /** - * 魔术方法 有不存在的操作的时候执行 - * @access public - * @param string $method 方法名 - * @param array $args 参数 - * @return mixed - */ - public function __call($method, $args) - {} -} diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index 15a240ad0d7fe700fa6db92e9a6b3e637ae16f73..0d30267b10bcc1743b2d9c3f9138d24722f0615a 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,32 +12,45 @@ namespace think\db; use PDO; -use think\Db; -use think\db\Connection; -use think\db\Query; use think\Exception; abstract class Builder { // connection对象实例 protected $connection; - // 查询对象实例 - protected $query; - // 数据库表达式 - protected $exp = ['eq' => '=', 'neq' => '<>', 'gt' => '>', 'egt' => '>=', 'lt' => '<', 'elt' => '<=', 'notlike' => 'NOT LIKE', 'like' => 'LIKE', 'in' => 'IN', 'exp' => 'EXP', 'notin' => 'NOT IN', 'not in' => 'NOT IN', 'between' => 'BETWEEN', 'not between' => 'NOT BETWEEN', 'notbetween' => 'NOT BETWEEN', 'exists' => 'EXISTS', 'notexists' => 'NOT EXISTS', 'not exists' => 'NOT EXISTS', 'null' => 'NULL', 'notnull' => 'NOT NULL', 'not null' => 'NOT NULL', '> time' => '> TIME', '< time' => '< TIME', '>= time' => '>= TIME', '<= time' => '<= TIME', 'between time' => 'BETWEEN TIME', 'not between time' => 'NOT BETWEEN TIME', 'notbetween time' => 'NOT BETWEEN TIME']; + // 查询表达式映射 + protected $exp = ['EQ' => '=', 'NEQ' => '<>', 'GT' => '>', 'EGT' => '>=', 'LT' => '<', 'ELT' => '<=', 'NOTLIKE' => 'NOT LIKE', 'NOTIN' => 'NOT IN', 'NOTBETWEEN' => 'NOT BETWEEN', 'NOTEXISTS' => 'NOT EXISTS', 'NOTNULL' => 'NOT NULL', 'NOTBETWEEN TIME' => 'NOT BETWEEN TIME']; + + // 查询表达式解析 + protected $parser = [ + 'parseCompare' => ['=', '<>', '>', '>=', '<', '<='], + 'parseLike' => ['LIKE', 'NOT LIKE'], + 'parseBetween' => ['NOT BETWEEN', 'BETWEEN'], + 'parseIn' => ['NOT IN', 'IN'], + 'parseExp' => ['EXP'], + 'parseNull' => ['NOT NULL', 'NULL'], + 'parseBetweenTime' => ['BETWEEN TIME', 'NOT BETWEEN TIME'], + 'parseTime' => ['< TIME', '> TIME', '<= TIME', '>= TIME'], + 'parseExists' => ['NOT EXISTS', 'EXISTS'], + 'parseColumn' => ['COLUMN'], + ]; // SQL表达式 - protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%'; - protected $insertSql = '%INSERT% INTO %TABLE% (%FIELD%) VALUES (%DATA%) %COMMENT%'; - protected $insertAllSql = 'INSERT INTO %TABLE% (%FIELD%) %DATA% %COMMENT%'; - protected $updateSql = 'UPDATE %TABLE% SET %SET% %JOIN% %WHERE% %ORDER%%LIMIT% %LOCK%%COMMENT%'; - protected $deleteSql = 'DELETE FROM %TABLE% %USING% %JOIN% %WHERE% %ORDER%%LIMIT% %LOCK%%COMMENT%'; + protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%UNION%%ORDER%%LIMIT% %LOCK%%COMMENT%'; + + protected $insertSql = '%INSERT% INTO %TABLE% (%FIELD%) VALUES (%DATA%) %COMMENT%'; + + protected $insertAllSql = '%INSERT% INTO %TABLE% (%FIELD%) %DATA% %COMMENT%'; + + protected $updateSql = 'UPDATE %TABLE% SET %SET%%JOIN%%WHERE%%ORDER%%LIMIT% %LOCK%%COMMENT%'; + + protected $deleteSql = 'DELETE FROM %TABLE%%USING%%JOIN%%WHERE%%ORDER%%LIMIT% %LOCK%%COMMENT%'; /** * 架构函数 * @access public - * @param Connection $connection 数据库连接对象实例 + * @param Connection $connection 数据库连接对象实例 */ public function __construct(Connection $connection) { @@ -45,359 +58,715 @@ abstract class Builder } /** - * 设置当前的Query对象实例 - * @access protected - * @param Query $query 当前查询对象实例 - * @return void + * 获取当前的连接对象实例 + * @access public + * @return Connection */ - public function setQuery(Query $query) + public function getConnection() { - $this->query = $query; + return $this->connection; } /** - * 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写) - * @access protected - * @param string $sql sql语句 - * @return string + * 注册查询表达式解析 + * @access public + * @param string $name 解析方法 + * @param array $parser 匹配表达式数据 + * @return $this */ - protected function parseSqlTable($sql) + public function bindParser($name, $parser) { - return $this->query->parseSqlTable($sql); + $this->parser[$name] = $parser; + return $this; } /** * 数据分析 * @access protected - * @param array $data 数据 - * @param array $options 查询参数 + * @param Query $query 查询对象 + * @param array $data 数据 + * @param array $fields 字段信息 + * @param array $bind 参数绑定 + * @param string $suffix 参数绑定后缀 * @return array */ - protected function parseData($data, $options) + protected function parseData(Query $query, $data = [], $fields = [], $bind = [], $suffix = '') { if (empty($data)) { return []; } + $options = $query->getOptions(); + // 获取绑定信息 - $bind = $this->query->getFieldsBind($options); - if ('*' == $options['field']) { - $fields = array_keys($bind); - } else { - $fields = $options['field']; + if (empty($bind)) { + $bind = $this->connection->getFieldsBind($options['table']); + } + + if (empty($fields)) { + if ('*' == $options['field']) { + $fields = array_keys($bind); + } else { + $fields = $options['field']; + } } $result = []; + foreach ($data as $key => $val) { - $item = $this->parseKey($key); - if (!in_array($key, $fields, true)) { + $item = $this->parseKey($query, $key, true); + + if ($val instanceof Expression) { + $result[$item] = $val->getValue(); + continue; + } elseif (!is_scalar($val) && (in_array($key, (array) $query->getOptions('json')) || 'json' == $this->connection->getFieldsType($options['table'], $key))) { + $val = json_encode($val); + } elseif (is_object($val) && method_exists($val, '__toString')) { + // 对象数据写入 + $val = $val->__toString(); + } + + if (false !== strpos($key, '->')) { + list($key, $name) = explode('->', $key); + $item = $this->parseKey($query, $key); + $result[$item] = 'json_set(' . $item . ', \'$.' . $name . '\', ' . $this->parseDataBind($query, $key, $val, $bind, $suffix) . ')'; + } elseif (false === strpos($key, '.') && !in_array($key, $fields, true)) { if ($options['strict']) { throw new Exception('fields not exists:[' . $key . ']'); } - } elseif (isset($val[0]) && 'exp' == $val[0]) { - $result[$item] = $val[1]; } elseif (is_null($val)) { $result[$item] = 'NULL'; + } elseif (is_array($val) && !empty($val)) { + switch (strtoupper($val[0])) { + case 'INC': + $result[$item] = $item . ' + ' . floatval($val[1]); + break; + case 'DEC': + $result[$item] = $item . ' - ' . floatval($val[1]); + break; + case 'EXP': + throw new Exception('not support data:[' . $val[0] . ']'); + } } elseif (is_scalar($val)) { // 过滤非标量数据 - if ($this->query->isBind(substr($val, 1))) { - $result[$item] = $val; - } else { - $this->query->bind($key, $val, isset($bind[$key]) ? $bind[$key] : PDO::PARAM_STR); - $result[$item] = ':' . $key; - } + $result[$item] = $this->parseDataBind($query, $key, $val, $bind, $suffix); } } + return $result; } /** - * 字段名分析 + * 数据绑定处理 * @access protected - * @param string $key + * @param Query $query 查询对象 + * @param string $key 字段名 + * @param mixed $data 数据 + * @param array $bind 绑定数据 + * @param string $suffix 绑定后缀 * @return string */ - protected function parseKey($key) + protected function parseDataBind(Query $query, $key, $data, $bind = [], $suffix = '') { - return $key; + // 过滤非标量数据 + if (0 === strpos($data, ':') && $query->isBind(substr($data, 1))) { + return $data; + } + + $key = str_replace(['.', '->'], '_', $key); + $name = 'data__' . $key . $suffix; + + $query->bind($name, $data, isset($bind[$key]) ? $bind[$key] : PDO::PARAM_STR); + + return ':' . $name; } /** - * value分析 - * @access protected - * @param mixed $value - * @param string $field - * @return string|array + * 字段名分析 + * @access public + * @param Query $query 查询对象 + * @param mixed $key 字段名 + * @param bool $strict 严格检测 + * @return string */ - protected function parseValue($value, $field = '') + public function parseKey(Query $query, $key, $strict = false) { - if (is_string($value)) { - $value = strpos($value, ':') === 0 && $this->query->isBind(substr($value, 1)) ? $value : $this->connection->quote($value); - } elseif (is_array($value)) { - $value = array_map([$this, 'parseValue'], $value); - } elseif (is_bool($value)) { - $value = $value ? '1' : '0'; - } elseif (is_null($value)) { - $value = 'null'; - } - return $value; + return $key instanceof Expression ? $key->getValue() : $key; } /** * field分析 * @access protected - * @param mixed $fields + * @param Query $query 查询对象 + * @param mixed $fields 字段名 * @return string */ - protected function parseField($fields) + protected function parseField(Query $query, $fields) { if ('*' == $fields || empty($fields)) { $fieldsStr = '*'; } elseif (is_array($fields)) { // 支持 'field1'=>'field2' 这样的字段别名定义 $array = []; + foreach ($fields as $key => $field) { if (!is_numeric($key)) { - $array[] = $this->parseKey($key) . ' AS ' . $this->parseKey($field); + $array[] = $this->parseKey($query, $key) . ' AS ' . $this->parseKey($query, $field, true); } else { - $array[] = $this->parseKey($field); + $array[] = $this->parseKey($query, $field); } } + $fieldsStr = implode(',', $array); } + return $fieldsStr; } /** * table分析 * @access protected - * @param mixed $table + * @param Query $query 查询对象 + * @param mixed $tables 表名 * @return string */ - protected function parseTable($tables) + protected function parseTable(Query $query, $tables) { - if (is_array($tables)) { - // 支持别名定义 - foreach ($tables as $table => $alias) { - $array[] = !is_numeric($table) ? - $this->parseKey($table) . ' ' . $this->parseKey($alias) : - $this->parseKey($alias); + $item = []; + $options = $query->getOptions(); + + foreach ((array) $tables as $key => $table) { + if (!is_numeric($key)) { + $key = $this->connection->parseSqlTable($key); + $item[] = $this->parseKey($query, $key) . ' ' . $this->parseKey($query, $table); + } else { + $table = $this->connection->parseSqlTable($table); + + if (isset($options['alias'][$table])) { + $item[] = $this->parseKey($query, $table) . ' ' . $this->parseKey($query, $options['alias'][$table]); + } else { + $item[] = $this->parseKey($query, $table); + } } - $tables = $array; - } elseif (is_string($tables)) { - $tables = $this->parseSqlTable($tables); - $tables = array_map([$this, 'parseKey'], explode(',', $tables)); } - return implode(',', $tables); + + return implode(',', $item); } /** * where分析 * @access protected - * @param mixed $where 查询条件 - * @param array $options 查询参数 + * @param Query $query 查询对象 + * @param mixed $where 查询条件 * @return string */ - protected function parseWhere($where, $options) + protected function parseWhere(Query $query, $where) { - $whereStr = $this->buildWhere($where, $options); + $options = $query->getOptions(); + $whereStr = $this->buildWhere($query, $where); + + if (!empty($options['soft_delete'])) { + // 附加软删除条件 + list($field, $condition) = $options['soft_delete']; + + $binds = $this->connection->getFieldsBind($options['table']); + $whereStr = $whereStr ? '( ' . $whereStr . ' ) AND ' : ''; + $whereStr = $whereStr . $this->parseWhereItem($query, $field, $condition, '', $binds); + } + return empty($whereStr) ? '' : ' WHERE ' . $whereStr; } /** * 生成查询条件SQL * @access public - * @param mixed $where - * @param array $options + * @param Query $query 查询对象 + * @param mixed $where 查询条件 * @return string */ - public function buildWhere($where, $options) + public function buildWhere(Query $query, $where) { if (empty($where)) { $where = []; } - if ($where instanceof Query) { - return $this->buildWhere($where->getOptions('where'), $options); - } - $whereStr = ''; - $binds = $this->query->getFieldsBind($options); - foreach ($where as $key => $val) { + $binds = $this->connection->getFieldsBind($query->getOptions('table')); + + foreach ($where as $logic => $val) { $str = []; - foreach ($val as $field => $value) { + + foreach ($val as $value) { + if ($value instanceof Expression) { + $str[] = ' ' . $logic . ' ( ' . $value->getValue() . ' )'; + continue; + } + + if (is_array($value)) { + if (key($value) !== 0) { + throw new Exception('where express error:' . var_export($value, true)); + } + $field = array_shift($value); + } elseif (!($value instanceof \Closure)) { + throw new Exception('where express error:' . var_export($value, true)); + } + if ($value instanceof \Closure) { // 使用闭包查询 - $query = new Query($this->connection); - call_user_func_array($value, [ & $query]); - $str[] = ' ' . $key . ' ( ' . $this->buildWhere($query->getOptions('where'), $options) . ' )'; + $newQuery = $query->newQuery()->setConnection($this->connection); + $value($newQuery); + $whereClause = $this->buildWhere($query, $newQuery->getOptions('where')); + + if (!empty($whereClause)) { + $str[] = ' ' . $logic . ' ( ' . $whereClause . ' )'; + } + } elseif (is_array($field)) { + array_unshift($value, $field); + $str2 = []; + foreach ($value as $item) { + $str2[] = $this->parseWhereItem($query, array_shift($item), $item, $logic, $binds); + } + + $str[] = ' ' . $logic . ' ( ' . implode(' AND ', $str2) . ' )'; } elseif (strpos($field, '|')) { // 不同字段使用相同查询条件(OR) $array = explode('|', $field); $item = []; + foreach ($array as $k) { - $item[] = $this->parseWhereItem($k, $value, '', $options, $binds); + $item[] = $this->parseWhereItem($query, $k, $value, '', $binds); } - $str[] = ' ' . $key . ' ( ' . implode(' OR ', $item) . ' )'; + + $str[] = ' ' . $logic . ' ( ' . implode(' OR ', $item) . ' )'; } elseif (strpos($field, '&')) { // 不同字段使用相同查询条件(AND) $array = explode('&', $field); $item = []; + foreach ($array as $k) { - $item[] = $this->parseWhereItem($k, $value, '', $options, $binds); + $item[] = $this->parseWhereItem($query, $k, $value, '', $binds); } - $str[] = ' ' . $key . ' ( ' . implode(' AND ', $item) . ' )'; + + $str[] = ' ' . $logic . ' ( ' . implode(' AND ', $item) . ' )'; } else { // 对字段使用表达式查询 $field = is_string($field) ? $field : ''; - $str[] = ' ' . $key . ' ' . $this->parseWhereItem($field, $value, $key, $options, $binds); + $str[] = ' ' . $logic . ' ' . $this->parseWhereItem($query, $field, $value, $logic, $binds); } } - $whereStr .= empty($whereStr) ? substr(implode(' ', $str), strlen($key) + 1) : implode(' ', $str); + $whereStr .= empty($whereStr) ? substr(implode(' ', $str), strlen($logic) + 1) : implode(' ', $str); } + return $whereStr; } // where子单元分析 - protected function parseWhereItem($field, $val, $rule = '', $options = [], $binds = [], $bindName = null) + protected function parseWhereItem(Query $query, $field, $val, $rule = '', $binds = [], $bindName = null) { // 字段分析 - $key = $field ? $this->parseKey($field) : ''; + $key = $field ? $this->parseKey($query, $field, true) : ''; // 查询规则和条件 if (!is_array($val)) { - $val = ['=', $val]; + $val = is_null($val) ? ['NULL', ''] : ['=', $val]; } + list($exp, $value) = $val; // 对一个字段使用多个查询条件 if (is_array($exp)) { $item = array_pop($val); + // 传入 or 或者 and if (is_string($item) && in_array($item, ['AND', 'and', 'OR', 'or'])) { $rule = $item; } else { array_push($val, $item); } + foreach ($val as $k => $item) { $bindName = 'where_' . str_replace('.', '_', $field) . '_' . $k; - $str[] = $this->parseWhereItem($field, $item, $rule, $options, $binds, $bindName); + $str[] = $this->parseWhereItem($query, $field, $item, $rule, $binds, $bindName); } + return '( ' . implode(' ' . $rule . ' ', $str) . ' )'; } // 检测操作符 - if (!in_array($exp, $this->exp)) { - $exp = strtolower($exp); - if (isset($this->exp[$exp])) { - $exp = $this->exp[$exp]; - } else { - throw new Exception('where express error:' . $exp); - } + $exp = strtoupper($exp); + if (isset($this->exp[$exp])) { + $exp = $this->exp[$exp]; + } + + $bindName = $bindName ?: 'where_' . $rule . '_' . str_replace(['.', '-'], '_', $field); + + if (preg_match('/\W/', $bindName)) { + // 处理带非单词字符的字段名 + $bindName = md5($bindName); } - $bindName = $bindName ?: 'where_' . str_replace('.', '_', $field); - $bindType = isset($binds[$field]) ? $binds[$field] : PDO::PARAM_STR; - if (is_scalar($value) && array_key_exists($field, $binds) && !in_array($exp, ['EXP', 'NOT NULL', 'NULL', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN']) && strpos($exp, 'TIME') === false) { - if (strpos($value, ':') !== 0 || !$this->query->isBind(substr($value, 1))) { - if ($this->query->isBind($bindName)) { - $bindName .= '_' . uniqid(); + + if ($value instanceof Expression) { + + } elseif (is_object($value) && method_exists($value, '__toString')) { + // 对象数据写入 + $value = $value->__toString(); + } + + if (strpos($field, '->')) { + $jsonType = $query->getJsonFieldType($field); + $bindType = $this->connection->getFieldBindType($jsonType); + } else { + $bindType = isset($binds[$field]) ? $binds[$field] : PDO::PARAM_STR; + } + + if (is_scalar($value) && !in_array($exp, ['EXP', 'NOT NULL', 'NULL', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN']) && strpos($exp, 'TIME') === false) { + if (strpos($value, ':') !== 0 || !$query->isBind(substr($value, 1))) { + if ($query->isBind($bindName)) { + $bindName .= '_' . str_replace('.', '_', uniqid('', true)); } - $this->query->bind($bindName, $value, $bindType); + + $query->bind($bindName, $value, $bindType); $value = ':' . $bindName; } } - $whereStr = ''; - if (in_array($exp, ['=', '<>', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE'])) { - // 比较运算 及 模糊匹配 - $whereStr .= $key . ' ' . $exp . ' ' . $this->parseValue($value, $field); - } elseif ('EXP' == $exp) { - // 表达式查询 - $whereStr .= '( ' . $key . ' ' . $value . ' )'; - } elseif (in_array($exp, ['NOT NULL', 'NULL'])) { - // NULL 查询 - $whereStr .= $key . ' IS ' . $exp; - } elseif (in_array($exp, ['NOT IN', 'IN'])) { - // IN 查询 - if ($value instanceof \Closure) { - $whereStr .= $key . ' ' . $exp . ' ' . $this->parseClosure($value); - } else { - $value = is_array($value) ? $value : explode(',', $value); - if (array_key_exists($field, $binds)) { - $bind = []; - $array = []; - foreach ($value as $k => $v) { - $bind[$bindName . '_in_' . $k] = [$v, $bindType]; - $array[] = ':' . $bindName . '_in_' . $k; - } - $this->query->bind($bind); - $zone = implode(',', $array); - } else { - $zone = implode(',', $this->parseValue($value, $field)); - } - $whereStr .= $key . ' ' . $exp . ' (' . $zone . ')'; - } - } elseif (in_array($exp, ['NOT BETWEEN', 'BETWEEN'])) { - // BETWEEN 查询 - $data = is_array($value) ? $value : explode(',', $value); - if (array_key_exists($field, $binds)) { - $bind = [ - $bindName . '_between_1' => [$data[0], $bindType], - $bindName . '_between_2' => [$data[1], $bindType], - ]; - $this->query->bind($bind); - $between = ':' . $bindName . '_between_1' . ' AND :' . $bindName . '_between_2'; - } else { - $between = $this->parseValue($data[0], $field) . ' AND ' . $this->parseValue($data[1], $field); + // 解析查询表达式 + foreach ($this->parser as $fun => $parse) { + if (in_array($exp, $parse)) { + $whereStr = $this->$fun($query, $key, $exp, $value, $field, $bindName, $bindType, isset($val[2]) ? $val[2] : 'AND'); + break; } - $whereStr .= $key . ' ' . $exp . ' ' . $between; - } elseif (in_array($exp, ['NOT EXISTS', 'EXISTS'])) { - // EXISTS 查询 - if ($value instanceof \Closure) { - $whereStr .= $exp . ' ' . $this->parseClosure($value); - } else { - $whereStr .= $exp . ' (' . $value . ')'; - } - } elseif (in_array($exp, ['< TIME', '> TIME', '<= TIME', '>= TIME'])) { - $whereStr .= $key . ' ' . substr($exp, 0, 2) . ' ' . $this->parseDateTime($value, $field, $options, $bindName, $bindType); - } elseif (in_array($exp, ['BETWEEN TIME', 'NOT BETWEEN TIME'])) { - if (is_string($value)) { - $value = explode(',', $value); + } + + if (!isset($whereStr)) { + throw new Exception('where express error:' . $exp); + } + + return $whereStr; + } + + /** + * 模糊查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param mixed $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @param string $logic + * @return string + */ + protected function parseLike(Query $query, $key, $exp, $value, $field, $bindName, $bindType, $logic) + { + // 模糊匹配 + if (is_array($value)) { + foreach ($value as $k => $item) { + $bindKey = $bindName . '_' . intval($k); + $bind[$bindKey] = [$item, $bindType]; + $array[] = $key . ' ' . $exp . ' :' . $bindKey; } - $whereStr .= $key . ' ' . substr($exp, 0, -4) . $this->parseDateTime($value[0], $field, $options, $bindName . '_between_1', $bindType) . ' AND ' . $this->parseDateTime($value[1], $field, $options, $bindName . '_between_2', $bindType); + $query->bind($bind); + + $whereStr = '(' . implode($array, ' ' . strtoupper($logic) . ' ') . ')'; + } else { + $whereStr = $key . ' ' . $exp . ' ' . $value; } + return $whereStr; } - // 执行闭包子查询 - protected function parseClosure($call, $show = true) + /** + * 表达式查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param array $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @return string + */ + protected function parseColumn(Query $query, $key, $exp, array $value, $field, $bindName, $bindType) + { + // 字段比较查询 + list($op, $field2) = $value; + + if (!in_array($op, ['=', '<>', '>', '>=', '<', '<='])) { + throw new Exception('where express error:' . var_export($value, true)); + } + + return '( ' . $key . ' ' . $op . ' ' . $this->parseKey($query, $field2, true) . ' )'; + } + + /** + * 表达式查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param Expression $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @return string + */ + protected function parseExp(Query $query, $key, $exp, Expression $value, $field, $bindName, $bindType) + { + // 表达式查询 + return '( ' . $key . ' ' . $value->getValue() . ' )'; + } + + /** + * Null查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param mixed $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @return string + */ + protected function parseNull(Query $query, $key, $exp, $value, $field, $bindName, $bindType) + { + // NULL 查询 + return $key . ' IS ' . $exp; + } + + /** + * 范围查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param mixed $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @return string + */ + protected function parseBetween(Query $query, $key, $exp, $value, $field, $bindName, $bindType) { - $query = new Query($this->connection); - call_user_func_array($call, [ & $query]); - return $query->buildSql($show); + // BETWEEN 查询 + $data = is_array($value) ? $value : explode(',', $value); + + if ($query->isBind($bindName . '_between_1')) { + $bindKey1 = $bindName . '_between_1' . uniqid(); + $bindKey2 = $bindName . '_between_2' . uniqid(); + } else { + $bindKey1 = $bindName . '_between_1'; + $bindKey2 = $bindName . '_between_2'; + } + + $bind = [ + $bindKey1 => [$data[0], $bindType], + $bindKey2 => [$data[1], $bindType], + ]; + + $query->bind($bind); + + $between = ':' . $bindKey1 . ' AND :' . $bindKey2; + + return $key . ' ' . $exp . ' ' . $between; + } + + /** + * Exists查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param mixed $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @return string + */ + protected function parseExists(Query $query, $key, $exp, $value, $field, $bindName, $bindType) + { + // EXISTS 查询 + if ($value instanceof \Closure) { + $value = $this->parseClosure($query, $value, false); + } elseif ($value instanceof Expression) { + $value = $value->getValue(); + } else { + throw new Exception('where express error:' . $value); + } + + return $exp . ' (' . $value . ')'; + } + + /** + * 时间比较查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param mixed $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @return string + */ + protected function parseTime(Query $query, $key, $exp, $value, $field, $bindName, $bindType) + { + return $key . ' ' . substr($exp, 0, 2) . ' ' . $this->parseDateTime($query, $value, $field, $bindName, $bindType); + } + + /** + * 大小比较查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param mixed $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @return string + */ + protected function parseCompare(Query $query, $key, $exp, $value, $field, $bindName, $bindType) + { + if (is_array($value)) { + throw new Exception('where express error:' . $exp . var_export($value, true)); + } + + // 比较运算 + if ($value instanceof \Closure) { + $value = $this->parseClosure($query, $value); + } + + return $key . ' ' . $exp . ' ' . $value; + } + + /** + * 时间范围查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param mixed $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @return string + */ + protected function parseBetweenTime(Query $query, $key, $exp, $value, $field, $bindName, $bindType) + { + if (is_string($value)) { + $value = explode(',', $value); + } + + return $key . ' ' . substr($exp, 0, -4) + . $this->parseDateTime($query, $value[0], $field, $bindName . '_between_1', $bindType) + . ' AND ' + . $this->parseDateTime($query, $value[1], $field, $bindName . '_between_2', $bindType); + + } + + /** + * IN查询 + * @access protected + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param mixed $value + * @param string $field + * @param string $bindName + * @param integer $bindType + * @return string + */ + protected function parseIn(Query $query, $key, $exp, $value, $field, $bindName, $bindType) + { + // IN 查询 + if ($value instanceof \Closure) { + $value = $this->parseClosure($query, $value, false); + } else { + $value = array_unique(is_array($value) ? $value : explode(',', $value)); + + $bind = []; + $array = []; + $i = 0; + + foreach ($value as $k => $v) { + $i++; + if ($query->isBind($bindName . '_in_' . $i)) { + $bindKey = $bindName . '_in_' . uniqid() . '_' . $i; + } else { + $bindKey = $bindName . '_in_' . $i; + } + $bind[$bindKey] = [$v, $bindType]; + $array[] = ':' . $bindKey; + } + + $zone = implode(',', $array); + $query->bind($bind); + + $value = empty($zone) ? "''" : $zone; + } + + return $key . ' ' . $exp . ' (' . $value . ')'; + } + + /** + * 闭包子查询 + * @access protected + * @param Query $query 查询对象 + * @param \Closure $call + * @param bool $show + * @return string + */ + protected function parseClosure(Query $query, $call, $show = true) + { + $newQuery = $query->newQuery()->setConnection($this->connection); + $call($newQuery); + + return $newQuery->buildSql($show); } /** * 日期时间条件解析 * @access protected - * @param string $value - * @param string $key - * @param array $options - * @param string $bindName - * @param integer $bindType + * @param Query $query 查询对象 + * @param string $value + * @param string $key + * @param array $options + * @param string $bindName + * @param integer $bindType * @return string */ - protected function parseDateTime($value, $key, $options = [], $bindName = null, $bindType = null) + protected function parseDateTime(Query $query, $value, $key, $bindName = null, $bindType = null) { + $options = $query->getOptions(); + // 获取时间字段类型 - $type = $this->query->getFieldsType($options); + if (strpos($key, '.')) { + list($table, $key) = explode('.', $key); + + if (isset($options['alias']) && $pos = array_search($table, $options['alias'])) { + $table = $pos; + } + } else { + $table = $options['table']; + } + + $type = $this->connection->getTableInfo($table, 'type'); + if (isset($type[$key])) { $info = $type[$key]; } + if (isset($info)) { - $value = strtotime($value) ?: $value; + if (is_string($value)) { + $value = strtotime($value) ?: $value; + } + if (preg_match('/(datetime|timestamp)/is', $info)) { // 日期及时间戳类型 $value = date('Y-m-d H:i:s', $value); @@ -406,18 +775,26 @@ abstract class Builder $value = date('Y-m-d', $value); } } + $bindName = $bindName ?: $key; - $this->query->bind($bindName, $value, $bindType); + + if ($query->isBind($bindName)) { + $bindName .= '_' . str_replace('.', '_', uniqid('', true)); + } + + $query->bind($bindName, $value, $bindType); + return ':' . $bindName; } /** * limit分析 * @access protected - * @param mixed $lmit + * @param Query $query 查询对象 + * @param mixed $limit * @return string */ - protected function parseLimit($limit) + protected function parseLimit(Query $query, $limit) { return (!empty($limit) && false === strpos($limit, '(')) ? ' LIMIT ' . $limit . ' ' : ''; } @@ -425,63 +802,141 @@ abstract class Builder /** * join分析 * @access protected - * @param mixed $join + * @param Query $query 查询对象 + * @param array $join * @return string */ - protected function parseJoin($join) + protected function parseJoin(Query $query, $join) { $joinStr = ''; + if (!empty($join)) { - $joinStr = ' ' . implode(' ', $join) . ' '; + foreach ($join as $item) { + list($table, $type, $on) = $item; + + $condition = []; + + foreach ((array) $on as $val) { + if ($val instanceof Expression) { + $condition[] = $val->getValue(); + } elseif (strpos($val, '=')) { + list($val1, $val2) = explode('=', $val, 2); + + $condition[] = $this->parseKey($query, $val1) . '=' . $this->parseKey($query, $val2); + } else { + $condition[] = $val; + } + } + + $table = $this->parseTable($query, $table); + + $joinStr .= ' ' . $type . ' JOIN ' . $table . ' ON ' . implode(' AND ', $condition); + } } + return $joinStr; } /** * order分析 * @access protected - * @param mixed $order + * @param Query $query 查询对象 + * @param mixed $order * @return string */ - protected function parseOrder($order) + protected function parseOrder(Query $query, $order) { - if (is_array($order)) { - $array = []; - foreach ($order as $key => $val) { + if (empty($order)) { + return ''; + } + + $array = []; + + foreach ($order as $key => $val) { + if ($val instanceof Expression) { + $array[] = $val->getValue(); + } elseif (is_array($val)) { + $array[] = $this->parseOrderField($query, $key, $val); + } elseif ('[rand]' == $val) { + $array[] = $this->parseRand($query); + } else { if (is_numeric($key)) { - if (false === strpos($val, '(')) { - $array[] = $this->parseKey($val); - } elseif ('[rand]' == $val) { - $array[] = $this->parseRand(); - } + list($key, $sort) = explode(' ', strpos($val, ' ') ? $val : $val . ' '); } else { - $sort = in_array(strtolower(trim($val)), ['asc', 'desc']) ? ' ' . $val : ''; - $array[] = $this->parseKey($key) . ' ' . $sort; + $sort = $val; } + + $sort = strtoupper($sort); + $sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : ''; + $array[] = $this->parseKey($query, $key, true) . $sort; } - $order = implode(',', $array); } - return !empty($order) ? ' ORDER BY ' . $order : ''; + + return ' ORDER BY ' . implode(',', $array); + } + + /** + * orderField分析 + * @access protected + * @param Query $query 查询对象 + * @param mixed $key + * @param array $val + * @return string + */ + protected function parseOrderField($query, $key, $val) + { + if (isset($val['sort'])) { + $sort = $val['sort']; + unset($val['sort']); + } else { + $sort = ''; + } + + $sort = strtoupper($sort); + $sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : ''; + + $options = $query->getOptions(); + $bind = $this->connection->getFieldsBind($options['table']); + + foreach ($val as $k => $item) { + $val[$k] = $this->parseDataBind($query, $key, $item, $bind, $k); + } + + return 'field(' . $this->parseKey($query, $key, true) . ',' . implode(',', $val) . ')' . $sort; } /** * group分析 * @access protected - * @param mixed $group + * @param Query $query 查询对象 + * @param mixed $group * @return string */ - protected function parseGroup($group) + protected function parseGroup(Query $query, $group) { - return !empty($group) ? ' GROUP BY ' . $group : ''; + if (empty($group)) { + return ''; + } + + if (is_string($group)) { + $group = explode(',', $group); + } + + foreach ($group as $key) { + $val[] = $this->parseKey($query, $key); + } + + return ' GROUP BY ' . implode(',', $val); } /** * having分析 * @access protected - * @param string $having + * @param Query $query 查询对象 + * @param string $having * @return string */ - protected function parseHaving($having) + protected function parseHaving(Query $query, $having) { return !empty($having) ? ' HAVING ' . $having : ''; } @@ -489,21 +944,27 @@ abstract class Builder /** * comment分析 * @access protected - * @param string $comment + * @param Query $query 查询对象 + * @param string $comment * @return string */ - protected function parseComment($comment) + protected function parseComment(Query $query, $comment) { + if (false !== strpos($comment, '*/')) { + $comment = strstr($comment, '*/', true); + } + return !empty($comment) ? ' /* ' . $comment . ' */' : ''; } /** * distinct分析 * @access protected - * @param mixed $distinct + * @param Query $query 查询对象 + * @param mixed $distinct * @return string */ - protected function parseDistinct($distinct) + protected function parseDistinct(Query $query, $distinct) { return !empty($distinct) ? ' DISTINCT ' : ''; } @@ -511,235 +972,253 @@ abstract class Builder /** * union分析 * @access protected - * @param mixed $union + * @param Query $query 查询对象 + * @param mixed $union * @return string */ - protected function parseUnion($union) + protected function parseUnion(Query $query, $union) { if (empty($union)) { return ''; } + $type = $union['type']; unset($union['type']); + foreach ($union as $u) { if ($u instanceof \Closure) { - $sql[] = $type . ' ' . $this->parseClosure($u, false); + $sql[] = $type . ' ' . $this->parseClosure($query, $u); } elseif (is_string($u)) { - $sql[] = $type . ' ' . $this->parseSqlTable($u); + $sql[] = $type . ' ( ' . $this->connection->parseSqlTable($u) . ' )'; } } - return implode(' ', $sql); + + return ' ' . implode(' ', $sql); } /** * index分析,可在操作链中指定需要强制使用的索引 * @access protected - * @param mixed $index + * @param Query $query 查询对象 + * @param mixed $index * @return string */ - protected function parseForce($index) + protected function parseForce(Query $query, $index) { if (empty($index)) { return ''; } - if (is_array($index)) { - $index = join(",", $index); - } - - return sprintf(" FORCE INDEX ( %s ) ", $index); + return sprintf(" FORCE INDEX ( %s ) ", is_array($index) ? implode(',', $index) : $index); } /** * 设置锁机制 * @access protected - * @param bool $locl + * @param Query $query 查询对象 + * @param bool|string $lock * @return string */ - protected function parseLock($lock = false) + protected function parseLock(Query $query, $lock = false) { - return $lock ? ' FOR UPDATE ' : ''; + if (is_bool($lock)) { + return $lock ? ' FOR UPDATE ' : ''; + } elseif (is_string($lock) && !empty($lock)) { + return ' ' . trim($lock) . ' '; + } } /** * 生成查询SQL * @access public - * @param array $options 表达式 + * @param Query $query 查询对象 * @return string */ - public function select($options = []) + public function select(Query $query) { - $sql = str_replace( + $options = $query->getOptions(); + + return str_replace( ['%TABLE%', '%DISTINCT%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'], [ - $this->parseTable($options['table']), - $this->parseDistinct($options['distinct']), - $this->parseField($options['field']), - $this->parseJoin($options['join']), - $this->parseWhere($options['where'], $options), - $this->parseGroup($options['group']), - $this->parseHaving($options['having']), - $this->parseOrder($options['order']), - $this->parseLimit($options['limit']), - $this->parseUnion($options['union']), - $this->parseLock($options['lock']), - $this->parseComment($options['comment']), - $this->parseForce($options['force']), - ], $this->selectSql); - return $sql; - } - - /** - * 生成insert SQL + $this->parseTable($query, $options['table']), + $this->parseDistinct($query, $options['distinct']), + $this->parseField($query, $options['field']), + $this->parseJoin($query, $options['join']), + $this->parseWhere($query, $options['where']), + $this->parseGroup($query, $options['group']), + $this->parseHaving($query, $options['having']), + $this->parseOrder($query, $options['order']), + $this->parseLimit($query, $options['limit']), + $this->parseUnion($query, $options['union']), + $this->parseLock($query, $options['lock']), + $this->parseComment($query, $options['comment']), + $this->parseForce($query, $options['force']), + ], + $this->selectSql); + } + + /** + * 生成Insert SQL * @access public - * @param array $data 数据 - * @param array $options 表达式 - * @param bool $replace 是否replace + * @param Query $query 查询对象 + * @param bool $replace 是否replace * @return string */ - public function insert(array $data, $options = [], $replace = false) + public function insert(Query $query, $replace = false) { + $options = $query->getOptions(); + // 分析并处理数据 - $data = $this->parseData($data, $options); + $data = $this->parseData($query, $options['data']); if (empty($data)) { - return 0; + return ''; } + $fields = array_keys($data); $values = array_values($data); - $sql = str_replace( + return str_replace( ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'], [ $replace ? 'REPLACE' : 'INSERT', - $this->parseTable($options['table']), + $this->parseTable($query, $options['table']), implode(' , ', $fields), implode(' , ', $values), - $this->parseComment($options['comment']), - ], $this->insertSql); - - return $sql; + $this->parseComment($query, $options['comment']), + ], + $this->insertSql); } /** * 生成insertall SQL * @access public - * @param array $dataSet 数据集 - * @param array $options 表达式 + * @param Query $query 查询对象 + * @param array $dataSet 数据集 + * @param bool $replace 是否replace * @return string */ - public function insertAll($dataSet, $options) + public function insertAll(Query $query, $dataSet, $replace = false) { + $options = $query->getOptions(); + // 获取合法的字段 if ('*' == $options['field']) { - $fields = array_keys($this->query->getFieldsType($options)); + $allowFields = $this->connection->getTableFields($options['table']); } else { - $fields = $options['field']; + $allowFields = $options['field']; } - foreach ($dataSet as &$data) { - foreach ($data as $key => $val) { - if (!in_array($key, $fields, true)) { - if ($options['strict']) { - throw new Exception('fields not exists:[' . $key . ']'); - } - unset($data[$key]); - } elseif (is_scalar($val)) { - $data[$key] = $this->parseValue($val, $key); - } else { - // 过滤掉非标量数据 - unset($data[$key]); - } + // 获取绑定信息 + $bind = $this->connection->getFieldsBind($options['table']); + + foreach ($dataSet as $k => $data) { + $data = $this->parseData($query, $data, $allowFields, $bind, '_' . $k); + + $values[] = 'SELECT ' . implode(',', array_values($data)); + + if (!isset($insertFields)) { + $insertFields = array_keys($data); } - $value = array_values($data); - $values[] = 'SELECT ' . implode(',', $value); } - $fields = array_map([$this, 'parseKey'], array_keys(reset($dataSet))); - $sql = str_replace( - ['%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'], + + $fields = []; + + foreach ($insertFields as $field) { + $fields[] = $this->parseKey($query, $field); + } + + return str_replace( + ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'], [ - $this->parseTable($options['table']), + $replace ? 'REPLACE' : 'INSERT', + $this->parseTable($query, $options['table']), implode(' , ', $fields), implode(' UNION ALL ', $values), - $this->parseComment($options['comment']), - ], $this->insertAllSql); - - return $sql; + $this->parseComment($query, $options['comment']), + ], + $this->insertAllSql); } /** - * 生成slectinsert SQL + * 生成slect insert SQL * @access public - * @param array $fields 数据 - * @param string $table 数据表 - * @param array $options 表达式 + * @param Query $query 查询对象 + * @param array $fields 数据 + * @param string $table 数据表 * @return string */ - public function selectInsert($fields, $table, $options) + public function selectInsert(Query $query, $fields, $table) { if (is_string($fields)) { $fields = explode(',', $fields); } - $fields = array_map([$this, 'parseKey'], $fields); - $sql = 'INSERT INTO ' . $this->parseTable($table) . ' (' . implode(',', $fields) . ') ' . $this->select($options); - return $sql; + foreach ($fields as &$field) { + $field = $this->parseKey($query, $field, true); + } + + return 'INSERT INTO ' . $this->parseTable($query, $table) . ' (' . implode(',', $fields) . ') ' . $this->select($query); } /** * 生成update SQL * @access public - * @param array $fields 数据 - * @param array $options 表达式 + * @param Query $query 查询对象 * @return string */ - public function update($data, $options) + public function update(Query $query) { - $table = $this->parseTable($options['table']); - $data = $this->parseData($data, $options); + $options = $query->getOptions(); + + $table = $this->parseTable($query, $options['table']); + $data = $this->parseData($query, $options['data']); + if (empty($data)) { return ''; } + foreach ($data as $key => $val) { - $set[] = $key . '=' . $val; + $set[] = $key . ' = ' . $val; } - $sql = str_replace( + return str_replace( ['%TABLE%', '%SET%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'], [ - $this->parseTable($options['table']), - implode(',', $set), - $this->parseJoin($options['join']), - $this->parseWhere($options['where'], $options), - $this->parseOrder($options['order']), - $this->parseLimit($options['limit']), - $this->parseLock($options['lock']), - $this->parseComment($options['comment']), - ], $this->updateSql); - - return $sql; + $this->parseTable($query, $options['table']), + implode(' , ', $set), + $this->parseJoin($query, $options['join']), + $this->parseWhere($query, $options['where']), + $this->parseOrder($query, $options['order']), + $this->parseLimit($query, $options['limit']), + $this->parseLock($query, $options['lock']), + $this->parseComment($query, $options['comment']), + ], + $this->updateSql); } /** * 生成delete SQL * @access public - * @param array $options 表达式 + * @param Query $query 查询对象 * @return string */ - public function delete($options) + public function delete(Query $query) { - $sql = str_replace( + $options = $query->getOptions(); + + return str_replace( ['%TABLE%', '%USING%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'], [ - $this->parseTable($options['table']), - !empty($options['using']) ? ' USING ' . $this->parseTable($options['using']) . ' ' : '', - $this->parseJoin($options['join']), - $this->parseWhere($options['where'], $options), - $this->parseOrder($options['order']), - $this->parseLimit($options['limit']), - $this->parseLock($options['lock']), - $this->parseComment($options['comment']), - ], $this->deleteSql); - - return $sql; + $this->parseTable($query, $options['table']), + !empty($options['using']) ? ' USING ' . $this->parseTable($query, $options['using']) . ' ' : '', + $this->parseJoin($query, $options['join']), + $this->parseWhere($query, $options['where']), + $this->parseOrder($query, $options['order']), + $this->parseLimit($query, $options['limit']), + $this->parseLock($query, $options['lock']), + $this->parseComment($query, $options['comment']), + ], + $this->deleteSql); } } diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index f405f9b9f812ca5829a70a17deb51b31ec043dcf..72722362bbcd4171c3d38c4a6dd706b67e61de35 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,27 +11,20 @@ namespace think\db; +use InvalidArgumentException; use PDO; use PDOStatement; -use think\Collection; +use think\Container; use think\Db; use think\db\exception\BindParamException; -use think\db\Query; use think\Debug; use think\Exception; use think\exception\PDOException; -use think\Log; - -/** - * Class Connection - * @package think - * @method Query table(string $table) 指定数据表(含前缀) - * @method Query name(string $name) 指定数据表(不含前缀) - * - */ +use think\Loader; + abstract class Connection { - + protected static $instance = []; /** @var PDOStatement PDO操作实例 */ protected $PDOStatement; @@ -52,60 +45,72 @@ abstract class Connection protected $linkRead; protected $linkWrite; - // 查询结果类型 - protected $resultSetType = 'array'; // 查询结果类型 protected $fetchType = PDO::FETCH_ASSOC; // 字段属性大小写 protected $attrCase = PDO::CASE_LOWER; // 监听回调 protected static $event = []; - // 查询对象 - protected $query = []; + + // 数据表信息 + protected static $info = []; + + // 使用Builder类 + protected $builderClassName; + // Builder对象 + protected $builder; // 数据库连接参数配置 protected $config = [ // 数据库类型 - 'type' => '', + 'type' => '', // 服务器地址 - 'hostname' => '', + 'hostname' => '', // 数据库名 - 'database' => '', + 'database' => '', // 用户名 - 'username' => '', + 'username' => '', // 密码 - 'password' => '', + 'password' => '', // 端口 - 'hostport' => '', + 'hostport' => '', // 连接dsn - 'dsn' => '', + 'dsn' => '', // 数据库连接参数 - 'params' => [], + 'params' => [], // 数据库编码默认采用utf8 - 'charset' => 'utf8', + 'charset' => 'utf8', // 数据库表前缀 - 'prefix' => '', + 'prefix' => '', // 数据库调试模式 - 'debug' => false, + 'debug' => false, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) - 'deploy' => 0, + 'deploy' => 0, // 数据库读写是否分离 主从式有效 - 'rw_separate' => false, + 'rw_separate' => false, // 读写分离后 主服务器数量 - 'master_num' => 1, + 'master_num' => 1, // 指定从服务器序号 - 'slave_no' => '', + 'slave_no' => '', + // 模型写入后自动读取主服务器 + 'read_master' => false, // 是否严格检查字段是否存在 - 'fields_strict' => true, + 'fields_strict' => true, // 数据集返回类型 - 'resultset_type' => 'array', + 'resultset_type' => '', // 自动写入时间戳字段 - 'auto_timestamp' => false, + 'auto_timestamp' => false, + // 时间字段取出后的默认时间格式 + 'datetime_format' => 'Y-m-d H:i:s', // 是否需要进行SQL性能分析 - 'sql_explain' => false, + 'sql_explain' => false, // Builder类 - 'builder' => '', + 'builder' => '', // Query类 - 'query' => '\\think\\db\\Query', + 'query' => '\\think\\db\\Query', + // 是否需要断线重连 + 'break_reconnect' => false, + // 断线标识字符串 + 'break_match_str' => [], ]; // PDO连接参数 @@ -117,54 +122,125 @@ abstract class Connection PDO::ATTR_EMULATE_PREPARES => false, ]; + // 服务器断线标识字符 + protected $breakMatchStr = [ + 'server has gone away', + 'no connection to the server', + 'Lost connection', + 'is dead or not enabled', + 'Error while sending', + 'decryption failed or bad record mac', + 'server closed the connection unexpectedly', + 'SSL connection has been closed unexpectedly', + 'Error writing data to the connection', + 'Resource deadlock avoided', + 'failed with errno', + ]; + + // 绑定参数 + protected $bind = []; + /** * 架构函数 读取数据库配置信息 * @access public - * @param array $config 数据库配置数组 + * @param array $config 数据库配置数组 */ public function __construct(array $config = []) { if (!empty($config)) { $this->config = array_merge($this->config, $config); } + + // 创建Builder对象 + $class = $this->getBuilderClass(); + + $this->builder = new $class($this); + + // 执行初始化操作 + $this->initialize(); } /** - * 创建指定模型的查询对象 + * 初始化 + * @access protected + * @return void + */ + protected function initialize() + {} + + /** + * 取得数据库连接类实例 * @access public - * @param string $model 模型类名称 - * @param string $queryClass 查询对象类名 - * @return Query + * @param mixed $config 连接配置 + * @param bool|string $name 连接标识 true 强制重新连接 + * @return Connection + * @throws Exception */ - public function model($model, $queryClass = '') + public static function instance($config = [], $name = false) { - if (!isset($this->query[$model])) { - $class = $queryClass ?: $this->config['query']; - $this->query[$model] = new $class($this, $model); + if (false === $name) { + $name = md5(serialize($config)); + } + + if (true === $name || !isset(self::$instance[$name])) { + if (empty($config['type'])) { + throw new InvalidArgumentException('Undefined db type'); + } + + // 记录初始化信息 + Container::get('app')->log('[ DB ] INIT ' . $config['type']); + + if (true === $name) { + $name = md5(serialize($config)); + } + + self::$instance[$name] = Loader::factory($config['type'], '\\think\\db\\connector\\', $config); } - return $this->query[$model]; + + return self::$instance[$name]; } /** - * 调用Query类的查询方法 + * 获取当前连接器类对应的Builder类 * @access public - * @param string $method 方法名称 - * @param array $args 调用参数 - * @return mixed + * @return string */ - public function __call($method, $args) + public function getBuilderClass() { - if (!isset($this->query['database'])) { - $class = $this->config['query']; - $this->query['database'] = new $class($this); + if (!empty($this->builderClassName)) { + return $this->builderClassName; } - return call_user_func_array([$this->query['database'], $method], $args); + + return $this->getConfig('builder') ?: '\\think\\db\\builder\\' . ucfirst($this->getConfig('type')); + } + + /** + * 设置当前的数据库Builder对象 + * @access protected + * @param Builder $builder + * @return void + */ + protected function setBuilder(Builder $builder) + { + $this->builder = $builder; + + return $this; + } + + /** + * 获取当前的builder实例对象 + * @access public + * @return Builder + */ + public function getBuilder() + { + return $this->builder; } /** * 解析pdo连接的dsn信息 * @access protected - * @param array $config 连接信息 + * @param array $config 连接信息 * @return string */ abstract protected function parseDsn($config); @@ -172,7 +248,7 @@ abstract class Connection /** * 取得数据表的字段信息 * @access public - * @param string $tableName + * @param string $tableName * @return array */ abstract public function getFields($tableName); @@ -188,7 +264,7 @@ abstract class Connection /** * SQL性能分析 * @access protected - * @param string $sql + * @param string $sql * @return array */ abstract protected function getExplain($sql); @@ -196,7 +272,7 @@ abstract class Connection /** * 对返数据表字段信息进行大小写转换出来 * @access public - * @param array $info 字段信息 + * @param array $info 字段信息 * @return array */ public function fieldCase($info) @@ -213,13 +289,173 @@ abstract class Connection default: // 不做转换 } + return $info; } + /** + * 获取字段绑定类型 + * @access public + * @param string $type 字段类型 + * @return integer + */ + public function getFieldBindType($type) + { + if (0 === strpos($type, 'set') || 0 === strpos($type, 'enum')) { + $bind = PDO::PARAM_STR; + } elseif (preg_match('/(int|double|float|decimal|real|numeric|serial|bit)/is', $type)) { + $bind = PDO::PARAM_INT; + } elseif (preg_match('/bool/is', $type)) { + $bind = PDO::PARAM_BOOL; + } else { + $bind = PDO::PARAM_STR; + } + + return $bind; + } + + /** + * 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写) + * @access public + * @param string $sql sql语句 + * @return string + */ + public function parseSqlTable($sql) + { + if (false !== strpos($sql, '__')) { + $prefix = $this->getConfig('prefix'); + $sql = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) { + return $prefix . strtolower($match[1]); + }, $sql); + } + + return $sql; + } + + /** + * 获取数据表信息 + * @access public + * @param mixed $tableName 数据表名 留空自动获取 + * @param string $fetch 获取信息类型 包括 fields type bind pk + * @return mixed + */ + public function getTableInfo($tableName, $fetch = '') + { + if (is_array($tableName)) { + $tableName = key($tableName) ?: current($tableName); + } + + if (strpos($tableName, ',')) { + // 多表不获取字段信息 + return false; + } else { + $tableName = $this->parseSqlTable($tableName); + } + + // 修正子查询作为表名的问题 + if (strpos($tableName, ')')) { + return []; + } + + list($tableName) = explode(' ', $tableName); + + if (!strpos($tableName, '.')) { + $schema = $this->getConfig('database') . '.' . $tableName; + } else { + $schema = $tableName; + } + + if (!isset(self::$info[$schema])) { + // 读取缓存 + $cacheFile = Container::get('app')->getRuntimePath() . 'schema' . DIRECTORY_SEPARATOR . $schema . '.php'; + + if (!$this->config['debug'] && is_file($cacheFile)) { + $info = include $cacheFile; + } else { + $info = $this->getFields($tableName); + } + + $fields = array_keys($info); + $bind = $type = []; + + foreach ($info as $key => $val) { + // 记录字段类型 + $type[$key] = $val['type']; + $bind[$key] = $this->getFieldBindType($val['type']); + + if (!empty($val['primary'])) { + $pk[] = $key; + } + } + + if (isset($pk)) { + // 设置主键 + $pk = count($pk) > 1 ? $pk : $pk[0]; + } else { + $pk = null; + } + + self::$info[$schema] = ['fields' => $fields, 'type' => $type, 'bind' => $bind, 'pk' => $pk]; + } + + return $fetch ? self::$info[$schema][$fetch] : self::$info[$schema]; + } + + /** + * 获取数据表的主键 + * @access public + * @param string $tableName 数据表名 + * @return string|array + */ + public function getPk($tableName) + { + return $this->getTableInfo($tableName, 'pk'); + } + + /** + * 获取数据表字段信息 + * @access public + * @param string $tableName 数据表名 + * @return array + */ + public function getTableFields($tableName) + { + return $this->getTableInfo($tableName, 'fields'); + } + + /** + * 获取数据表字段类型 + * @access public + * @param string $tableName 数据表名 + * @param string $field 字段名 + * @return array|string + */ + public function getFieldsType($tableName, $field = null) + { + $result = $this->getTableInfo($tableName, 'type'); + + if ($field && isset($result[$field])) { + return $result[$field]; + } + + return $result; + } + + /** + * 获取数据表绑定信息 + * @access public + * @param string $tableName 数据表名 + * @return array + */ + public function getFieldsBind($tableName) + { + return $this->getTableInfo($tableName, 'bind'); + } + /** * 获取数据库的配置参数 * @access public - * @param string $config 配置名称 + * @param string $config 配置名称 * @return mixed */ public function getConfig($config = '') @@ -230,8 +466,8 @@ abstract class Connection /** * 设置数据库的配置参数 * @access public - * @param string|array $config 配置名称 - * @param mixed $value 配置值 + * @param string|array $config 配置名称 + * @param mixed $value 配置值 * @return void */ public function setConfig($config, $value = '') @@ -246,192 +482,998 @@ abstract class Connection /** * 连接数据库方法 * @access public - * @param array $config 连接参数 - * @param integer $linkNum 连接序号 - * @param array|bool $autoConnection 是否自动连接主数据库(用于分布式) + * @param array $config 连接参数 + * @param integer $linkNum 连接序号 + * @param array|bool $autoConnection 是否自动连接主数据库(用于分布式) * @return PDO * @throws Exception */ public function connect(array $config = [], $linkNum = 0, $autoConnection = false) { - if (!isset($this->links[$linkNum])) { - if (!$config) { - $config = $this->config; + if (isset($this->links[$linkNum])) { + return $this->links[$linkNum]; + } + + if (!$config) { + $config = $this->config; + } else { + $config = array_merge($this->config, $config); + } + + // 连接参数 + if (isset($config['params']) && is_array($config['params'])) { + $params = $config['params'] + $this->params; + } else { + $params = $this->params; + } + + // 记录当前字段属性大小写设置 + $this->attrCase = $params[PDO::ATTR_CASE]; + + if (!empty($config['break_match_str'])) { + $this->breakMatchStr = array_merge($this->breakMatchStr, (array) $config['break_match_str']); + } + + try { + if (empty($config['dsn'])) { + $config['dsn'] = $this->parseDsn($config); + } + + if ($config['debug']) { + $startTime = microtime(true); + } + + $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params); + + if ($config['debug']) { + // 记录数据库连接信息 + $this->log('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn']); + } + + return $this->links[$linkNum]; + } catch (\PDOException $e) { + if ($autoConnection) { + $this->log($e->getMessage(), 'error'); + return $this->connect($autoConnection, $linkNum); + } else { + throw $e; + } + } + } + + /** + * 释放查询结果 + * @access public + */ + public function free() + { + $this->PDOStatement = null; + } + + /** + * 获取PDO对象 + * @access public + * @return \PDO|false + */ + public function getPdo() + { + if (!$this->linkID) { + return false; + } + + return $this->linkID; + } + + /** + * 执行查询 使用生成器返回数据 + * @access public + * @param string $sql sql指令 + * @param array $bind 参数绑定 + * @param bool $master 是否在主服务器读操作 + * @param Model $model 模型对象实例 + * @param array $condition 查询条件 + * @param mixed $relation 关联查询 + * @return \Generator + */ + public function getCursor($sql, $bind = [], $master = false, $model = null, $condition = null, $relation = null) + { + $this->initConnect($master); + + // 记录SQL语句 + $this->queryStr = $sql; + + $this->bind = $bind; + + // 释放前次的查询结果 + if (!empty($this->PDOStatement)) { + $this->free(); + } + + Db::$queryTimes++; + + // 调试开始 + $this->debug(true); + + // 预处理 + if (empty($this->PDOStatement)) { + $this->PDOStatement = $this->linkID->prepare($sql); + } + + // 是否为存储过程调用 + $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']); + + // 参数绑定 + if ($procedure) { + $this->bindParam($bind); + } else { + $this->bindValue($bind); + } + + // 执行查询 + $this->PDOStatement->execute(); + + // 调试结束 + $this->debug(false, '', $master); + + // 返回结果集 + while ($result = $this->PDOStatement->fetch($this->fetchType)) { + if ($model) { + $instance = $model->newInstance($result, $condition); + + if ($relation) { + $instance->relationQuery($relation); + } + + yield $instance; } else { - $config = array_merge($this->config, $config); + yield $result; + } + } + } + + /** + * 执行查询 返回数据集 + * @access public + * @param string $sql sql指令 + * @param array $bind 参数绑定 + * @param bool $master 是否在主服务器读操作 + * @param bool $pdo 是否返回PDO对象 + * @return array + * @throws BindParamException + * @throws \PDOException + * @throws \Exception + * @throws \Throwable + */ + public function query($sql, $bind = [], $master = false, $pdo = false) + { + $this->initConnect($master); + + if (!$this->linkID) { + return false; + } + + // 记录SQL语句 + $this->queryStr = $sql; + + $this->bind = $bind; + + Db::$queryTimes++; + + try { + // 调试开始 + $this->debug(true); + + // 释放前次的查询结果 + if (!empty($this->PDOStatement)) { + $this->free(); + } + + // 预处理 + if (empty($this->PDOStatement)) { + $this->PDOStatement = $this->linkID->prepare($sql); } - // 连接参数 - if (isset($config['params']) && is_array($config['params'])) { - $params = $config['params'] + $this->params; + + // 是否为存储过程调用 + $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']); + + // 参数绑定 + if ($procedure) { + $this->bindParam($bind); } else { - $params = $this->params; + $this->bindValue($bind); + } + + // 执行查询 + $this->PDOStatement->execute(); + + // 调试结束 + $this->debug(false, '', $master); + + // 返回结果集 + return $this->getResult($pdo, $procedure); + } catch (\PDOException $e) { + if ($this->isBreak($e)) { + return $this->close()->query($sql, $bind, $master, $pdo); } - // 记录当前字段属性大小写设置 - $this->attrCase = $params[PDO::ATTR_CASE]; - // 记录数据集返回类型 - if (isset($config['resultset_type'])) { - $this->resultSetType = $config['resultset_type']; + + throw new PDOException($e, $this->config, $this->getLastsql()); + } catch (\Throwable $e) { + if ($this->isBreak($e)) { + return $this->close()->query($sql, $bind, $master, $pdo); } - try { - if (empty($config['dsn'])) { - $config['dsn'] = $this->parseDsn($config); - } - if ($config['debug']) { - $startTime = microtime(true); - } - $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params); - if ($config['debug']) { - // 记录数据库连接信息 - Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn'], 'sql'); - } - } catch (\PDOException $e) { - if ($autoConnection) { - Log::record($e->getMessage(), 'error'); - return $this->connect($autoConnection, $linkNum); - } else { - throw $e; - } + + throw $e; + } catch (\Exception $e) { + if ($this->isBreak($e)) { + return $this->close()->query($sql, $bind, $master, $pdo); } + + throw $e; + } + } + + /** + * 执行语句 + * @access public + * @param string $sql sql指令 + * @param array $bind 参数绑定 + * @param Query $query 查询对象 + * @return int + * @throws BindParamException + * @throws \PDOException + * @throws \Exception + * @throws \Throwable + */ + public function execute($sql, $bind = [], Query $query = null) + { + $this->initConnect(true); + + if (!$this->linkID) { + return false; + } + + // 记录SQL语句 + $this->queryStr = $sql; + + $this->bind = $bind; + + Db::$executeTimes++; + try { + // 调试开始 + $this->debug(true); + + //释放前次的查询结果 + if (!empty($this->PDOStatement) && $this->PDOStatement->queryString != $sql) { + $this->free(); + } + + // 预处理 + if (empty($this->PDOStatement)) { + $this->PDOStatement = $this->linkID->prepare($sql); + } + + // 是否为存储过程调用 + $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']); + + // 参数绑定 + if ($procedure) { + $this->bindParam($bind); + } else { + $this->bindValue($bind); + } + + // 执行语句 + $this->PDOStatement->execute(); + + // 调试结束 + $this->debug(false, '', true); + + if ($query && !empty($this->config['deploy']) && !empty($this->config['read_master'])) { + $query->readMaster(); + } + + $this->numRows = $this->PDOStatement->rowCount(); + + return $this->numRows; + } catch (\PDOException $e) { + if ($this->isBreak($e)) { + return $this->close()->execute($sql, $bind, $query); + } + + throw new PDOException($e, $this->config, $this->getLastsql()); + } catch (\Throwable $e) { + if ($this->isBreak($e)) { + return $this->close()->execute($sql, $bind, $query); + } + + throw $e; + } catch (\Exception $e) { + if ($this->isBreak($e)) { + return $this->close()->execute($sql, $bind, $query); + } + + throw $e; + } + } + + /** + * 查找单条记录 + * @access public + * @param Query $query 查询对象 + * @return array|null|\PDOStatement|string + * @throws DbException + * @throws ModelNotFoundException + * @throws DataNotFoundException + */ + public function find(Query $query) + { + // 分析查询表达式 + $options = $query->getOptions(); + $pk = $query->getPk($options); + + $data = $options['data']; + $query->setOption('limit', 1); + + if (empty($options['fetch_sql']) && !empty($options['cache'])) { + // 判断查询缓存 + $cache = $options['cache']; + + if (is_string($cache['key'])) { + $key = $cache['key']; + } else { + $key = $this->getCacheKey($query, $data); + } + + $result = Container::get('cache')->get($key); + + if (false !== $result) { + return $result; + } + } + + if (is_string($pk) && !is_array($data)) { + if (isset($key) && strpos($key, '|')) { + list($a, $val) = explode('|', $key); + $item[$pk] = $val; + } else { + $item[$pk] = $data; + } + $data = $item; + } + + $query->setOption('data', $data); + + // 生成查询SQL + $sql = $this->builder->select($query); + + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + // 获取实际执行的SQL语句 + return $this->getRealSql($sql, $bind); + } + + // 事件回调 + $result = $query->trigger('before_find'); + + if (!$result) { + // 执行查询 + $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']); + + if ($resultSet instanceof \PDOStatement) { + // 返回PDOStatement对象 + return $resultSet; + } + + $result = isset($resultSet[0]) ? $resultSet[0] : null; + } + + if (isset($cache) && $result) { + // 缓存数据 + $this->cacheData($key, $result, $cache); + } + + return $result; + } + + /** + * 使用游标查询记录 + * @access public + * @param Query $query 查询对象 + * @return \Generator + */ + public function cursor(Query $query) + { + // 分析查询表达式 + $options = $query->getOptions(); + + // 生成查询SQL + $sql = $this->builder->select($query); + + $bind = $query->getBind(); + + $condition = isset($options['where']['AND']) ? $options['where']['AND'] : null; + $relation = isset($options['relaltion']) ? $options['relation'] : null; + + // 执行查询操作 + return $this->getCursor($sql, $bind, $options['master'], $query->getModel(), $condition, $relation); + } + + /** + * 查找记录 + * @access public + * @param Query $query 查询对象 + * @return array|\PDOStatement|string + * @throws DbException + * @throws ModelNotFoundException + * @throws DataNotFoundException + */ + public function select(Query $query) + { + // 分析查询表达式 + $options = $query->getOptions(); + + if (empty($options['fetch_sql']) && !empty($options['cache'])) { + $resultSet = $this->getCacheData($query, $options['cache'], null, $key); + + if (false !== $resultSet) { + return $resultSet; + } + } + + // 生成查询SQL + $sql = $this->builder->select($query); + + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + // 获取实际执行的SQL语句 + return $this->getRealSql($sql, $bind); + } + + $resultSet = $query->trigger('before_select'); + + if (!$resultSet) { + // 执行查询操作 + $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']); + + if ($resultSet instanceof \PDOStatement) { + // 返回PDOStatement对象 + return $resultSet; + } + } + + if (!empty($options['cache']) && false !== $resultSet) { + // 缓存数据集 + $this->cacheData($key, $resultSet, $options['cache']); + } + + return $resultSet; + } + + /** + * 插入记录 + * @access public + * @param Query $query 查询对象 + * @param boolean $replace 是否replace + * @param boolean $getLastInsID 返回自增主键 + * @param string $sequence 自增序列名 + * @return integer|string + */ + public function insert(Query $query, $replace = false, $getLastInsID = false, $sequence = null) + { + // 分析查询表达式 + $options = $query->getOptions(); + + // 生成SQL语句 + $sql = $this->builder->insert($query, $replace); + + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + // 获取实际执行的SQL语句 + return $this->getRealSql($sql, $bind); + } + + // 执行操作 + $result = '' == $sql ? 0 : $this->execute($sql, $bind, $query); + + if ($result) { + $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null); + $lastInsId = $this->getLastInsID($sequence); + + $data = $options['data']; + + if ($lastInsId) { + $pk = $query->getPk($options); + if (is_string($pk)) { + $data[$pk] = $lastInsId; + } + } + + $query->setOption('data', $data); + + $query->trigger('after_insert'); + + if ($getLastInsID) { + return $lastInsId; + } + } + + return $result; + } + + /** + * 批量插入记录 + * @access public + * @param Query $query 查询对象 + * @param mixed $dataSet 数据集 + * @param bool $replace 是否replace + * @param integer $limit 每次写入数据限制 + * @return integer|string + * @throws \Exception + * @throws \Throwable + */ + public function insertAll(Query $query, $dataSet = [], $replace = false, $limit = null) + { + if (!is_array(reset($dataSet))) { + return false; + } + + $options = $query->getOptions(); + + if ($limit) { + // 分批写入 自动启动事务支持 + $this->startTrans(); + + try { + $array = array_chunk($dataSet, $limit, true); + $count = 0; + + foreach ($array as $item) { + $sql = $this->builder->insertAll($query, $item, $replace); + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + $fetchSql[] = $this->getRealSql($sql, $bind); + } else { + $count += $this->execute($sql, $bind, $query); + } + } + + // 提交事务 + $this->commit(); + } catch (\Exception $e) { + $this->rollback(); + throw $e; + } catch (\Throwable $e) { + $this->rollback(); + throw $e; + } + + return isset($fetchSql) ? implode(';', $fetchSql) : $count; + } + + $sql = $this->builder->insertAll($query, $dataSet, $replace); + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + return $this->getRealSql($sql, $bind); + } + + return $this->execute($sql, $bind, $query); + } + + /** + * 通过Select方式插入记录 + * @access public + * @param Query $query 查询对象 + * @param string $fields 要插入的数据表字段名 + * @param string $table 要插入的数据表名 + * @return integer|string + * @throws PDOException + */ + public function selectInsert(Query $query, $fields, $table) + { + // 分析查询表达式 + $options = $query->getOptions(); + + $table = $this->parseSqlTable($table); + + $sql = $this->builder->selectInsert($query, $fields, $table); + + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + return $this->getRealSql($sql, $bind); + } + + return $this->execute($sql, $bind, $query); + } + + /** + * 更新记录 + * @access public + * @param Query $query 查询对象 + * @return integer|string + * @throws Exception + * @throws PDOException + */ + public function update(Query $query) + { + $options = $query->getOptions(); + + if (isset($options['cache']) && is_string($options['cache']['key'])) { + $key = $options['cache']['key']; + } + + $pk = $query->getPk($options); + $data = $options['data']; + + if (empty($options['where'])) { + // 如果存在主键数据 则自动作为更新条件 + if (is_string($pk) && isset($data[$pk])) { + $where[$pk] = [$pk, '=', $data[$pk]]; + if (!isset($key)) { + $key = $this->getCacheKey($query, $data[$pk]); + } + unset($data[$pk]); + } elseif (is_array($pk)) { + // 增加复合主键支持 + foreach ($pk as $field) { + if (isset($data[$field])) { + $where[$field] = [$field, '=', $data[$field]]; + } else { + // 如果缺少复合主键数据则不执行 + throw new Exception('miss complex primary data'); + } + unset($data[$field]); + } + } + + if (!isset($where)) { + // 如果没有任何更新条件则不执行 + throw new Exception('miss update condition'); + } else { + $options['where']['AND'] = $where; + $query->setOption('where', ['AND' => $where]); + } + } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'])) { + foreach ($options['where']['AND'] as $val) { + if (is_array($val) && $val[0] == $pk) { + $key = $this->getCacheKey($query, $val); + } + } + } + + // 更新数据 + $query->setOption('data', $data); + + // 生成UPDATE SQL语句 + $sql = $this->builder->update($query); + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + // 获取实际执行的SQL语句 + return $this->getRealSql($sql, $bind); + } + + // 检测缓存 + $cache = Container::get('cache'); + + if (isset($key) && $cache->get($key)) { + // 删除缓存 + $cache->rm($key); + } elseif (!empty($options['cache']['tag'])) { + $cache->clear($options['cache']['tag']); + } + + // 执行操作 + $result = '' == $sql ? 0 : $this->execute($sql, $bind, $query); + + if ($result) { + if (is_string($pk) && isset($where[$pk])) { + $data[$pk] = $where[$pk]; + } elseif (is_string($pk) && isset($key) && strpos($key, '|')) { + list($a, $val) = explode('|', $key); + $data[$pk] = $val; + } + + $query->setOption('data', $data); + $query->trigger('after_update'); + } + + return $result; + } + + /** + * 删除记录 + * @access public + * @param Query $query 查询对象 + * @return int + * @throws Exception + * @throws PDOException + */ + public function delete(Query $query) + { + // 分析查询表达式 + $options = $query->getOptions(); + $pk = $query->getPk($options); + $data = $options['data']; + + if (isset($options['cache']) && is_string($options['cache']['key'])) { + $key = $options['cache']['key']; + } elseif (!is_null($data) && true !== $data && !is_array($data)) { + $key = $this->getCacheKey($query, $data); + } elseif (is_string($pk) && isset($options['where']['AND'])) { + foreach ($options['where']['AND'] as $val) { + if (is_array($val) && $val[0] == $pk) { + $key = $this->getCacheKey($query, $val); + } + } + } + + if (true !== $data && empty($options['where'])) { + // 如果条件为空 不进行删除操作 除非设置 1=1 + throw new Exception('delete without condition'); + } + + // 生成删除SQL语句 + $sql = $this->builder->delete($query); + + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + // 获取实际执行的SQL语句 + return $this->getRealSql($sql, $bind); + } + + // 检测缓存 + $cache = Container::get('cache'); + + if (isset($key) && $cache->get($key)) { + // 删除缓存 + $cache->rm($key); + } elseif (!empty($options['cache']['tag'])) { + $cache->clear($options['cache']['tag']); + } + + // 执行操作 + $result = $this->execute($sql, $bind, $query); + + if ($result) { + if (!is_array($data) && is_string($pk) && isset($key) && strpos($key, '|')) { + list($a, $val) = explode('|', $key); + $item[$pk] = $val; + $data = $item; + } + + $options['data'] = $data; + + $query->trigger('after_delete'); + } + + return $result; + } + + /** + * 得到某个字段的值 + * @access public + * @param Query $query 查询对象 + * @param string $field 字段名 + * @param bool $default 默认值 + * @return mixed + */ + public function value(Query $query, $field, $default = null) + { + $options = $query->getOptions(); + + if (empty($options['fetch_sql']) && !empty($options['cache'])) { + $cache = $options['cache']; + $result = $this->getCacheData($query, $cache, null, $key); + + if (false !== $result) { + return $result; + } + } + + if (isset($options['field'])) { + $query->removeOption('field'); + } + + if (is_string($field)) { + $field = array_map('trim', explode(',', $field)); + } + + $query->setOption('field', $field); + $query->setOption('limit', 1); + + // 生成查询SQL + $sql = $this->builder->select($query); + + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + // 获取实际执行的SQL语句 + return $this->getRealSql($sql, $bind); + } + + // 执行查询操作 + $pdo = $this->query($sql, $bind, $options['master'], true); + + $result = $pdo->fetchColumn(); + + if (isset($cache) && false !== $result) { + // 缓存数据 + $this->cacheData($key, $result, $cache); } - return $this->links[$linkNum]; + + return false !== $result ? $result : $default; } /** - * 释放查询结果 + * 得到某个字段的值 * @access public + * @param Query $query 查询对象 + * @param string $aggregate 聚合方法 + * @param string $field 字段名 + * @return mixed */ - public function free() + public function aggregate(Query $query, $aggregate, $field) { - $this->PDOStatement = null; + $field = $aggregate . '(' . $this->builder->parseKey($query, $field, true) . ') AS tp_' . strtolower($aggregate); + + return $this->value($query, $field, 0); } /** - * 获取PDO对象 + * 得到某个列的数组 * @access public - * @return \PDO|false + * @param Query $query 查询对象 + * @param string $field 字段名 多个字段用逗号分隔 + * @param string $key 索引 + * @return array */ - public function getPdo() + public function column(Query $query, $field, $key = '') { - if (!$this->linkID) { - return false; - } else { - return $this->linkID; + $options = $query->getOptions(); + + if (empty($options['fetch_sql']) && !empty($options['cache'])) { + // 判断查询缓存 + $cache = $options['cache']; + $result = $this->getCacheData($query, $cache, null, $guid); + + if (false !== $result) { + return $result; + } } - } - /** - * 执行查询 返回数据集 - * @access public - * @param string $sql sql指令 - * @param array $bind 参数绑定 - * @param boolean $master 是否在主服务器读操作 - * @param bool|string $class 指定返回的数据集对象 - * @return mixed - * @throws BindParamException - * @throws PDOException - */ - public function query($sql, $bind = [], $master = false, $class = false) - { - $this->initConnect($master); - if (!$this->linkID) { - return false; + if (isset($options['field'])) { + $query->removeOption('field'); } - // 根据参数绑定组装最终的SQL语句 - $this->queryStr = $this->getRealSql($sql, $bind); - //释放前次的查询结果 - if (!empty($this->PDOStatement)) { - $this->free(); + if (is_null($field)) { + $field = '*'; + } elseif ($key && '*' != $field) { + $field = $key . ',' . $field; } - Db::$queryTimes++; - try { - // 调试开始 - $this->debug(true); - // 预处理 - $this->PDOStatement = $this->linkID->prepare($sql); - // 参数绑定 - $this->bindValue($bind); - // 执行查询 - $result = $this->PDOStatement->execute(); - // 调试结束 - $this->debug(false); - $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']); - return $this->getResult($class, $procedure); - } catch (\PDOException $e) { - throw new PDOException($e, $this->config, $this->queryStr); + if (is_string($field)) { + $field = array_map('trim', explode(',', $field)); + } + + $query->setOption('field', $field); + + // 生成查询SQL + $sql = $this->builder->select($query); + + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + // 获取实际执行的SQL语句 + return $this->getRealSql($sql, $bind); + } + + // 执行查询操作 + $pdo = $this->query($sql, $bind, $options['master'], true); + + if (1 == $pdo->columnCount()) { + $result = $pdo->fetchAll(PDO::FETCH_COLUMN); + } else { + $resultSet = $pdo->fetchAll(PDO::FETCH_ASSOC); + + if ('*' == $field && $key) { + $result = array_column($resultSet, null, $key); + } elseif ($resultSet) { + $fields = array_keys($resultSet[0]); + $count = count($fields); + $key1 = array_shift($fields); + $key2 = $fields ? array_shift($fields) : ''; + $key = $key ?: $key1; + + if (strpos($key, '.')) { + list($alias, $key) = explode('.', $key); + } + + if (2 == $count) { + $column = $key2; + } elseif (1 == $count) { + $column = $key1; + } else { + $column = null; + } + + $result = array_column($resultSet, $column, $key); + } else { + $result = []; + } } + + if (isset($cache) && isset($guid)) { + // 缓存数据 + $this->cacheData($guid, $result, $cache); + } + + return $result; } /** - * 执行语句 + * 执行查询但只返回PDOStatement对象 * @access public - * @param string $sql sql指令 - * @param array $bind 参数绑定 - * @return int - * @throws BindParamException - * @throws PDOException + * @return \PDOStatement|string */ - public function execute($sql, $bind = []) + public function pdo(Query $query) { - $this->initConnect(true); - if (!$this->linkID) { - return false; - } - // 根据参数绑定组装最终的SQL语句 - $this->queryStr = $this->getRealSql($sql, $bind); + // 分析查询表达式 + $options = $query->getOptions(); - //释放前次的查询结果 - if (!empty($this->PDOStatement)) { - $this->free(); - } + // 生成查询SQL + $sql = $this->builder->select($query); - Db::$executeTimes++; - try { - // 调试开始 - $this->debug(true); - // 预处理 - $this->PDOStatement = $this->linkID->prepare($sql); - // 参数绑定操作 - $this->bindValue($bind); - // 执行语句 - $result = $this->PDOStatement->execute(); - // 调试结束 - $this->debug(false); + $bind = $query->getBind(); - $this->numRows = $this->PDOStatement->rowCount(); - return $this->numRows; - } catch (\PDOException $e) { - throw new PDOException($e, $this->config, $this->queryStr); + if (!empty($options['fetch_sql'])) { + // 获取实际执行的SQL语句 + return $this->getRealSql($sql, $bind); } + + // 执行查询操作 + return $this->query($sql, $bind, $options['master'], true); } /** * 根据参数绑定组装最终的SQL语句 便于调试 * @access public - * @param string $sql 带参数绑定的sql语句 - * @param array $bind 参数绑定列表 + * @param string $sql 带参数绑定的sql语句 + * @param array $bind 参数绑定列表 * @return string */ public function getRealSql($sql, array $bind = []) { - if ($bind) { - foreach ($bind as $key => $val) { - $value = is_array($val) ? $val[0] : $val; - $type = is_array($val) ? $val[1] : PDO::PARAM_STR; - if (PDO::PARAM_STR == $type) { - $value = $this->quote($value); - } - // 判断占位符 - $sql = is_numeric($key) ? - substr_replace($sql, $value, strpos($sql, '?'), 1) : - str_replace( - [':' . $key . ')', ':' . $key . ',', ':' . $key . ' '], - [$value . ')', $value . ',', $value . ' '], - $sql . ' '); + if (is_array($sql)) { + $sql = implode(';', $sql); + } + + foreach ($bind as $key => $val) { + $value = is_array($val) ? $val[0] : $val; + $type = is_array($val) ? $val[1] : PDO::PARAM_STR; + + if (PDO::PARAM_STR == $type) { + $value = '\'' . addslashes($value) . '\''; + } elseif (PDO::PARAM_INT == $type) { + $value = (float) $value; } + + // 判断占位符 + $sql = is_numeric($key) ? + substr_replace($sql, $value, strpos($sql, '?'), 1) : + str_replace( + [':' . $key . ')', ':' . $key . ',', ':' . $key . ' ', ':' . $key . PHP_EOL], + [$value . ')', $value . ',', $value . ' ', $value . PHP_EOL], + $sql . ' '); } - return $sql; + + return rtrim($sql); } /** @@ -439,25 +1481,62 @@ abstract class Connection * 支持 ['name'=>'value','id'=>123] 对应命名占位符 * 或者 ['value',123] 对应问号占位符 * @access public - * @param array $bind 要绑定的参数列表 + * @param array $bind 要绑定的参数列表 * @return void - * @throws \think\Exception + * @throws BindParamException */ protected function bindValue(array $bind = []) { foreach ($bind as $key => $val) { // 占位符 $param = is_numeric($key) ? $key + 1 : ':' . $key; + if (is_array($val)) { + if (PDO::PARAM_INT == $val[1] && '' === $val[0]) { + $val[0] = 0; + } $result = $this->PDOStatement->bindValue($param, $val[0], $val[1]); } else { $result = $this->PDOStatement->bindValue($param, $val); } + + if (!$result) { + throw new BindParamException( + "Error occurred when binding parameters '{$param}'", + $this->config, + $this->getLastsql(), + $bind + ); + } + } + } + + /** + * 存储过程的输入输出参数绑定 + * @access public + * @param array $bind 要绑定的参数列表 + * @return void + * @throws BindParamException + */ + protected function bindParam($bind) + { + foreach ($bind as $key => $val) { + $param = is_numeric($key) ? $key + 1 : ':' . $key; + + if (is_array($val)) { + array_unshift($val, $param); + $result = call_user_func_array([$this->PDOStatement, 'bindParam'], $val); + } else { + $result = $this->PDOStatement->bindValue($param, $val); + } + if (!$result) { + $param = array_shift($val); + throw new BindParamException( "Error occurred when binding parameters '{$param}'", $this->config, - $this->queryStr, + $this->getLastsql(), $bind ); } @@ -465,58 +1544,56 @@ abstract class Connection } /** - * 获得数据集 + * 获得数据集数组 * @access protected - * @param bool|string $class true 返回PDOStatement 字符串用于指定返回的类名 - * @param bool $procedure 是否存储过程 - * @return mixed + * @param bool $pdo 是否返回PDOStatement + * @param bool $procedure 是否存储过程 + * @return array */ - protected function getResult($class = '', $procedure = false) + protected function getResult($pdo = false, $procedure = false) { - if (true === $class) { + if ($pdo) { // 返回PDOStatement对象处理 return $this->PDOStatement; } + if ($procedure) { // 存储过程返回结果 - return $this->procedure($class); + return $this->procedure(); } - $result = $this->PDOStatement->fetchAll($this->fetchType); + + $result = $this->PDOStatement->fetchAll($this->fetchType); + $this->numRows = count($result); - if (!empty($class)) { - // 返回指定数据集对象类 - $result = new $class($result); - } elseif ('collection' == $this->resultSetType) { - // 返回数据集Collection对象 - $result = new Collection($result); - } return $result; } /** * 获得存储过程数据集 * @access protected - * @param bool|string $class true 返回PDOStatement 字符串用于指定返回的类名 * @return array */ - protected function procedure($class) + protected function procedure() { $item = []; + do { - $result = $this->getResult($class); + $result = $this->getResult(); if ($result) { $item[] = $result; } } while ($this->PDOStatement->nextRowset()); + $this->numRows = count($item); + return $item; } /** * 执行数据库事务 * @access public - * @param callable $callback 数据操作方法回调 + * @param callable $callback 数据操作方法回调 * @return mixed * @throws PDOException * @throws \Exception @@ -525,11 +1602,13 @@ abstract class Connection public function transaction($callback) { $this->startTrans(); + try { $result = null; if (is_callable($callback)) { $result = call_user_func_array($callback, [$this]); } + $this->commit(); return $result; } catch (\Exception $e) { @@ -541,10 +1620,48 @@ abstract class Connection } } + /** + * 启动XA事务 + * @access public + * @param string $xid XA事务id + * @return void + */ + public function startTransXa($xid) + {} + + /** + * 预编译XA事务 + * @access public + * @param string $xid XA事务id + * @return void + */ + public function prepareXa($xid) + {} + + /** + * 提交XA事务 + * @access public + * @param string $xid XA事务id + * @return void + */ + public function commitXa($xid) + {} + + /** + * 回滚XA事务 + * @access public + * @param string $xid XA事务id + * @return void + */ + public function rollbackXa($xid) + {} + /** * 启动事务 * @access public * @return void + * @throws \PDOException + * @throws \Exception */ public function startTrans() { @@ -555,12 +1672,24 @@ abstract class Connection ++$this->transTimes; - if (1 == $this->transTimes) { - $this->linkID->beginTransaction(); - } elseif ($this->transTimes > 1 && $this->supportSavepoint()) { - $this->linkID->exec( - $this->parseSavepoint('trans' . $this->transTimes) - ); + try { + if (1 == $this->transTimes) { + $this->linkID->beginTransaction(); + } elseif ($this->transTimes > 1 && $this->supportSavepoint()) { + $this->linkID->exec( + $this->parseSavepoint('trans' . $this->transTimes) + ); + } + } catch (\PDOException $e) { + if ($this->isBreak($e)) { + return $this->close()->startTrans(); + } + throw $e; + } catch (\Exception $e) { + if ($this->isBreak($e)) { + return $this->close()->startTrans(); + } + throw $e; } } @@ -613,7 +1742,8 @@ abstract class Connection /** * 生成定义保存点的SQL - * @param $name + * @access protected + * @param $name * @return string */ protected function parseSavepoint($name) @@ -623,7 +1753,8 @@ abstract class Connection /** * 生成回滚到保存点的SQL - * @param $name + * @access protected + * @param $name * @return string */ protected function parseSavepointRollBack($name) @@ -635,19 +1766,22 @@ abstract class Connection * 批处理执行SQL语句 * 批处理的指令都认为是execute操作 * @access public - * @param array $sqlArray SQL批处理指令 + * @param array $sqlArray SQL批处理指令 + * @param array $bind 参数绑定 * @return boolean */ - public function batchQuery($sqlArray = []) + public function batchQuery($sqlArray = [], $bind = []) { if (!is_array($sqlArray)) { return false; } + // 自动启动事务支持 $this->startTrans(); + try { foreach ($sqlArray as $sql) { - $this->execute($sql); + $this->execute($sql, $bind); } // 提交事务 $this->commit(); @@ -655,13 +1789,14 @@ abstract class Connection $this->rollback(); throw $e; } + return true; } /** * 获得查询次数 * @access public - * @param boolean $execute 是否包含所有查询 + * @param boolean $execute 是否包含所有查询 * @return integer */ public function getQueryTimes($execute = false) @@ -680,12 +1815,40 @@ abstract class Connection } /** - * 关闭数据库 + * 关闭数据库(或者重新连接) * @access public + * @return $this */ public function close() { - $this->linkID = null; + $this->linkID = null; + $this->linkWrite = null; + $this->linkRead = null; + $this->links = []; + + return $this; + } + + /** + * 是否断线 + * @access protected + * @param \PDOException|\Exception $e 异常对象 + * @return bool + */ + protected function isBreak($e) + { + if (!$this->config['break_reconnect']) { + return false; + } + + $error = $e->getMessage(); + + foreach ($this->breakMatchStr as $msg) { + if (false !== stripos($error, $msg)) { + return true; + } + } + return false; } /** @@ -695,13 +1858,13 @@ abstract class Connection */ public function getLastSql() { - return $this->queryStr; + return $this->getRealSql($this->queryStr, $this->bind); } /** * 获取最近插入的ID * @access public - * @param string $sequence 自增序列名 + * @param string $sequence 自增序列名 * @return string */ public function getLastInsID($sequence = null) @@ -732,51 +1895,44 @@ abstract class Connection } else { $error = ''; } + if ('' != $this->queryStr) { - $error .= "\n [ SQL语句 ] : " . $this->queryStr; + $error .= "\n [ SQL语句 ] : " . $this->getLastsql(); } - return $error; - } - /** - * SQL指令安全过滤 - * @access public - * @param string $str SQL字符串 - * @param bool $master 是否主库查询 - * @return string - */ - public function quote($str, $master = true) - { - $this->initConnect($master); - return $this->linkID ? $this->linkID->quote($str) : $str; + return $error; } /** * 数据库调试 记录当前SQL及分析性能 * @access protected - * @param boolean $start 调试开始标记 true 开始 false 结束 - * @param string $sql 执行的SQL语句 留空自动获取 + * @param boolean $start 调试开始标记 true 开始 false 结束 + * @param string $sql 执行的SQL语句 留空自动获取 + * @param bool $master 主从标记 * @return void */ - protected function debug($start, $sql = '') + protected function debug($start, $sql = '', $master = false) { if (!empty($this->config['debug'])) { // 开启数据库调试模式 + $debug = Container::get('debug'); + if ($start) { - Debug::remark('queryStartTime', 'time'); + $debug->remark('queryStartTime', 'time'); } else { // 记录操作结束时间 - Debug::remark('queryEndTime', 'time'); - $runtime = Debug::getRangeTime('queryStartTime', 'queryEndTime'); - $sql = $sql ?: $this->queryStr; - $log = $sql . ' [ RunTime:' . $runtime . 's ]'; + $debug->remark('queryEndTime', 'time'); + $runtime = $debug->getRangeTime('queryStartTime', 'queryEndTime'); + $sql = $sql ?: $this->getLastsql(); $result = []; + // SQL性能分析 if ($this->config['sql_explain'] && 0 === stripos(trim($sql), 'select')) { $result = $this->getExplain($sql); } + // SQL监听 - $this->trigger($sql, $runtime, $result); + $this->triggerSql($sql, $runtime, $result, $master); } } } @@ -784,7 +1940,7 @@ abstract class Connection /** * 监听SQL执行 * @access public - * @param callable $callback 回调方法 + * @param callable $callback 回调方法 * @return void */ public function listen($callback) @@ -795,47 +1951,63 @@ abstract class Connection /** * 触发SQL事件 * @access protected - * @param string $sql SQL语句 - * @param float $runtime SQL运行时间 - * @param mixed $explain SQL分析 - * @return bool + * @param string $sql SQL语句 + * @param float $runtime SQL运行时间 + * @param mixed $explain SQL分析 + * @param bool $master 主从标记 + * @return void */ - protected function trigger($sql, $runtime, $explain = []) + protected function triggerSql($sql, $runtime, $explain = [], $master = false) { if (!empty(self::$event)) { foreach (self::$event as $callback) { if (is_callable($callback)) { - call_user_func_array($callback, [$sql, $runtime, $explain]); + call_user_func_array($callback, [$sql, $runtime, $explain, $master]); } } } else { + if ($this->config['deploy']) { + // 分布式记录当前操作的主从 + $master = $master ? 'master|' : 'slave|'; + } else { + $master = ''; + } + // 未注册监听则记录到日志中 - Log::record('[ SQL ] ' . $sql . ' [ RunTime:' . $runtime . 's ]', 'sql'); + $this->log('[ SQL ] ' . $sql . ' [ ' . $master . 'RunTime:' . $runtime . 's ]'); + if (!empty($explain)) { - Log::record('[ EXPLAIN : ' . var_export($explain, true) . ' ]', 'sql'); + $this->log('[ EXPLAIN : ' . var_export($explain, true) . ' ]'); } } } + public function log($log, $type = 'sql') + { + $this->config['debug'] && Container::get('log')->record($log, $type); + } + /** * 初始化数据库连接 * @access protected - * @param boolean $master 是否主服务器 + * @param boolean $master 是否主服务器 * @return void */ protected function initConnect($master = true) { if (!empty($this->config['deploy'])) { // 采用分布式数据库 - if ($master) { + if ($master || $this->transTimes) { if (!$this->linkWrite) { $this->linkWrite = $this->multiConnect(true); } + $this->linkID = $this->linkWrite; } else { if (!$this->linkRead) { $this->linkRead = $this->multiConnect(false); } + $this->linkID = $this->linkRead; } } elseif (!$this->linkID) { @@ -847,12 +2019,13 @@ abstract class Connection /** * 连接分布式服务器 * @access protected - * @param boolean $master 主服务器 + * @param boolean $master 主服务器 * @return PDO */ protected function multiConnect($master = false) { $_config = []; + // 分布式数据库配置解析 foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) { $_config[$name] = explode(',', $this->config[$name]); @@ -878,16 +2051,20 @@ abstract class Connection $r = floor(mt_rand(0, count($_config['hostname']) - 1)); } $dbMaster = false; + if ($m != $r) { $dbMaster = []; foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) { $dbMaster[$name] = isset($_config[$name][$m]) ? $_config[$name][$m] : $_config[$name][0]; } } + $dbConfig = []; + foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) { $dbConfig[$name] = isset($_config[$name][$r]) ? $_config[$name][$r] : $_config[$name][0]; } + return $this->connect($dbConfig, $r, $r == $m ? false : $dbMaster); } @@ -898,10 +2075,72 @@ abstract class Connection public function __destruct() { // 释放查询 - if ($this->PDOStatement) { - $this->free(); - } + $this->free(); + // 关闭连接 $this->close(); } + + /** + * 缓存数据 + * @access protected + * @param string $key 缓存标识 + * @param mixed $data 缓存数据 + * @param array $config 缓存参数 + */ + protected function cacheData($key, $data, $config = []) + { + $cache = Container::get('cache'); + + if (isset($config['tag'])) { + $cache->tag($config['tag'])->set($key, $data, $config['expire']); + } else { + $cache->set($key, $data, $config['expire']); + } + } + + /** + * 获取缓存数据 + * @access protected + * @param Query $query 查询对象 + * @param mixed $cache 缓存设置 + * @param array $options 缓存 + * @return mixed + */ + protected function getCacheData(Query $query, $cache, $data, &$key = null) + { + // 判断查询缓存 + $key = is_string($cache['key']) ? $cache['key'] : $this->getCacheKey($query, $data); + + return Container::get('cache')->get($key); + } + + /** + * 生成缓存标识 + * @access protected + * @param Query $query 查询对象 + * @param mixed $value 缓存数据 + * @return string + */ + protected function getCacheKey(Query $query, $value) + { + if (is_scalar($value)) { + $data = $value; + } elseif (is_array($value) && isset($value[1], $value[2]) && in_array($value[1], ['=', 'eq'], true) && is_scalar($value[2])) { + $data = $value[2]; + } + + $prefix = 'think:' . $this->getConfig('database') . '.'; + + if (isset($data)) { + return $prefix . $query->getTable() . '|' . $data; + } + + try { + return md5($prefix . serialize($query->getOptions()) . serialize($query->getBind(false))); + } catch (\Exception $e) { + throw new Exception('closure not support cache(true)'); + } + } + } diff --git a/tests/thinkphp/library/think/config/driver/iniTest.php b/library/think/db/Expression.php similarity index 47% rename from tests/thinkphp/library/think/config/driver/iniTest.php rename to library/think/db/Expression.php index 2575157c4b643f8a201d70201d06fadf3e1c6a7c..f1b92abd7b93116c0c9b681f45c3d8e15c0b8596 100644 --- a/tests/thinkphp/library/think/config/driver/iniTest.php +++ b/library/think/db/Expression.php @@ -2,32 +2,47 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st // +---------------------------------------------------------------------- -/** - * Ini配置测试 - * @author 7IN0SAN9 - */ +namespace think\db; -namespace tests\thinkphp\library\think\config\driver; +class Expression +{ + /** + * 查询表达式 + * + * @var string + */ + protected $value; -use think\config; + /** + * 创建一个查询表达式 + * + * @param string $value + * @return void + */ + public function __construct($value) + { + $this->value = $value; + } -class iniTest extends \PHPUnit_Framework_TestCase -{ - public function testParse() + /** + * 获取表达式 + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + public function __toString() { - Config::parse('inistring=1', 'ini'); - $this->assertEquals(1, Config::get('inistring')); - Config::reset(); - Config::parse(__DIR__ . '/fixtures/config.ini'); - $this->assertTrue(Config::has('inifile')); - $this->assertEquals(1, Config::get('inifile')); - Config::reset(); + return (string) $this->value; } } diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 2e9308cc66838c81079de3621530f47aeb18cb2e..e0f9a8ac0b2a5d310d512dd879c15a56833ba9e9 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,12 +12,9 @@ namespace think\db; use PDO; -use think\Cache; use think\Collection; -use think\Config; +use think\Container; use think\Db; -use think\db\Builder; -use think\db\Connection; use think\db\exception\BindParamException; use think\db\exception\DataNotFoundException; use think\db\exception\ModelNotFoundException; @@ -27,71 +24,193 @@ use think\exception\PDOException; use think\Loader; use think\Model; use think\model\Relation; +use think\model\relation\OneToOne; use think\Paginator; class Query { - // 数据库Connection对象实例 + /** + * 当前数据库连接对象 + * @var Connection + */ protected $connection; - // 数据库驱动类型 - protected $builder; - // 当前模型类名称 + + /** + * 当前模型对象 + * @var Model + */ protected $model; - // 当前数据表名称(含前缀) - protected $table = ''; - // 当前数据表名称(不含前缀) + + /** + * 当前数据表名称(不含前缀) + * @var string + */ protected $name = ''; - // 当前数据表主键 + + /** + * 当前数据表主键 + * @var string|array + */ protected $pk; - // 当前数据表前缀 + + /** + * 当前数据表前缀 + * @var string + */ protected $prefix = ''; - // 查询参数 + + /** + * 当前查询参数 + * @var array + */ protected $options = []; - // 参数绑定 + + /** + * 当前参数绑定 + * @var array + */ protected $bind = []; - // 数据表信息 - protected static $info = []; + + /** + * 事件回调 + * @var array + */ + private static $event = []; + + /** + * 扩展查询方法 + * @var array + */ + private static $extend = []; + + /** + * 读取主库的表 + * @var array + */ + protected static $readMaster = []; + + /** + * 日期查询表达式 + * @var array + */ + protected $timeRule = [ + 'today' => ['today', 'tomorrow'], + 'yesterday' => ['yesterday', 'today'], + 'week' => ['this week 00:00:00', 'next week 00:00:00'], + 'last week' => ['last week 00:00:00', 'this week 00:00:00'], + 'month' => ['first Day of this month 00:00:00', 'first Day of next month 00:00:00'], + 'last month' => ['first Day of last month 00:00:00', 'first Day of this month 00:00:00'], + 'year' => ['this year 1/1', 'next year 1/1'], + 'last year' => ['last year 1/1', 'this year 1/1'], + ]; + + /** + * 日期查询快捷定义 + * @var array + */ + protected $timeExp = ['d' => 'today', 'w' => 'week', 'm' => 'month', 'y' => 'year']; /** * 架构函数 * @access public - * @param Connection $connection 数据库对象实例 - * @param string $model 模型名 */ - public function __construct(Connection $connection = null, $model = '') + public function __construct(Connection $connection = null) { - $this->connection = $connection ?: Db::connect([], true); - $this->builder = $this->connection->getConfig('builder') ?: $this->connection->getConfig('type'); - $this->prefix = $this->connection->getConfig('prefix'); - $this->model = $model; + if (is_null($connection)) { + $this->connection = Db::connect(); + } else { + $this->connection = $connection; + } + + $this->prefix = $this->connection->getConfig('prefix'); + } + + /** + * 创建一个新的查询对象 + * @access public + * @return Query + */ + public function newQuery() + { + return new static($this->connection); } /** * 利用__call方法实现一些特殊的Model方法 * @access public - * @param string $method 方法名称 - * @param array $args 调用参数 + * @param string $method 方法名称 + * @param array $args 调用参数 * @return mixed * @throws DbException * @throws Exception */ public function __call($method, $args) { - if (strtolower(substr($method, 0, 5)) == 'getby') { + if (isset(self::$extend[strtolower($method)])) { + // 调用扩展查询方法 + array_unshift($args, $this); + + return Container::getInstance()->invoke(self::$extend[strtolower($method)], $args); + } elseif (strtolower(substr($method, 0, 5)) == 'getby') { // 根据某个字段获取记录 - $field = Loader::parseName(substr($method, 5)); - $where[$field] = $args[0]; - return $this->where($where)->find(); + $field = Loader::parseName(substr($method, 5)); + return $this->where($field, '=', $args[0])->find(); } elseif (strtolower(substr($method, 0, 10)) == 'getfieldby') { // 根据某个字段获取记录的某个值 - $name = Loader::parseName(substr($method, 10)); - $where[$name] = $args[0]; - return $this->where($where)->value($args[1]); + $name = Loader::parseName(substr($method, 10)); + return $this->where($name, '=', $args[0])->value($args[1]); + } elseif (strtolower(substr($method, 0, 7)) == 'whereor') { + $name = Loader::parseName(substr($method, 7)); + array_unshift($args, $name); + return call_user_func_array([$this, 'whereOr'], $args); + } elseif (strtolower(substr($method, 0, 5)) == 'where') { + $name = Loader::parseName(substr($method, 5)); + array_unshift($args, $name); + return call_user_func_array([$this, 'where'], $args); + } elseif ($this->model && method_exists($this->model, 'scope' . $method)) { + // 动态调用命名范围 + $method = 'scope' . $method; + array_unshift($args, $this); + + call_user_func_array([$this->model, $method], $args); + return $this; + } else { + throw new Exception('method not exist:' . static::class . '->' . $method); + } + } + + /** + * 扩展查询方法 + * @access public + * @param string|array $method 查询方法名 + * @param callable $callback + * @return void + */ + public static function extend($method, $callback = null) + { + if (is_array($method)) { + foreach ($method as $key => $val) { + self::$extend[strtolower($key)] = $val; + } } else { - throw new Exception('method not exist:' . __CLASS__ . '->' . $method); + self::$extend[strtolower($method)] = $callback; } } + /** + * 设置当前的数据库Connection对象 + * @access public + * @param Connection $connection + * @return $this + */ + public function setConnection(Connection $connection) + { + $this->connection = $connection; + $this->prefix = $this->connection->getConfig('prefix'); + + return $this; + } + /** * 获取当前的数据库Connection对象 * @access public @@ -103,85 +222,88 @@ class Query } /** - * 切换当前的数据库连接 + * 指定模型 * @access public - * @param mixed $config + * @param Model $model 模型对象实例 * @return $this */ - public function connect($config) + public function model(Model $model) { - $this->connection = Db::connect($config); + $this->model = $model; return $this; } /** - * 指定默认的数据表名(不含前缀) + * 获取当前的模型对象 + * @access public + * @return Model|null + */ + public function getModel() + { + return $this->model ? $this->model->setQuery($this) : null; + } + + /** + * 设置从主库读取数据 * @access public - * @param string $name + * @param bool $all 是否所有表有效 * @return $this */ - public function name($name) + public function readMaster($all = false) { - $this->name = $name; + $table = $all ? '*' : $this->getTable(); + + static::$readMaster[$table] = true; + return $this; } /** - * 指定默认数据表名(含前缀) + * 指定当前数据表名(不含前缀) * @access public - * @param string $table 表名 + * @param string $name * @return $this */ - public function setTable($table) + public function name($name) { - $this->table = $table; + $this->name = $name; return $this; } /** - * 得到当前或者指定名称的数据表 + * 获取当前的数据表名称 * @access public - * @param string $name * @return string */ - public function getTable($name = '') + public function getName() { - if ($name || empty($this->table)) { - $name = $name ?: $this->name; - $tableName = $this->prefix; - if ($name) { - $tableName .= Loader::parseName($name); - } - } else { - $tableName = $this->table; - } - return $tableName; + return $this->name ?: $this->model->getName(); } /** - * 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写) + * 得到当前或者指定名称的数据表 * @access public - * @param string $sql sql语句 + * @param string $name * @return string */ - public function parseSqlTable($sql) + public function getTable($name = '') { - if (false !== strpos($sql, '__')) { - $prefix = $this->prefix; - $sql = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) { - return $prefix . strtolower($match[1]); - }, $sql); + if (empty($name) && isset($this->options['table'])) { + return $this->options['table']; } - return $sql; + + $name = $name ?: $this->name; + + return $this->prefix . Loader::parseName($name); } /** * 执行查询 返回数据集 * @access public - * @param string $sql sql指令 - * @param array $bind 参数绑定 - * @param boolean $master 是否在主服务器读操作 - * @param bool|string $class 指定返回的数据集对象 + * @param string $sql sql指令 + * @param array $bind 参数绑定 + * @param boolean $master 是否在主服务器读操作 + * @param bool|string $class 指定返回的数据集对象 * @return mixed * @throws BindParamException * @throws PDOException @@ -194,8 +316,8 @@ class Query /** * 执行语句 * @access public - * @param string $sql sql指令 - * @param array $bind 参数绑定 + * @param string $sql sql指令 + * @param array $bind 参数绑定 * @return int * @throws BindParamException * @throws PDOException @@ -205,10 +327,21 @@ class Query return $this->connection->execute($sql, $bind); } + /** + * 监听SQL执行 + * @access public + * @param callable $callback 回调方法 + * @return void + */ + public function listen($callback) + { + $this->connection->listen($callback); + } + /** * 获取最近插入的ID * @access public - * @param string $sequence 自增序列名 + * @param string $sequence 自增序列名 * @return string */ public function getLastInsID($sequence = null) @@ -216,6 +349,16 @@ class Query return $this->connection->getLastInsID($sequence); } + /** + * 获取返回或者影响的记录数 + * @access public + * @return integer + */ + public function getNumRows() + { + return $this->connection->getNumRows(); + } + /** * 获取最近一次查询的sql语句 * @access public @@ -226,10 +369,66 @@ class Query return $this->connection->getLastSql(); } + /** + * 执行数据库Xa事务 + * @access public + * @param callable $callback 数据操作方法回调 + * @param array $dbs 多个查询对象或者连接对象 + * @return mixed + * @throws PDOException + * @throws \Exception + * @throws \Throwable + */ + public function transactionXa($callback, array $dbs = []) + { + $xid = uniqid('xa'); + + if (empty($dbs)) { + $dbs[] = $this->getConnection(); + } + + foreach ($dbs as $key => $db) { + if ($db instanceof Query) { + $db = $db->getConnection(); + + $dbs[$key] = $db; + } + + $db->startTransXa($xid); + } + + try { + $result = null; + if (is_callable($callback)) { + $result = call_user_func_array($callback, [$this]); + } + + foreach ($dbs as $db) { + $db->prepareXa($xid); + } + + foreach ($dbs as $db) { + $db->commitXa($xid); + } + + return $result; + } catch (\Exception $e) { + foreach ($dbs as $db) { + $db->rollbackXa($xid); + } + throw $e; + } catch (\Throwable $e) { + foreach ($dbs as $db) { + $db->rollbackXa($xid); + } + throw $e; + } + } + /** * 执行数据库事务 * @access public - * @param callable $callback 数据操作方法回调 + * @param callable $callback 数据操作方法回调 * @return mixed */ public function transaction($callback) @@ -273,7 +472,7 @@ class Query * 批处理执行SQL语句 * 批处理的指令都认为是execute操作 * @access public - * @param array $sql SQL批处理指令 + * @param array $sql SQL批处理指令 * @return boolean */ public function batchQuery($sql = []) @@ -284,20 +483,51 @@ class Query /** * 获取数据库的配置参数 * @access public - * @param string $name 参数名称 - * @return boolean + * @param string $name 参数名称 + * @return mixed */ public function getConfig($name = '') { return $this->connection->getConfig($name); } + /** + * 获取数据表字段信息 + * @access public + * @param string $tableName 数据表名 + * @return array + */ + public function getTableFields($tableName = '') + { + if ('' == $tableName) { + $tableName = isset($this->options['table']) ? $this->options['table'] : $this->getTable(); + } + + return $this->connection->getTableFields($tableName); + } + + /** + * 获取数据表字段类型 + * @access public + * @param string $tableName 数据表名 + * @param string $field 字段名 + * @return array|string + */ + public function getFieldsType($tableName = '', $field = null) + { + if ('' == $tableName) { + $tableName = isset($this->options['table']) ? $this->options['table'] : $this->getTable(); + } + + return $this->connection->getFieldsType($tableName, $field); + } + /** * 得到分表的的数据表名 * @access public - * @param array $data 操作的数据 - * @param string $field 分表依据的字段 - * @param array $rule 分表规则 + * @param array $data 操作的数据 + * @param string $field 分表依据的字段 + * @param array $rule 分表规则 * @return string */ public function getPartitionTableName($data, $field, $rule = []) @@ -337,211 +567,147 @@ class Query } } return $this->getTable() . '_' . $seq; - } else { - // 当设置的分表字段不在查询条件或者数据中 - // 进行联合查询,必须设定 partition['num'] - $tableName = []; - for ($i = 0; $i < $rule['num']; $i++) { - $tableName[] = 'SELECT * FROM ' . $this->getTable() . '_' . ($i + 1); - } - - $tableName = '( ' . implode(" UNION ", $tableName) . ') AS ' . $this->name; - return $tableName; } - } - - /** - * 获取当前的builder实例对象 - * @access protected - * @return Builder - */ - protected function builder() - { - static $builder = []; - $driver = $this->builder; - if (!isset($builder[$driver])) { - $class = false !== strpos($driver, '\\') ? $driver : '\\think\\db\\builder\\' . ucfirst($driver); - $builder[$driver] = new $class($this->connection); + // 当设置的分表字段不在查询条件或者数据中 + // 进行联合查询,必须设定 partition['num'] + $tableName = []; + for ($i = 0; $i < $rule['num']; $i++) { + $tableName[] = 'SELECT * FROM ' . $this->getTable() . '_' . ($i + 1); } - // 设置当前查询对象 - $builder[$driver]->setQuery($this); - return $builder[$driver]; + + $tableName = '( ' . implode(" UNION ", $tableName) . ') AS ' . $this->name; + + return $tableName; } /** * 得到某个字段的值 * @access public - * @param string $field 字段名 - * @param mixed $default 默认值 + * @param string $field 字段名 + * @param mixed $default 默认值 * @return mixed */ public function value($field, $default = null) { - $result = null; - if (!empty($this->options['cache'])) { - // 判断查询缓存 - $cache = $this->options['cache']; - if (empty($this->options['table'])) { - $this->options['table'] = $this->getTable(); - } - $key = is_string($cache['key']) ? $cache['key'] : md5($field . serialize($this->options)); - $result = Cache::get($key); - } - if (!$result) { - if (isset($this->options['field'])) { - unset($this->options['field']); - } - $pdo = $this->field($field)->fetchPdo(true)->find(); - if (is_string($pdo)) { - // 返回SQL语句 - return $pdo; - } - $result = $pdo->fetchColumn(); - if (isset($cache)) { - // 缓存数据 - if (isset($cache['tag'])) { - Cache::tag($cache['tag'])->set($key, $result, $cache['expire']); - } else { - Cache::set($key, $result, $cache['expire']); - } - } - } else { - // 清空查询条件 - $this->options = []; - } - return !is_null($result) ? $result : $default; + $this->parseOptions(); + + return $this->connection->value($this, $field, $default); } /** * 得到某个列的数组 * @access public - * @param string $field 字段名 多个字段用逗号分隔 - * @param string $key 索引 + * @param string $field 字段名 多个字段用逗号分隔 + * @param string $key 索引 * @return array */ public function column($field, $key = '') { - $result = false; - if (!empty($this->options['cache'])) { - // 判断查询缓存 - $cache = $this->options['cache']; - if (empty($this->options['table'])) { - $this->options['table'] = $this->getTable(); - } - $guid = is_string($cache['key']) ? $cache['key'] : md5($field . serialize($this->options)); - $result = Cache::get($guid); - } - if (!$result) { - if (isset($this->options['field'])) { - unset($this->options['field']); - } - if ($key && '*' != $field) { - $field = $key . ',' . $field; - } - $pdo = $this->field($field)->fetchPdo(true)->select(); - if (is_string($pdo)) { - // 返回SQL语句 - return $pdo; - } - if (1 == $pdo->columnCount()) { - $result = $pdo->fetchAll(PDO::FETCH_COLUMN); - } else { - $resultSet = $pdo->fetchAll(PDO::FETCH_ASSOC); - if ($resultSet) { - $fields = array_keys($resultSet[0]); - $count = count($fields); - $key1 = array_shift($fields); - $key2 = $fields ? array_shift($fields) : ''; - $key = $key ?: $key1; - foreach ($resultSet as $val) { - if ($count > 2) { - $result[$val[$key]] = $val; - } elseif (2 == $count) { - $result[$val[$key]] = $val[$key2]; - } elseif (1 == $count) { - $result[$val[$key]] = $val[$key1]; - } - } - } else { - $result = []; - } - } - if (isset($cache) && isset($guid)) { - // 缓存数据 - if (isset($cache['tag'])) { - Cache::tag($cache['tag'])->set($guid, $result, $cache['expire']); - } else { - Cache::set($guid, $result, $cache['expire']); - } - } - } else { - // 清空查询条件 - $this->options = []; + $this->parseOptions(); + + return $this->connection->column($this, $field, $key); + } + + /** + * 聚合查询 + * @access public + * @param string $aggregate 聚合方法 + * @param string $field 字段名 + * @param bool $force 强制转为数字类型 + * @return mixed + */ + public function aggregate($aggregate, $field, $force = false) + { + $this->parseOptions(); + + $result = $this->connection->aggregate($this, $aggregate, $field); + + if (!empty($this->options['fetch_sql'])) { + return $result; + } elseif ($force) { + $result = (float) $result; } + return $result; } /** * COUNT查询 * @access public - * @param string $field 字段名 - * @return integer + * @param string $field 字段名 + * @return float|string */ public function count($field = '*') { - return (int) $this->value('COUNT(' . $field . ') AS tp_count', 0); + if (!empty($this->options['group'])) { + // 支持GROUP + $options = $this->getOptions(); + $subSql = $this->options($options)->field('count(' . $field . ') AS think_count')->bind($this->bind)->buildSql(); + + $query = $this->newQuery()->table([$subSql => '_group_count_']); + + if (!empty($options['fetch_sql'])) { + $query->fetchSql(true); + } + + return $query->aggregate('COUNT', '*', true); + } + + return $this->aggregate('COUNT', $field, true); } /** * SUM查询 * @access public - * @param string $field 字段名 - * @return float|int + * @param string $field 字段名 + * @return float */ - public function sum($field = '*') + public function sum($field) { - return $this->value('SUM(' . $field . ') AS tp_sum', 0) + 0; + return $this->aggregate('SUM', $field, true); } /** * MIN查询 * @access public - * @param string $field 字段名 - * @return float|int + * @param string $field 字段名 + * @param bool $force 强制转为数字类型 + * @return mixed */ - public function min($field = '*') + public function min($field, $force = true) { - return $this->value('MIN(' . $field . ') AS tp_min', 0) + 0; + return $this->aggregate('MIN', $field, $force); } /** * MAX查询 * @access public - * @param string $field 字段名 - * @return float|int + * @param string $field 字段名 + * @param bool $force 强制转为数字类型 + * @return mixed */ - public function max($field = '*') + public function max($field, $force = true) { - return $this->value('MAX(' . $field . ') AS tp_max', 0) + 0; + return $this->aggregate('MAX', $field, $force); } /** * AVG查询 * @access public - * @param string $field 字段名 - * @return float|int + * @param string $field 字段名 + * @return float */ - public function avg($field = '*') + public function avg($field) { - return $this->value('AVG(' . $field . ') AS tp_avg', 0) + 0; + return $this->aggregate('AVG', $field, true); } /** * 设置记录的某个字段值 * 支持使用数据库字段和方法 * @access public - * @param string|array $field 字段名 - * @param mixed $value 字段值 + * @param string|array $field 字段名 + * @param mixed $value 字段值 * @return integer */ public function setField($field, $value = '') @@ -551,106 +717,118 @@ class Query } else { $data[$field] = $value; } + return $this->update($data); } /** * 字段值(延迟)增长 * @access public - * @param string $field 字段名 - * @param integer $step 增长值 - * @param integer $lazyTime 延时时间(s) + * @param string $field 字段名 + * @param integer $step 增长值 + * @param integer $lazyTime 延时时间(s) * @return integer|true * @throws Exception */ public function setInc($field, $step = 1, $lazyTime = 0) { $condition = !empty($this->options['where']) ? $this->options['where'] : []; + if (empty($condition)) { // 没有条件不做任何更新 throw new Exception('no data to update'); } + if ($lazyTime > 0) { // 延迟写入 $guid = md5($this->getTable() . '_' . $field . '_' . serialize($condition)); $step = $this->lazyWrite('inc', $guid, $step, $lazyTime); + if (false === $step) { // 清空查询条件 $this->options = []; return true; - } else { - return $this->setField($field, $step); } } - return $this->setField($field, ['exp', $field . '+' . $step]); + + return $this->setField($field, ['INC', $step]); } /** * 字段值(延迟)减少 * @access public - * @param string $field 字段名 - * @param integer $step 减少值 - * @param integer $lazyTime 延时时间(s) + * @param string $field 字段名 + * @param integer $step 减少值 + * @param integer $lazyTime 延时时间(s) * @return integer|true * @throws Exception */ public function setDec($field, $step = 1, $lazyTime = 0) { $condition = !empty($this->options['where']) ? $this->options['where'] : []; + if (empty($condition)) { // 没有条件不做任何更新 throw new Exception('no data to update'); } + if ($lazyTime > 0) { // 延迟写入 $guid = md5($this->getTable() . '_' . $field . '_' . serialize($condition)); $step = $this->lazyWrite('dec', $guid, $step, $lazyTime); + if (false === $step) { // 清空查询条件 $this->options = []; return true; - } else { - return $this->setField($field, $step); } + + $value = ['INC', $step]; + } else { + $value = ['DEC', $step]; } - return $this->setField($field, ['exp', $field . '-' . $step]); + + return $this->setField($field, $value); } /** * 延时更新检查 返回false表示需要延时 * 否则返回实际写入的数值 * @access protected - * @param string $type 自增或者自减 - * @param string $guid 写入标识 - * @param integer $step 写入步进值 - * @param integer $lazyTime 延时时间(s) + * @param string $type 自增或者自减 + * @param string $guid 写入标识 + * @param integer $step 写入步进值 + * @param integer $lazyTime 延时时间(s) * @return false|integer */ protected function lazyWrite($type, $guid, $step, $lazyTime) { - if (!Cache::has($guid . '_time')) { + $cache = Container::get('cache'); + + if (!$cache->has($guid . '_time')) { // 计时开始 - Cache::set($guid . '_time', $_SERVER['REQUEST_TIME'], 0); - Cache::$type($guid, $step, 0); - } elseif ($_SERVER['REQUEST_TIME'] > Cache::get($guid . '_time') + $lazyTime) { + $cache->set($guid . '_time', time(), 0); + $cache->$type($guid, $step); + } elseif (time() > $cache->get($guid . '_time') + $lazyTime) { // 删除缓存 - $value = Cache::$type($guid, $step, 0); - Cache::rm($guid); - Cache::rm($guid . '_time'); + $value = $cache->$type($guid, $step); + $cache->rm($guid); + $cache->rm($guid . '_time'); return 0 === $value ? false : $value; } else { // 更新缓存 - Cache::$type($guid, $step, 0); + $cache->$type($guid, $step); } + return false; } /** * 查询SQL组装 join * @access public - * @param mixed $join 关联的表名 - * @param mixed $condition 条件 - * @param string $type JOIN类型 + * @param mixed $join 关联的表名 + * @param mixed $condition 条件 + * @param string $type JOIN类型 * @return $this */ public function join($join, $condition = null, $type = 'INNER') @@ -663,87 +841,162 @@ class Query } } } else { - $prefix = $this->prefix; - // 传入的表名为数组 - if (is_array($join)) { - if (0 !== $key = key($join)) { - // 设置了键名则键名为表名,键值作为表的别名 - $table = $key . ' ' . array_shift($join); - } else { - $table = array_shift($join); - } - if (count($join)) { - // 有设置第二个元素则把第二元素作为表前缀 - $table = (string) current($join) . $table; - } elseif (false === strpos($table, '.')) { - // 加上默认的表前缀 - $table = $prefix . $table; - } - } else { - $join = trim($join); - if (0 === strpos($join, '__')) { - $table = $this->parseSqlTable($join); - } elseif (false === strpos($join, '(') && false === strpos($join, '.') && !empty($prefix) && 0 !== strpos($join, $prefix)) { - // 传入的表名中不带有'('并且不以默认的表前缀开头时加上默认的表前缀 - $table = $prefix . $join; - } else { - $table = $join; - } - } - if (is_array($condition)) { - $condition = implode(' AND ', $condition); - } - $this->options['join'][] = strtoupper($type) . ' JOIN ' . $table . ' ON ' . $condition; + $table = $this->getJoinTable($join); + + $this->options['join'][] = [$table, strtoupper($type), $condition]; } + return $this; } /** - * 查询SQL组装 union + * LEFT JOIN * @access public - * @param mixed $union - * @param boolean $all + * @param mixed $join 关联的表名 + * @param mixed $condition 条件 * @return $this */ - public function union($union, $all = false) + public function leftJoin($join, $condition = null) { - $this->options['union']['type'] = $all ? 'UNION ALL' : 'UNION'; + return $this->join($join, $condition, 'LEFT'); + } - if (is_array($union)) { - $this->options['union'] = array_merge($this->options['union'], $union); - } else { - $this->options['union'][] = $union; - } - return $this; + /** + * RIGHT JOIN + * @access public + * @param mixed $join 关联的表名 + * @param mixed $condition 条件 + * @return $this + */ + public function rightJoin($join, $condition = null) + { + return $this->join($join, $condition, 'RIGHT'); } /** - * 指定查询字段 支持字段排除和指定数据表 + * FULL JOIN * @access public - * @param mixed $field - * @param boolean $except 是否排除 - * @param string $tableName 数据表名 - * @param string $prefix 字段前缀 - * @param string $alias 别名前缀 + * @param mixed $join 关联的表名 + * @param mixed $condition 条件 * @return $this */ - public function field($field, $except = false, $tableName = '', $prefix = '', $alias = '') + public function fullJoin($join, $condition = null) { - if (empty($field)) { - return $this; - } - if (is_string($field)) { - $field = array_map('trim', explode(',', $field)); + return $this->join($join, $condition, 'FULL'); + } + + /** + * 获取Join表名及别名 支持 + * ['prefix_table或者子查询'=>'alias'] 'table alias' + * @access protected + * @param array|string $join + * @param string $alias + * @return string + */ + protected function getJoinTable($join, &$alias = null) + { + if (is_array($join)) { + $table = $join; + $alias = array_shift($join); + } else { + $join = trim($join); + + if (false !== strpos($join, '(')) { + // 使用子查询 + $table = $join; + } else { + $prefix = $this->prefix; + if (strpos($join, ' ')) { + // 使用别名 + list($table, $alias) = explode(' ', $join); + } else { + $table = $join; + if (false === strpos($join, '.') && 0 !== strpos($join, '__')) { + $alias = $join; + } + } + + if ($prefix && false === strpos($table, '.') && 0 !== strpos($table, $prefix) && 0 !== strpos($table, '__')) { + $table = $this->getTable($table); + } + } + + if (isset($alias) && $table != $alias) { + $table = [$table => $alias]; + } + } + + return $table; + } + + /** + * 查询SQL组装 union + * @access public + * @param mixed $union + * @param boolean $all + * @return $this + */ + public function union($union, $all = false) + { + $this->options['union']['type'] = $all ? 'UNION ALL' : 'UNION'; + + if (is_array($union)) { + $this->options['union'] = array_merge($this->options['union'], $union); + } else { + $this->options['union'][] = $union; + } + + return $this; + } + + /** + * 查询SQL组装 union all + * @access public + * @param mixed $union + * @return $this + */ + public function unionAll($union) + { + return $this->union($union, true); + } + + /** + * 指定查询字段 支持字段排除和指定数据表 + * @access public + * @param mixed $field + * @param boolean $except 是否排除 + * @param string $tableName 数据表名 + * @param string $prefix 字段前缀 + * @param string $alias 别名前缀 + * @return $this + */ + public function field($field, $except = false, $tableName = '', $prefix = '', $alias = '') + { + if (empty($field)) { + return $this; + } elseif ($field instanceof Expression) { + $this->options['field'][] = $field; + return $this; + } + + if (is_string($field)) { + if (preg_match('/[\<\'\"\(]/', $field)) { + return $this->fieldRaw($field); + } + + $field = array_map('trim', explode(',', $field)); } + if (true === $field) { // 获取全部字段 - $fields = $this->getTableInfo($tableName ?: (isset($this->options['table']) ? $this->options['table'] : ''), 'fields'); + $fields = $this->getTableFields($tableName); $field = $fields ?: ['*']; } elseif ($except) { // 字段排除 - $fields = $this->getTableInfo($tableName ?: (isset($this->options['table']) ? $this->options['table'] : ''), 'fields'); + $fields = $this->getTableFields($tableName); $field = $fields ? array_diff($fields, $field) : $field; } + if ($tableName) { // 添加统一的前缀 $prefix = $prefix ?: $tableName; @@ -756,46 +1009,153 @@ class Query } if (isset($this->options['field'])) { - $field = array_merge($this->options['field'], $field); + $field = array_merge((array) $this->options['field'], $field); } + $this->options['field'] = array_unique($field); + + return $this; + } + + /** + * 表达式方式指定查询字段 + * @access public + * @param string $field 字段名 + * @param array $bind 参数绑定 + * @return $this + */ + public function fieldRaw($field, array $bind = []) + { + $this->options['field'][] = $this->raw($field); + + if ($bind) { + $this->bind($bind); + } + + return $this; + } + + /** + * 设置数据排除字段 + * @access public + * @param mixed $field 字段名或者数据 + * @return $this + */ + public function hidden($field) + { + return $this->field($field, true); + } + + /** + * 设置数据 + * @access public + * @param mixed $field 字段名或者数据 + * @param mixed $value 字段值 + * @return $this + */ + public function data($field, $value = null) + { + if (is_array($field)) { + $this->options['data'] = isset($this->options['data']) ? array_merge($this->options['data'], $field) : $field; + } else { + $this->options['data'][$field] = $value; + } + + return $this; + } + + /** + * 字段值增长 + * @access public + * @param string|array $field 字段名 + * @param integer $step 增长值 + * @return $this + */ + public function inc($field, $step = 1, $op = 'INC') + { + $fields = is_string($field) ? explode(',', $field) : $field; + + foreach ($fields as $field => $val) { + if (is_numeric($field)) { + $field = $val; + } else { + $step = $val; + } + + $this->data($field, [$op, $step]); + } + return $this; } + /** + * 字段值减少 + * @access public + * @param string|array $field 字段名 + * @param integer $step 增长值 + * @return $this + */ + public function dec($field, $step = 1) + { + return $this->inc($field, $step, 'DEC'); + } + + /** + * 使用表达式设置数据 + * @access public + * @param string $field 字段名 + * @param string $value 字段值 + * @return $this + */ + public function exp($field, $value) + { + $this->data($field, $this->raw($value)); + return $this; + } + + /** + * 使用表达式设置数据 + * @access public + * @param mixed $value 表达式 + * @return Expression + */ + public function raw($value) + { + return new Expression($value); + } + /** * 指定JOIN查询字段 * @access public - * @param string|array $table 数据表 - * @param string|array $field 查询字段 - * @param string|array $on JOIN条件 - * @param string $type JOIN类型 + * @param string|array $table 数据表 + * @param string|array $field 查询字段 + * @param mixed $on JOIN条件 + * @param string $type JOIN类型 * @return $this */ public function view($join, $field = true, $on = null, $type = 'INNER') { $this->options['view'] = true; - if (is_array($join) && is_null($field)) { + + if (is_array($join) && key($join) === 0) { foreach ($join as $key => $val) { - $this->view($key, $val[0], isset($val[1]) ? $val[1] : null, isset($val[2]) ? $val[2] : 'INNER'); + $this->view($val[0], $val[1], isset($val[2]) ? $val[2] : null, isset($val[3]) ? $val[3] : 'INNER'); } } else { $fields = []; - if (is_array($join)) { - // 支持数据表别名 - list($join, $alias, $table) = array_pad($join, 3, ''); - } else { - $alias = $join; - } - $table = !empty($table) ? $table : $this->getTable($join); + $table = $this->getJoinTable($join, $alias); + if (true === $field) { $fields = $alias . '.*'; } else { if (is_string($field)) { $field = explode(',', $field); } + foreach ($field as $key => $val) { if (is_numeric($key)) { - $fields[] = $alias . '.' . $val; + $fields[] = $alias . '.' . $val; + $this->options['map'][$val] = $alias . '.' . $val; } else { if (preg_match('/[,=\.\'\"\(\s]/', $key)) { @@ -803,145 +1163,510 @@ class Query } else { $name = $alias . '.' . $key; } - $fields[] = $name . ' AS ' . $val; + + $fields[] = $name . ' AS ' . $val; + $this->options['map'][$val] = $name; } } } + $this->field($fields); + if ($on) { - $this->join($table . ' ' . $alias, $on, $type); + $this->join($table, $on, $type); } else { - $this->table($table . ' ' . $alias); + $this->table($table); } } + return $this; } /** * 设置分表规则 * @access public - * @param array $data 操作的数据 - * @param string $field 分表依据的字段 - * @param array $rule 分表规则 + * @param array $data 操作的数据 + * @param string $field 分表依据的字段 + * @param array $rule 分表规则 * @return $this */ public function partition($data, $field, $rule = []) { $this->options['table'] = $this->getPartitionTableName($data, $field, $rule); + return $this; } /** * 指定AND查询条件 * @access public - * @param mixed $field 查询字段 - * @param mixed $op 查询表达式 - * @param mixed $condition 查询条件 + * @param mixed $field 查询字段 + * @param mixed $op 查询表达式 + * @param mixed $condition 查询条件 * @return $this */ public function where($field, $op = null, $condition = null) { $param = func_get_args(); array_shift($param); - $this->parseWhereExp('AND', $field, $op, $condition, $param); - return $this; + return $this->parseWhereExp('AND', $field, $op, $condition, $param); } /** * 指定OR查询条件 * @access public - * @param mixed $field 查询字段 - * @param mixed $op 查询表达式 - * @param mixed $condition 查询条件 + * @param mixed $field 查询字段 + * @param mixed $op 查询表达式 + * @param mixed $condition 查询条件 * @return $this */ public function whereOr($field, $op = null, $condition = null) { $param = func_get_args(); array_shift($param); - $this->parseWhereExp('OR', $field, $op, $condition, $param); - return $this; + return $this->parseWhereExp('OR', $field, $op, $condition, $param); } /** * 指定XOR查询条件 * @access public - * @param mixed $field 查询字段 - * @param mixed $op 查询表达式 - * @param mixed $condition 查询条件 + * @param mixed $field 查询字段 + * @param mixed $op 查询表达式 + * @param mixed $condition 查询条件 * @return $this */ public function whereXor($field, $op = null, $condition = null) { $param = func_get_args(); array_shift($param); - $this->parseWhereExp('XOR', $field, $op, $condition, $param); + return $this->parseWhereExp('XOR', $field, $op, $condition, $param); + } + + /** + * 指定Null查询条件 + * @access public + * @param mixed $field 查询字段 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereNull($field, $logic = 'AND') + { + return $this->parseWhereExp($logic, $field, 'NULL', null, [], true); + } + + /** + * 指定NotNull查询条件 + * @access public + * @param mixed $field 查询字段 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereNotNull($field, $logic = 'AND') + { + return $this->parseWhereExp($logic, $field, 'NOTNULL', null, [], true); + } + + /** + * 指定Exists查询条件 + * @access public + * @param mixed $condition 查询条件 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereExists($condition, $logic = 'AND') + { + if (is_string($condition)) { + $condition = $this->raw($condition); + } + + $this->options['where'][strtoupper($logic)][] = ['', 'EXISTS', $condition]; return $this; } /** - * 分析查询表达式 + * 指定NotExists查询条件 * @access public - * @param string $logic 查询逻辑 and or xor - * @param string|array|\Closure $field 查询字段 - * @param mixed $op 查询表达式 - * @param mixed $condition 查询条件 - * @param array $param 查询参数 - * @return void + * @param mixed $condition 查询条件 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereNotExists($condition, $logic = 'AND') + { + if (is_string($condition)) { + $condition = $this->raw($condition); + } + + $this->options['where'][strtoupper($logic)][] = ['', 'NOT EXISTS', $condition]; + return $this; + } + + /** + * 指定In查询条件 + * @access public + * @param mixed $field 查询字段 + * @param mixed $condition 查询条件 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereIn($field, $condition, $logic = 'AND') + { + return $this->parseWhereExp($logic, $field, 'IN', $condition, [], true); + } + + /** + * 指定NotIn查询条件 + * @access public + * @param mixed $field 查询字段 + * @param mixed $condition 查询条件 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereNotIn($field, $condition, $logic = 'AND') + { + return $this->parseWhereExp($logic, $field, 'NOT IN', $condition, [], true); + } + + /** + * 指定Like查询条件 + * @access public + * @param mixed $field 查询字段 + * @param mixed $condition 查询条件 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereLike($field, $condition, $logic = 'AND') + { + return $this->parseWhereExp($logic, $field, 'LIKE', $condition, [], true); + } + + /** + * 指定NotLike查询条件 + * @access public + * @param mixed $field 查询字段 + * @param mixed $condition 查询条件 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereNotLike($field, $condition, $logic = 'AND') + { + return $this->parseWhereExp($logic, $field, 'NOT LIKE', $condition, [], true); + } + + /** + * 指定Between查询条件 + * @access public + * @param mixed $field 查询字段 + * @param mixed $condition 查询条件 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereBetween($field, $condition, $logic = 'AND') + { + return $this->parseWhereExp($logic, $field, 'BETWEEN', $condition, [], true); + } + + /** + * 指定NotBetween查询条件 + * @access public + * @param mixed $field 查询字段 + * @param mixed $condition 查询条件 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereNotBetween($field, $condition, $logic = 'AND') + { + return $this->parseWhereExp($logic, $field, 'NOT BETWEEN', $condition, [], true); + } + + /** + * 比较两个字段 + * @access public + * @param string|array $field1 查询字段 + * @param string $operator 比较操作符 + * @param string $field2 比较字段 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereColumn($field1, $operator = null, $field2 = null, $logic = 'AND') + { + if (is_array($field1)) { + foreach ($field1 as $item) { + $this->whereColumn($item[0], $item[1], isset($item[2]) ? $item[2] : null); + } + return $this; + } + + if (is_null($field2)) { + $field2 = $operator; + $operator = '='; + } + + return $this->parseWhereExp($logic, $field1, 'COLUMN', [$operator, $field2], [], true); + } + + /** + * 设置软删除字段及条件 + * @access public + * @param false|string $field 查询字段 + * @param mixed $condition 查询条件 + * @return $this + */ + public function useSoftDelete($field, $condition = null) + { + if ($field) { + $this->options['soft_delete'] = [$field, $condition]; + } + + return $this; + } + + /** + * 指定Exp查询条件 + * @access public + * @param mixed $field 查询字段 + * @param string $condition 查询条件 + * @param array $bind 参数绑定 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereExp($field, $condition, $bind = [], $logic = 'AND') + { + $this->options['where'][$logic][] = [$field, 'EXP', $this->raw($condition)]; + + if ($bind) { + $this->bind($bind); + } + return $this; + } + + /** + * 指定表达式查询条件 + * @access public + * @param string $where 查询条件 + * @param array $bind 参数绑定 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function whereRaw($where, $bind = [], $logic = 'AND') + { + $this->options['where'][$logic][] = $this->raw($where); + + if ($bind) { + $this->bind($bind); + } + + return $this; + } + + /** + * 指定表达式查询条件 OR + * @access public + * @param string $where 查询条件 + * @param array $bind 参数绑定 + * @return $this + */ + public function whereOrRaw($where, $bind = []) + { + return $this->whereRaw($where, $bind, 'OR'); + } + + /** + * 分析查询表达式 + * @access protected + * @param string $logic 查询逻辑 and or xor + * @param mixed $field 查询字段 + * @param mixed $op 查询表达式 + * @param mixed $condition 查询条件 + * @param array $param 查询参数 + * @param bool $strict 严格模式 + * @return $this */ - protected function parseWhereExp($logic, $field, $op, $condition, $param = []) + protected function parseWhereExp($logic, $field, $op, $condition, array $param = [], $strict = false) { - if ($field instanceof \Closure) { - $this->options['where'][$logic][] = is_string($op) ? [$op, $field] : $field; - return; + if ($field instanceof $this) { + $this->options['where'] = $field->getOptions('where'); + return $this; } + $logic = strtoupper($logic); + if (is_string($field) && !empty($this->options['via']) && !strpos($field, '.')) { $field = $this->options['via'] . '.' . $field; } - if (is_string($field) && preg_match('/[,=\>\<\'\"\(\s]/', $field)) { - $where[] = ['exp', $field]; - if (is_array($op)) { - // 参数绑定 - $this->bind($op); + + if ($field instanceof Expression) { + return $this->whereRaw($field, is_array($op) ? $op : []); + } elseif ($strict) { + // 使用严格模式查询 + $where = [$field, $op, $condition]; + } elseif (is_array($field)) { + // 解析数组批量查询 + return $this->parseArrayWhereItems($field, $logic); + } elseif ($field instanceof \Closure) { + $where = $field; + } elseif (is_string($field)) { + if (preg_match('/[,=\<\'\"\(\s]/', $field)) { + return $this->whereRaw($field, $op); + } elseif (is_string($op) && strtolower($op) == 'exp') { + $bind = isset($param[2]) && is_array($param[2]) ? $param[2] : null; + return $this->whereExp($field, $condition, $bind, $logic); + } + + $where = $this->parseWhereItem($logic, $field, $op, $condition, $param); + } + + if (!empty($where)) { + $this->options['where'][$logic][] = $where; + } + + return $this; + } + + /** + * 分析查询表达式 + * @access protected + * @param string $logic 查询逻辑 and or xor + * @param mixed $field 查询字段 + * @param mixed $op 查询表达式 + * @param mixed $condition 查询条件 + * @param array $param 查询参数 + * @return mixed + */ + protected function parseWhereItem($logic, $field, $op, $condition, $param = []) + { + if (is_array($op)) { + // 同一字段多条件查询 + array_unshift($param, $field); + $where = $param; + } elseif ($field && is_null($condition)) { + if (in_array(strtoupper($op), ['NULL', 'NOTNULL', 'NOT NULL'], true)) { + // null查询 + $where = [$field, $op, '']; + } elseif (in_array($op, ['=', 'eq', 'EQ', null], true)) { + $where = [$field, 'NULL', '']; + } elseif (in_array($op, ['<>', 'neq', 'NEQ'], true)) { + $where = [$field, 'NOTNULL', '']; + } else { + // 字段相等查询 + $where = [$field, '=', $op]; } - } elseif (is_null($op) && is_null($condition)) { - if (is_array($field)) { - // 数组批量查询 - $where = $field; - } elseif ($field) { - // 字符串查询 - if (is_numeric($field)) { - $where[] = ['exp', $field]; + } elseif (in_array(strtoupper($op), ['REGEXP', 'NOT REGEXP', 'EXISTS', 'NOT EXISTS', 'NOTEXISTS'], true)) { + $where = [$field, $op, is_string($condition) ? $this->raw($condition) : $condition]; + } else { + $where = $field ? [$field, $op, $condition, isset($param[2]) ? $param[2] : null] : null; + } + + return $where; + } + + /** + * 数组批量查询 + * @access protected + * @param array $field 批量查询 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + protected function parseArrayWhereItems($field, $logic) + { + if (key($field) !== 0) { + $where = []; + foreach ($field as $key => $val) { + if ($val instanceof Expression) { + $where[] = [$key, 'exp', $val]; + } elseif (is_null($val)) { + $where[] = [$key, 'NULL', '']; } else { - $where[$field] = ['null', '']; + $where[] = [$key, is_array($val) ? 'IN' : '=', $val]; } } - } elseif (is_array($op)) { - $where[$field] = $param; - } elseif (in_array(strtolower($op), ['null', 'notnull', 'not null'])) { - // null查询 - $where[$field] = [$op, '']; - } elseif (is_null($condition)) { - // 字段相等查询 - $where[$field] = ['eq', $op]; } else { - $where[$field] = [$op, $condition]; + // 数组批量查询 + $where = $field; } + if (!empty($where)) { - if (!isset($this->options['where'][$logic])) { - $this->options['where'][$logic] = []; + $this->options['where'][$logic] = isset($this->options['where'][$logic]) ? array_merge($this->options['where'][$logic], $where) : $where; + } + + return $this; + } + + /** + * 去除某个查询条件 + * @access public + * @param string $field 查询字段 + * @param string $logic 查询逻辑 and or xor + * @return $this + */ + public function removeWhereField($field, $logic = 'AND') + { + $logic = strtoupper($logic); + + if (isset($this->options['where'][$logic])) { + foreach ($this->options['where'][$logic] as $key => $val) { + if (is_array($val) && $val[0] == $field) { + unset($this->options['where'][$logic][$key]); + } + } + } + + return $this; + } + + /** + * 去除查询参数 + * @access public + * @param string|bool $option 参数名 true 表示去除所有参数 + * @return $this + */ + public function removeOption($option = true) + { + if (true === $option) { + $this->options = []; + } elseif (is_string($option) && isset($this->options[$option])) { + unset($this->options[$option]); + } + + return $this; + } + + /** + * 条件查询 + * @access public + * @param mixed $condition 满足条件(支持闭包) + * @param \Closure|array $query 满足条件后执行的查询表达式(闭包或数组) + * @param \Closure|array $otherwise 不满足条件后执行 + * @return $this + */ + public function when($condition, $query, $otherwise = null) + { + if ($condition instanceof \Closure) { + $condition = $condition($this); + } + + if ($condition) { + if ($query instanceof \Closure) { + $query($this, $condition); + } elseif (is_array($query)) { + $this->where($query); + } + } elseif ($otherwise) { + if ($otherwise instanceof \Closure) { + $otherwise($this, $condition); + } elseif (is_array($otherwise)) { + $this->where($otherwise); } - $this->options['where'][$logic] = array_merge($this->options['where'][$logic], $where); } + + return $this; } /** * 指定查询数量 * @access public - * @param mixed $offset 起始位置 - * @param mixed $length 查询数量 + * @param mixed $offset 起始位置 + * @param mixed $length 查询数量 * @return $this */ public function limit($offset, $length = null) @@ -949,15 +1674,17 @@ class Query if (is_null($length) && strpos($offset, ',')) { list($offset, $length) = explode(',', $offset); } + $this->options['limit'] = intval($offset) . ($length ? ',' . intval($length) : ''); + return $this; } /** * 指定分页 * @access public - * @param mixed $page 页数 - * @param mixed $listRows 每页数量 + * @param mixed $page 页数 + * @param mixed $listRows 每页数量 * @return $this */ public function page($page, $listRows = null) @@ -965,23 +1692,26 @@ class Query if (is_null($listRows) && strpos($page, ',')) { list($page, $listRows) = explode(',', $page); } + $this->options['page'] = [intval($page), intval($listRows)]; + return $this; } /** * 分页查询 - * @param int|null $listRows 每页数量 - * @param int|bool $simple 简洁模式或者总记录数 - * @param array $config 配置参数 - * page:当前页, - * path:url路径, - * query:url额外参数, - * fragment:url锚点, - * var_page:分页变量, - * list_rows:每页数量 - * type:分页类名 - * @return \think\paginator\Collection + * @access public + * @param int|array $listRows 每页数量 数组表示配置参数 + * @param int|bool $simple 是否简洁模式或者总记录数 + * @param array $config 配置参数 + * page:当前页, + * path:url路径, + * query:url额外参数, + * fragment:url锚点, + * var_page:分页变量, + * list_rows:每页数量 + * type:分页类名 + * @return \think\Paginator * @throws DbException */ public function paginate($listRows = null, $simple = false, $config = []) @@ -990,8 +1720,16 @@ class Query $total = $simple; $simple = false; } - $config = array_merge(Config::get('paginate'), $config); - $listRows = $listRows ?: $config['list_rows']; + + $paginate = Container::get('config')->pull('paginate'); + + if (is_array($listRows)) { + $config = array_merge($paginate, $listRows); + $listRows = $config['list_rows']; + } else { + $config = array_merge($paginate, $config); + $listRows = $listRows ?: $config['list_rows']; + } /** @var Paginator $class */ $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\paginator\\driver\\' . ucwords($config['type']); @@ -1006,8 +1744,11 @@ class Query if (!isset($total) && !$simple) { $options = $this->getOptions(); - $total = $this->count(); + + unset($this->options['order'], $this->options['limit'], $this->options['page'], $this->options['field']); + $bind = $this->bind; + $total = $this->count(); $results = $this->options($options)->bind($bind)->page($page, $listRows)->select(); } elseif ($simple) { $results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select(); @@ -1015,88 +1756,196 @@ class Query } else { $results = $this->page($page, $listRows)->select(); } + return $class::make($results, $listRows, $page, $total, $simple, $config); } /** * 指定当前操作的数据表 * @access public - * @param string $table 表名 + * @param mixed $table 表名 * @return $this */ public function table($table) { + if (is_string($table)) { + if (strpos($table, ')')) { + // 子查询 + } elseif (strpos($table, ',')) { + $tables = explode(',', $table); + $table = []; + + foreach ($tables as $item) { + list($item, $alias) = explode(' ', trim($item)); + if ($alias) { + $this->alias([$item => $alias]); + $table[$item] = $alias; + } else { + $table[] = $item; + } + } + } elseif (strpos($table, ' ')) { + list($table, $alias) = explode(' ', $table); + + $table = [$table => $alias]; + $this->alias($table); + } + } else { + $tables = $table; + $table = []; + + foreach ($tables as $key => $val) { + if (is_numeric($key)) { + $table[] = $val; + } else { + $this->alias([$key => $val]); + $table[$key] = $val; + } + } + } + $this->options['table'] = $table; + + return $this; + } + + /** + * USING支持 用于多表删除 + * @access public + * @param mixed $using + * @return $this + */ + public function using($using) + { + $this->options['using'] = $using; + return $this; + } + + /** + * 指定排序 order('id','desc') 或者 order(['id'=>'desc','create_time'=>'desc']) + * @access public + * @param string|array $field 排序字段 + * @param string $order 排序 + * @return $this + */ + public function order($field, $order = null) + { + if (empty($field)) { + return $this; + } elseif ($field instanceof Expression) { + $this->options['order'][] = $field; + return $this; + } + + if (is_string($field)) { + if (!empty($this->options['via'])) { + $field = $this->options['via'] . '.' . $field; + } + + if (strpos($field, ',')) { + $field = array_map('trim', explode(',', $field)); + } else { + $field = empty($order) ? $field : [$field => $order]; + } + } elseif (!empty($this->options['via'])) { + foreach ($field as $key => $val) { + if (is_numeric($key)) { + $field[$key] = $this->options['via'] . '.' . $val; + } else { + $field[$this->options['via'] . '.' . $key] = $val; + unset($field[$key]); + } + } + } + + if (!isset($this->options['order'])) { + $this->options['order'] = []; + } + + if (is_array($field)) { + $this->options['order'] = array_merge($this->options['order'], $field); + } else { + $this->options['order'][] = $field; + } + + return $this; + } + + /** + * 表达式方式指定Field排序 + * @access public + * @param string $field 排序字段 + * @param array $bind 参数绑定 + * @return $this + */ + public function orderRaw($field, array $bind = []) + { + $this->options['order'][] = $this->raw($field); + + if ($bind) { + $this->bind($bind); + } + return $this; } /** - * USING支持 用于多表删除 + * 指定Field排序 order('id',[1,2,3],'desc') * @access public - * @param mixed $using + * @param string|array $field 排序字段 + * @param array $values 排序值 + * @param string $order * @return $this */ - public function using($using) + public function orderField($field, array $values, $order = '') { - $this->options['using'] = $using; + if (!empty($values)) { + $values['sort'] = $order; + + $this->options['order'][$field] = $values; + } + return $this; } /** - * 指定排序 order('id','desc') 或者 order(['id'=>'desc','create_time'=>'desc']) + * 随机排序 * @access public - * @param string|array $field 排序字段 - * @param string $order 排序 * @return $this */ - public function order($field, $order = null) + public function orderRand() { - if (!empty($field)) { - if (is_string($field)) { - if (!empty($this->options['via'])) { - $field = $this->options['via'] . '.' . $field; - } - $field = empty($order) ? $field : [$field => $order]; - } elseif (!empty($this->options['via'])) { - foreach ($field as $key => $val) { - if (is_numeric($key)) { - $field[$key] = $this->options['via'] . '.' . $val; - } else { - $field[$this->options['via'] . '.' . $key] = $val; - unset($field[$key]); - } - } - } - $this->options['order'] = $field; - } + $this->options['order'][] = '[rand]'; return $this; } /** * 查询缓存 * @access public - * @param mixed $key 缓存key - * @param integer $expire 缓存有效期 - * @param string $tag 缓存标签 + * @param mixed $key 缓存key + * @param integer|\DateTime $expire 缓存有效期 + * @param string $tag 缓存标签 * @return $this */ public function cache($key = true, $expire = null, $tag = null) { // 增加快捷调用方式 cache(10) 等同于 cache(true, 10) - if (is_numeric($key) && is_null($expire)) { + if ($key instanceof \DateTime || (is_numeric($key) && is_null($expire))) { $expire = $key; $key = true; } + if (false !== $key) { $this->options['cache'] = ['key' => $key, 'expire' => $expire, 'tag' => $tag]; } + return $this; } /** * 指定group查询 * @access public - * @param string $group GROUP + * @param string|array $group GROUP * @return $this */ public function group($group) @@ -1108,7 +1957,7 @@ class Query /** * 指定having查询 * @access public - * @param string $having having + * @param string $having having * @return $this */ public function having($having) @@ -1120,20 +1969,21 @@ class Query /** * 指定查询lock * @access public - * @param boolean $lock 是否lock + * @param bool|string $lock 是否lock * @return $this */ public function lock($lock = false) { $this->options['lock'] = $lock; $this->options['master'] = true; + return $this; } /** * 指定distinct查询 * @access public - * @param string $distinct 是否唯一 + * @param string $distinct 是否唯一 * @return $this */ public function distinct($distinct) @@ -1145,19 +1995,40 @@ class Query /** * 指定数据表别名 * @access public - * @param string $alias 数据表别名 + * @param array|string $alias 数据表别名 * @return $this */ public function alias($alias) { - $this->options['alias'] = $alias; + if (is_array($alias)) { + foreach ($alias as $key => $val) { + if (false !== strpos($key, '__')) { + $table = $this->connection->parseSqlTable($key); + } else { + $table = $key; + } + $this->options['alias'][$table] = $val; + } + } else { + if (isset($this->options['table'])) { + $table = is_array($this->options['table']) ? key($this->options['table']) : $this->options['table']; + if (false !== strpos($table, '__')) { + $table = $this->connection->parseSqlTable($table); + } + } else { + $table = $this->getTable(); + } + + $this->options['alias'][$table] = $alias; + } + return $this; } /** * 指定强制索引 * @access public - * @param string $force 索引名称 + * @param string $force 索引名称 * @return $this */ public function force($force) @@ -1169,7 +2040,7 @@ class Query /** * 查询注释 * @access public - * @param string $comment 注释 + * @param string $comment 注释 * @return $this */ public function comment($comment) @@ -1181,7 +2052,7 @@ class Query /** * 获取执行的SQL语句 * @access public - * @param boolean $fetch 是否返回sql + * @param boolean $fetch 是否返回sql * @return $this */ public function fetchSql($fetch = true) @@ -1193,24 +2064,12 @@ class Query /** * 不主动获取数据集 * @access public - * @param bool $pdo 是否返回 PDOStatement 对象 + * @param bool $pdo 是否返回 PDOStatement 对象 * @return $this */ public function fetchPdo($pdo = true) { - $this->options['fetch_class'] = $pdo; - return $this; - } - - /** - * 指定数据集返回对象 - * @access public - * @param string $class 指定返回的数据集对象类名 - * @return $this - */ - public function fetchClass($class) - { - $this->options['fetch_class'] = $class; + $this->options['fetch_pdo'] = $pdo; return $this; } @@ -1228,7 +2087,7 @@ class Query /** * 设置是否严格检查字段名 * @access public - * @param bool $strict 是否严格检查字段 + * @param bool $strict 是否严格检查字段 * @return $this */ public function strict($strict = true) @@ -1240,7 +2099,7 @@ class Query /** * 设置查询数据不存在是否抛出异常 * @access public - * @param bool $fail 数据不存在是否抛出异常 + * @param bool $fail 数据不存在是否抛出异常 * @return $this */ public function failException($fail = true) @@ -1252,7 +2111,7 @@ class Query /** * 设置自增序列名 * @access public - * @param string $sequence 自增序列名 + * @param string $sequence 自增序列名 * @return $this */ public function sequence($sequence = null) @@ -1262,188 +2121,203 @@ class Query } /** - * 指定数据表主键 + * 设置JSON字段信息 * @access public - * @param string $pk 主键 + * @param array $json JSON字段 + * @param bool $assoc 是否取出数组 * @return $this */ - public function pk($pk) + public function json(array $json = [], $assoc = false) { - $this->pk = $pk; + $this->options['json'] = $json; + $this->options['json_assoc'] = $assoc; return $this; } /** - * 查询日期或者时间 + * 设置字段类型信息 * @access public - * @param string $field 日期字段名 - * @param string $op 比较运算符或者表达式 - * @param string|array $range 比较范围 + * @param array $type 字段类型信息 * @return $this */ - public function whereTime($field, $op, $range = null) + public function setJsonFieldType(array $type) { - if (is_null($range)) { - // 使用日期表达式 - $date = getdate(); - switch (strtolower($op)) { - case 'today': - case 'd': - $range = 'today'; - break; - case 'week': - case 'w': - $range = 'this week 00:00:00'; - break; - case 'month': - case 'm': - $range = mktime(0, 0, 0, $date['mon'], 1, $date['year']); - break; - case 'year': - case 'y': - $range = mktime(0, 0, 0, 1, 1, $date['year']); - break; - case 'yesterday': - $range = ['yesterday', 'today']; - break; - case 'last week': - $range = ['last week 00:00:00', 'this week 00:00:00']; - break; - case 'last month': - $range = [date('y-m-01', strtotime('-1 month')), mktime(0, 0, 0, $date['mon'], 1, $date['year'])]; - break; - case 'last year': - $range = [mktime(0, 0, 0, 1, 1, $date['year'] - 1), mktime(0, 0, 0, 1, 1, $date['year'])]; - break; - } - $op = is_array($range) ? 'between' : '>'; - } - $this->where($field, strtolower($op) . ' time', $range); + $this->options['field_type'] = $type; return $this; } /** - * 获取数据表信息 + * 获取字段类型信息 * @access public - * @param string $tableName 数据表名 留空自动获取 - * @param string $fetch 获取信息类型 包括 fields type bind pk - * @return mixed + * @param string $field 字段名 + * @return string|null */ - public function getTableInfo($tableName = '', $fetch = '') + public function getJsonFieldType($field) { - if (!$tableName) { - $tableName = $this->getTable(); - } - if (is_array($tableName)) { - $tableName = key($tableName) ?: current($tableName); + return isset($this->options['field_type'][$field]) ? $this->options['field_type'][$field] : null; + } + + /** + * 添加查询范围 + * @access public + * @param array|string|\Closure $scope 查询范围定义 + * @param array $args 参数 + * @return $this + */ + public function scope($scope, ...$args) + { + // 查询范围的第一个参数始终是当前查询对象 + array_unshift($args, $this); + + if ($scope instanceof \Closure) { + call_user_func_array($scope, $args); + return $this; } - if (strpos($tableName, ',')) { - // 多表不获取字段信息 - return false; - } else { - $tableName = $this->parseSqlTable($tableName); + if (is_string($scope)) { + $scope = explode(',', $scope); } - list($guid) = explode(' ', $tableName); - if (!isset(self::$info[$guid])) { - if (!strpos($guid, '.')) { - $schema = $this->getConfig('database') . '.' . $guid; - } else { - $schema = $guid; - } - // 读取缓存 - if (is_file(RUNTIME_PATH . 'schema/' . $schema . '.php')) { - $info = include RUNTIME_PATH . 'schema/' . $schema . '.php'; - } else { - $info = $this->connection->getFields($guid); - } - $fields = array_keys($info); - $bind = $type = []; - foreach ($info as $key => $val) { - // 记录字段类型 - $type[$key] = $val['type']; - $bind[$key] = $this->getFieldBindType($val['type']); - if (!empty($val['primary'])) { - $pk[] = $key; + if ($this->model) { + // 检查模型类的查询范围方法 + foreach ($scope as $name) { + $method = 'scope' . trim($name); + + if (method_exists($this->model, $method)) { + call_user_func_array([$this->model, $method], $args); } } - if (isset($pk)) { - // 设置主键 - $pk = count($pk) > 1 ? $pk : $pk[0]; - } else { - $pk = null; - } - self::$info[$guid] = ['fields' => $fields, 'type' => $type, 'bind' => $bind, 'pk' => $pk]; } - return $fetch ? self::$info[$guid][$fetch] : self::$info[$guid]; + + return $this; } /** - * 获取当前数据表的主键 + * 指定数据表主键 * @access public - * @param string|array $options 数据表名或者查询参数 - * @return string|array + * @param string $pk 主键 + * @return $this */ - public function getPk($options = '') + public function pk($pk) { - if (!empty($this->pk)) { - $pk = $this->pk; - } else { - $pk = $this->getTableInfo(is_array($options) ? $options['table'] : $options, 'pk'); + $this->pk = $pk; + return $this; + } + + /** + * 查询日期或者时间 + * @access public + * @param string $name 时间表达式 + * @param string|array $rule 时间范围 + * @return $this + */ + public function timeRule($name, $rule) + { + $this->timeRule[$name] = $rule; + return $this; + } + + /** + * 查询日期或者时间 + * @access public + * @param string $field 日期字段名 + * @param string|array $op 比较运算符或者表达式 + * @param string|array $range 比较范围 + * @param string $logic AND OR + * @return $this + */ + public function whereTime($field, $op, $range = null, $logic = 'AND') + { + if (is_null($range)) { + if (is_array($op)) { + $range = $op; + } else { + if (isset($this->timeExp[strtolower($op)])) { + $op = $this->timeExp[strtolower($op)]; + } + + if (isset($this->timeRule[strtolower($op)])) { + $range = $this->timeRule[strtolower($op)]; + } else { + $range = $op; + } + } + + $op = is_array($range) ? 'between' : '>='; } - return $pk; + + return $this->parseWhereExp($logic, $field, strtolower($op) . ' time', $range, [], true); } - // 获取当前数据表字段信息 - public function getTableFields($options) + /** + * 查询当前时间在两个时间字段范围 + * @access public + * @param string $startField 开始时间字段 + * @param string $endField 结束时间字段 + * @param string $logic AND OR + * @return $this + */ + public function whereBetweenTimeField($startField, $endField) { - return $this->getTableInfo($options['table'], 'fields'); + return $this->whereTime($startField, '<=', time()) + ->whereTime($endField, '>=', time()); } - // 获取当前数据表字段类型 - public function getFieldsType($options) + /** + * 查询当前时间不在两个时间字段范围 + * @access public + * @param string $startField 开始时间字段 + * @param string $endField 结束时间字段 + * @return $this + */ + public function whereNotBetweenTimeField($startField, $endField) { - return $this->getTableInfo($options['table'], 'type'); + return $this->whereTime($startField, '>', time()) + ->whereTime($endField, '<', time(), 'OR'); } - // 获取当前数据表绑定信息 - public function getFieldsBind($options) + /** + * 查询日期或者时间范围 + * @access public + * @param string $field 日期字段名 + * @param string $startTime 开始时间 + * @param string $endTime 结束时间 + * @param string $logic AND OR + * @return $this + */ + public function whereBetweenTime($field, $startTime, $endTime = null, $logic = 'AND') { - $types = $this->getFieldsType($options); - $bind = []; - if ($types) { - foreach ($types as $key => $type) { - $bind[$key] = $this->getFieldBindType($type); - } + if (is_null($endTime)) { + $time = is_string($startTime) ? strtotime($startTime) : $startTime; + $endTime = strtotime('+1 day', $time); } - return $bind; + + return $this->parseWhereExp($logic, $field, 'between time', [$startTime, $endTime], [], true); } /** - * 获取字段绑定类型 + * 获取当前数据表的主键 * @access public - * @param string $type 字段类型 - * @return integer + * @param string|array $options 数据表名或者查询参数 + * @return string|array */ - protected function getFieldBindType($type) + public function getPk($options = '') { - if (preg_match('/(int|double|float|decimal|real|numeric|serial)/is', $type)) { - $bind = PDO::PARAM_INT; - } elseif (preg_match('/bool/is', $type)) { - $bind = PDO::PARAM_BOOL; + if (!empty($this->pk)) { + $pk = $this->pk; } else { - $bind = PDO::PARAM_STR; + $pk = $this->connection->getPk(is_array($options) && isset($options['table']) ? $options['table'] : $this->getTable()); } - return $bind; + + return $pk; } /** * 参数绑定 * @access public - * @param mixed $key 参数名 - * @param mixed $value 绑定变量值 - * @param integer $type 绑定类型 + * @param mixed $key 参数名 + * @param mixed $value 绑定变量值 + * @param integer $type 绑定类型 * @return $this */ public function bind($key, $value = false, $type = PDO::PARAM_STR) @@ -1453,13 +2327,14 @@ class Query } else { $this->bind[$key] = [$value, $type]; } + return $this; } /** * 检测参数是否已经绑定 * @access public - * @param string $key 参数名 + * @param string $key 参数名 * @return bool */ public function isBind($key) @@ -1467,10 +2342,23 @@ class Query return isset($this->bind[$key]); } + /** + * 查询参数赋值 + * @access public + * @param string $name 参数名 + * @param mixed $value 值 + * @return $this + */ + public function option($name, $value) + { + $this->options[$name] = $value; + return $this; + } + /** * 查询参数赋值 * @access protected - * @param array $options 表达式参数 + * @param array $options 表达式参数 * @return $this */ protected function options(array $options) @@ -1482,22 +2370,34 @@ class Query /** * 获取当前的查询参数 * @access public - * @param string $name 参数名 + * @param string $name 参数名 * @return mixed */ public function getOptions($name = '') { if ('' === $name) { return $this->options; - } else { - return isset($this->options[$name]) ? $this->options[$name] : null; } + return isset($this->options[$name]) ? $this->options[$name] : null; + } + + /** + * 设置当前的查询参数 + * @access public + * @param string $option 参数名 + * @param mixed $value 参数值 + * @return $this + */ + public function setOption($option, $value) + { + $this->options[$option] = $value; + return $this; } /** * 设置关联查询JOIN预查询 * @access public - * @param string|array $with 关联方法名称 + * @param string|array $with 关联方法名称 * @return $this */ public function with($with) @@ -1510,74 +2410,158 @@ class Query $with = explode(',', $with); } - $i = 0; - $currentModel = $this->model; + $first = true; /** @var Model $class */ - $class = new $currentModel; + $class = $this->model; foreach ($with as $key => $relation) { - $closure = false; + $subRelation = ''; + $closure = false; + if ($relation instanceof \Closure) { // 支持闭包查询过滤关联条件 $closure = $relation; $relation = $key; $with[$key] = $key; + } elseif (is_array($relation)) { + $subRelation = $relation; + $relation = $key; } elseif (is_string($relation) && strpos($relation, '.')) { - $with[$key] = $relation; + $with[$key] = $relation; + list($relation, $subRelation) = explode('.', $relation, 2); } /** @var Relation $model */ - $model = $class->$relation(); - $info = $model->getRelationInfo(); - if (in_array($info['type'], [Relation::HAS_ONE, Relation::BELONGS_TO])) { - if (0 == $i) { - $name = Loader::parseName(basename(str_replace('\\', '/', $currentModel))); - $table = $this->getTable(); - $alias = isset($info['alias'][$name]) ? $info['alias'][$name] : $name; - $this->table($table)->alias($alias); - if (isset($this->options['field'])) { - $field = $this->options['field']; - unset($this->options['field']); - } else { - $field = true; - } - $this->field($field, false, $table, $alias); - } - // 预载入封装 - $joinTable = $model->getTable(); - $joinName = Loader::parseName(basename(str_replace('\\', '/', $info['model']))); - $joinAlias = isset($info['alias'][$joinName]) ? $info['alias'][$joinName] : $joinName; - $this->via($joinAlias); - - if (Relation::HAS_ONE == $info['type']) { - $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['localKey'] . '=' . $joinAlias . '.' . $info['foreignKey'], $info['joinType']); - } else { - $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['foreignKey'] . '=' . $joinAlias . '.' . $info['localKey'], $info['joinType']); - } + $relation = Loader::parseName($relation, 1, false); + $model = $class->$relation(); - if ($closure) { - // 执行闭包查询 - call_user_func_array($closure, [ & $this]); - //指定获取关联的字段 - //需要在 回调中 调方法 withField 方法,如 - // $query->where(['id'=>1])->withField('id,name'); - if (!empty($this->options['with_field'])) { - $field = $this->options['with_field']; - unset($this->options['with_field']); - } - } - $this->field($field, false, $joinTable, $joinAlias, $relation . '__'); - $i++; + if ($model instanceof OneToOne && 0 == $model->getEagerlyType()) { + $model->removeOption()->eagerly($this, $relation, $subRelation, $closure, $first); + $first = false; } elseif ($closure) { $with[$key] = $closure; } } $this->via(); - $this->options['with'] = $with; + + if (isset($this->options['with'])) { + $this->options['with'] = array_merge($this->options['with'], $with); + } else { + $this->options['with'] = $with; + } + + return $this; + } + + /** + * 关联统计 + * @access protected + * @param string|array $relation 关联方法名 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @param bool $subQuery 是否使用子查询 + * @return $this + */ + protected function withAggregate($relation, $aggregate = 'count', $field = '*', $subQuery = true) + { + $relations = is_string($relation) ? explode(',', $relation) : $relation; + + if (!$subQuery) { + $this->options['with_count'][] = [$relations, $aggregate, $field]; + } else { + if (!isset($this->options['field'])) { + $this->field('*'); + } + + foreach ($relations as $key => $relation) { + $closure = false; + if ($relation instanceof \Closure) { + $closure = $relation; + $relation = $key; + } elseif (!is_int($key)) { + $aggregateField = $relation; + $relation = $key; + } + + if (!isset($aggregateField)) { + $aggregateField = Loader::parseName($relation) . '_' . $aggregate; + } + + $relation = Loader::parseName($relation, 1, false); + $count = '(' . $this->model->$relation()->getRelationCountQuery($closure, $aggregate, $field) . ')'; + + $this->field([$count => $aggregateField]); + } + } + return $this; } + /** + * 关联统计 + * @access public + * @param string|array $relation 关联方法名 + * @param bool $subQuery 是否使用子查询 + * @return $this + */ + public function withCount($relation, $subQuery = true) + { + return $this->withAggregate($relation, 'count', '*', $subQuery); + } + + /** + * 关联统计Sum + * @access public + * @param string|array $relation 关联方法名 + * @param string $field 字段 + * @param bool $subQuery 是否使用子查询 + * @return $this + */ + public function withSum($relation, $field, $subQuery = true) + { + return $this->withAggregate($relation, 'sum', $field, $subQuery); + } + + /** + * 关联统计Max + * @access public + * @param string|array $relation 关联方法名 + * @param string $field 字段 + * @param bool $subQuery 是否使用子查询 + * @return $this + */ + public function withMax($relation, $field, $subQuery = true) + { + return $this->withAggregate($relation, 'max', $field, $subQuery); + } + + /** + * 关联统计Min + * @access public + * @param string|array $relation 关联方法名 + * @param string $field 字段 + * @param bool $subQuery 是否使用子查询 + * @return $this + */ + public function withMin($relation, $field, $subQuery = true) + { + return $this->withAggregate($relation, 'min', $field, $subQuery); + } + + /** + * 关联统计Avg + * @access public + * @param string|array $relation 关联方法名 + * @param string $field 字段 + * @param bool $subQuery 是否使用子查询 + * @return $this + */ + public function withAvg($relation, $field, $subQuery = true) + { + return $this->withAggregate($relation, 'avg', $field, $subQuery); + } + /** * 关联预加载中 获取关联指定字段值 * example: @@ -1585,121 +2569,79 @@ class Query * $query->withField("id,name"); * }]) * - * @param string | array $field 指定获取的字段 + * @access public + * @param string | array $field 指定获取的字段 * @return $this */ public function withField($field) { $this->options['with_field'] = $field; + return $this; } /** * 设置当前字段添加的表别名 * @access public - * @param string $via + * @param string $via * @return $this */ public function via($via = '') { $this->options['via'] = $via; + return $this; } /** * 设置关联查询 * @access public - * @param string $relation 关联名称 + * @param string|array $relation 关联名称 * @return $this */ - public function relation($relation) - { - $this->options['relation'] = $relation; - return $this; - } - - /** - * 把主键值转换为查询条件 支持复合主键 - * @access public - * @param array|string $data 主键数据 - * @param mixed $options 表达式参数 - * @return void - * @throws Exception - */ - protected function parsePkWhere($data, &$options) - { - $pk = $this->getPk($options); - // 获取当前数据表 - if (!empty($options['alias'])) { - $alias = $options['alias']; - } - if (is_string($pk)) { - $key = isset($alias) ? $alias . '.' . $pk : $pk; - // 根据主键查询 - if (is_array($data)) { - $where[$key] = isset($data[$pk]) ? $data[$pk] : ['in', $data]; - } else { - $where[$key] = strpos($data, ',') ? ['IN', $data] : $data; - } - } elseif (is_array($pk) && is_array($data) && !empty($data)) { - // 根据复合主键查询 - foreach ($pk as $key) { - if (isset($data[$key])) { - $attr = isset($alias) ? $alias . '.' . $key : $key; - $where[$attr] = $data[$key]; - } else { - throw new Exception('miss complex primary data'); - } - } + public function relation($relation) + { + if (empty($relation)) { + return $this; } - if (!empty($where)) { - if (isset($options['where']['AND'])) { - $options['where']['AND'] = array_merge($options['where']['AND'], $where); - } else { - $options['where']['AND'] = $where; - } + if (is_string($relation)) { + $relation = explode(',', $relation); } - return; + + if (isset($this->options['relation'])) { + $this->options['relation'] = array_merge($this->options['relation'], $relation); + } else { + $this->options['relation'] = $relation; + } + + return $this; } /** * 插入记录 * @access public - * @param mixed $data 数据 - * @param boolean $replace 是否replace - * @param boolean $getLastInsID 返回自增主键 - * @param string $sequence 自增序列名 + * @param array $data 数据 + * @param boolean $replace 是否replace + * @param boolean $getLastInsID 返回自增主键 + * @param string $sequence 自增序列名 * @return integer|string */ - public function insert(array $data, $replace = false, $getLastInsID = false, $sequence = null) + public function insert(array $data = [], $replace = false, $getLastInsID = false, $sequence = null) { - // 分析查询表达式 - $options = $this->parseExpress(); - // 生成SQL语句 - $sql = $this->builder()->insert($data, $options, $replace); - // 获取参数绑定 - $bind = $this->getBind(); - if ($options['fetch_sql']) { - // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $bind); - } + $this->parseOptions(); - // 执行操作 - $result = $this->execute($sql, $bind); - if ($getLastInsID) { - $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null); - return $this->getLastInsID($sequence); - } - return $result; + $this->options['data'] = array_merge($this->options['data'], $data); + + return $this->connection->insert($this, $replace, $getLastInsID, $sequence); } /** * 插入记录并获取自增ID * @access public - * @param mixed $data 数据 - * @param boolean $replace 是否replace - * @param string $sequence 自增序列名 + * @param array $data 数据 + * @param boolean $replace 是否replace + * @param string $sequence 自增序列名 * @return integer|string */ public function insertGetId(array $data, $replace = false, $sequence = null) @@ -1710,123 +2652,133 @@ class Query /** * 批量插入记录 * @access public - * @param mixed $dataSet 数据集 + * @param array $dataSet 数据集 + * @param boolean $replace 是否replace + * @param integer $limit 每次写入数据限制 * @return integer|string */ - public function insertAll(array $dataSet) + public function insertAll(array $dataSet = [], $replace = false, $limit = null) { - // 分析查询表达式 - $options = $this->parseExpress(); - if (!is_array(reset($dataSet))) { - return false; + $this->parseOptions(); + + if (empty($dataSet)) { + $dataSet = $this->options['data']; } - // 生成SQL语句 - $sql = $this->builder()->insertAll($dataSet, $options); - // 获取参数绑定 - $bind = $this->getBind(); - if ($options['fetch_sql']) { - // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $bind); - } else { - // 执行操作 - return $this->execute($sql, $bind); + + if (empty($limit) && !empty($this->options['limit'])) { + $limit = $this->options['limit']; } + + return $this->connection->insertAll($this, $dataSet, $replace, $limit); } /** * 通过Select方式插入记录 * @access public - * @param string $fields 要插入的数据表字段名 - * @param string $table 要插入的数据表名 + * @param string $fields 要插入的数据表字段名 + * @param string $table 要插入的数据表名 * @return integer|string * @throws PDOException */ public function selectInsert($fields, $table) { - // 分析查询表达式 - $options = $this->parseExpress(); - // 生成SQL语句 - $table = $this->parseSqlTable($table); - $sql = $this->builder()->selectInsert($fields, $table, $options); - // 获取参数绑定 - $bind = $this->getBind(); - if ($options['fetch_sql']) { - // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $bind); - } else { - // 执行操作 - return $this->execute($sql, $bind); - } + $this->parseOptions(); + + return $this->connection->selectInsert($this, $fields, $table); } /** * 更新记录 * @access public - * @param mixed $data 数据 + * @param mixed $data 数据 * @return integer|string * @throws Exception * @throws PDOException */ - public function update(array $data) + public function update(array $data = []) + { + $this->parseOptions(); + + $this->options['data'] = array_merge($this->options['data'], $data); + + return $this->connection->update($this); + } + + /** + * 删除记录 + * @access public + * @param mixed $data 表达式 true 表示强制删除 + * @return int + * @throws Exception + * @throws PDOException + */ + public function delete($data = null) { - $options = $this->parseExpress(); - $pk = $this->getPk($options); - if (isset($options['cache']) && is_string($options['cache'])) { - $key = $options['cache']; + $this->parseOptions(); + + if (!is_null($data) && true !== $data) { + // AR模式分析主键条件 + $this->parsePkWhere($data); } - if (empty($options['where'])) { - // 如果存在主键数据 则自动作为更新条件 - if (is_string($pk) && isset($data[$pk])) { - $where[$pk] = $data[$pk]; - if (!isset($key)) { - $key = 'think:' . $options['table'] . '|' . $data[$pk]; - } - unset($data[$pk]); - } elseif (is_array($pk)) { - // 增加复合主键支持 - foreach ($pk as $field) { - if (isset($data[$field])) { - $where[$field] = $data[$field]; - } else { - // 如果缺少复合主键数据则不执行 - throw new Exception('miss complex primary data'); - } - unset($data[$field]); - } - } - if (!isset($where)) { - // 如果没有任何更新条件则不执行 - throw new Exception('miss update condition'); - } else { - $options['where']['AND'] = $where; - } - } elseif (is_string($pk) && isset($options['where']['AND'][$pk]) && is_scalar($options['where']['AND'][$pk])) { - $key = 'think:' . $options['table'] . '|' . $options['where']['AND'][$pk]; - } - // 生成UPDATE SQL语句 - $sql = $this->builder()->update($data, $options); - // 获取参数绑定 - $bind = $this->getBind(); - if ($options['fetch_sql']) { - // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $bind); - } else { - // 检测缓存 - if (isset($key) && Cache::get($key)) { - // 删除缓存 - Cache::rm($key); - } - // 执行操作 - return '' == $sql ? 0 : $this->execute($sql, $bind); + if (!empty($this->options['soft_delete'])) { + // 软删除 + list($field, $condition) = $this->options['soft_delete']; + unset($this->options['soft_delete']); + $this->options['data'] = [$field => $condition]; + + return $this->connection->update($this); + } + + $this->options['data'] = $data; + + return $this->connection->delete($this); + } + + /** + * 执行查询但只返回PDOStatement对象 + * @access public + * @return \PDOStatement|string + */ + public function getPdo() + { + $this->parseOptions(); + + return $this->connection->pdo($this); + } + + /** + * 使用游标查找记录 + * @access public + * @param array|string|Query|\Closure $data + * @return \Generator + */ + public function cursor($data = null) + { + if ($data instanceof \Closure) { + $data($this); + $data = null; + } + + $this->parseOptions(); + + if (!is_null($data)) { + // 主键条件分析 + $this->parsePkWhere($data); } + + $this->options['data'] = $data; + + $connection = clone $this->connection; + + return $connection->cursor($this); } /** * 查找记录 * @access public - * @param array|string|Query|\Closure $data - * @return Collection|false|\PDOStatement|string + * @param array|string|Query|\Closure $data + * @return Collection|array|\PDOStatement|string * @throws DbException * @throws ModelNotFoundException * @throws DataNotFoundException @@ -1836,87 +2788,73 @@ class Query if ($data instanceof Query) { return $data->select(); } elseif ($data instanceof \Closure) { - call_user_func_array($data, [ & $this]); + $data($this); $data = null; } - // 分析查询表达式 - $options = $this->parseExpress(); + + $this->parseOptions(); if (false === $data) { // 用于子查询 不查询只返回SQL - $options['fetch_sql'] = true; + $this->options['fetch_sql'] = true; } elseif (!is_null($data)) { // 主键条件分析 - $this->parsePkWhere($data, $options); - } - - $resultSet = false; - if (empty($options['fetch_sql']) && !empty($options['cache'])) { - // 判断查询缓存 - $cache = $options['cache']; - unset($options['cache']); - $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options)); - $resultSet = Cache::get($key); - } - if (!$resultSet) { - // 生成查询SQL - $sql = $this->builder()->select($options); - // 获取参数绑定 - $bind = $this->getBind(); - if ($options['fetch_sql']) { - // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $bind); - } - // 执行查询操作 - $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_class']); + $this->parsePkWhere($data); + } - if ($resultSet instanceof \PDOStatement) { - // 返回PDOStatement对象 - return $resultSet; - } + $this->options['data'] = $data; - if (isset($cache)) { - // 缓存数据集 - if (isset($cache['tag'])) { - Cache::tag($cache['tag'])->set($key, $resultSet, $cache['expire']); - } else { - Cache::set($key, $resultSet, $cache['expire']); - } - } + $resultSet = $this->connection->select($this); + + if ($this->options['fetch_sql']) { + return $resultSet; } - // 返回结果处理 - if (count($resultSet) > 0) { - // 数据列表读取后的处理 - if (!empty($this->model)) { - // 生成模型对象 - $model = $this->model; - foreach ($resultSet as $key => $result) { - /** @var Model $result */ - $result = new $model($result); - $result->isUpdate(true); - // 关联查询 - if (!empty($options['relation'])) { - $result->relationQuery($options['relation']); - } - $resultSet[$key] = $result; + // 数据列表读取后的处理 + if (!empty($this->model)) { + // 生成模型对象 + if (count($resultSet) > 0) { + foreach ($resultSet as $key => &$result) { + // 数据转换为模型对象 + $this->resultToModel($result, $this->options, true); } - if (!empty($options['with']) && $result instanceof Model) { + + if (!empty($this->options['with'])) { // 预载入 - $resultSet = $result->eagerlyResultSet($resultSet, $options['with'], is_object($resultSet) ? get_class($resultSet) : ''); + $result->eagerlyResultSet($resultSet, $this->options['with']); + } + + // 模型数据集转换 + $resultSet = $result->toCollection($resultSet); + } else { + $resultSet = $this->model->toCollection($resultSet); + } + } else { + if (!empty($this->options['json'])) { + foreach ($resultSet as &$result) { + $this->jsonResult($result, $this->options['json'], true); } } - } elseif (!empty($options['fail'])) { - $this->throwNotFound($options); + + if ('collection' == $this->connection->getConfig('resultset_type')) { + // 返回Collection对象 + $resultSet = new Collection($resultSet); + } + } + + // 返回结果处理 + if (!empty($this->options['fail']) && count($resultSet) == 0) { + $this->throwNotFound($this->options); } + return $resultSet; } /** * 查找单条记录 * @access public - * @param array|string|Query|\Closure $data - * @return array|false|\PDOStatement|string|Model + * @param array|string|Query|\Closure $data + * @return array|null|\PDOStatement|string|Model * @throws DbException * @throws ModelNotFoundException * @throws DataNotFoundException @@ -1926,101 +2864,113 @@ class Query if ($data instanceof Query) { return $data->find(); } elseif ($data instanceof \Closure) { - call_user_func_array($data, [ & $this]); + $data($this); $data = null; } - // 分析查询表达式 - $options = $this->parseExpress(); + + $this->parseOptions(); if (!is_null($data)) { // AR模式分析主键条件 - $this->parsePkWhere($data, $options); + $this->parsePkWhere($data); } - $options['limit'] = 1; - $result = false; - if (empty($options['fetch_sql']) && !empty($options['cache'])) { - // 判断查询缓存 - $cache = $options['cache']; - if (true === $cache['key'] && !is_null($data) && !is_array($data)) { - $key = 'think:' . $options['table'] . '|' . $data; - } else { - $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options)); - } - $result = Cache::get($key); - } - if (!$result) { - // 生成查询SQL - $sql = $this->builder()->select($options); - // 获取参数绑定 - $bind = $this->getBind(); - if ($options['fetch_sql']) { - // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $bind); - } - // 执行查询 - $result = $this->query($sql, $bind, $options['master'], $options['fetch_class']); + $this->options['data'] = $data; - if ($result instanceof \PDOStatement) { - // 返回PDOStatement对象 - return $result; - } + $result = $this->connection->find($this); - if (isset($cache)) { - // 缓存数据 - if (isset($cache['tag'])) { - Cache::tag($cache['tag'])->set($key, $result, $cache['expire']); - } else { - Cache::set($key, $result, $cache['expire']); - } - } + if ($this->options['fetch_sql']) { + return $result; } // 数据处理 - if (!empty($result[0])) { - $data = $result[0]; + if (!empty($result)) { if (!empty($this->model)) { // 返回模型对象 - $model = $this->model; - $data = new $model($data); - $data->isUpdate(true, isset($options['where']['AND']) ? $options['where']['AND'] : null); - // 关联查询 - if (!empty($options['relation'])) { - $data->relationQuery($options['relation']); - } - if (!empty($options['with'])) { - // 预载入 - $data->eagerlyResult($data, $options['with'], is_object($result) ? get_class($result) : ''); - } + $this->resultToModel($result, $this->options); + } elseif (!empty($this->options['json'])) { + $this->jsonResult($result, $this->options['json'], true); + } + } elseif (!empty($this->options['fail'])) { + $this->throwNotFound($this->options); + } + + return $result; + } + + /** + * JSON字段数据转换 + * @access protected + * @param array $result 查询数据 + * @param array $json JSON字段 + * @param bool $assoc 是否转换为数组 + * @return void + */ + protected function jsonResult(&$result, $json = [], $assoc = false) + { + foreach ($json as $name) { + if (isset($result[$name])) { + $result[$name] = json_decode($result[$name], $assoc); + } + } + } + + /** + * 查询数据转换为模型对象 + * @access protected + * @param array $result 查询数据 + * @param array $options 查询参数 + * @param bool $resultSet 是否为数据集查询 + * @return void + */ + protected function resultToModel(&$result, $options = [], $resultSet = false) + { + if (!empty($options['json'])) { + $this->jsonResult($result, $options['json'], $options['json_assoc']); + } + + $condition = (!$resultSet && isset($options['where']['AND'])) ? $options['where']['AND'] : null; + $result = $this->model->newInstance($result, $condition); + + // 关联查询 + if (!empty($options['relation'])) { + $result->relationQuery($options['relation']); + } + + // 预载入查询 + if (!$resultSet && !empty($options['with'])) { + $result->eagerlyResult($result, $options['with']); + } + + // 关联统计 + if (!empty($options['with_count'])) { + foreach ($options['with_count'] as $val) { + $result->relationCount($result, $val[0], $val[1], $val[2]); } - } elseif (!empty($options['fail'])) { - $this->throwNotFound($options); - } else { - $data = null; } - return $data; } /** * 查询失败 抛出异常 - * @access public - * @param array $options 查询参数 + * @access protected + * @param array $options 查询参数 * @throws ModelNotFoundException * @throws DataNotFoundException */ protected function throwNotFound($options = []) { if (!empty($this->model)) { - throw new ModelNotFoundException('model data Not Found:' . $this->model, $this->model, $options); - } else { - throw new DataNotFoundException('table data not Found:' . $options['table'], $options['table'], $options); + $class = get_class($this->model); + throw new ModelNotFoundException('model data Not Found:' . $class, $class, $options); } + $table = is_array($options['table']) ? key($options['table']) : $options['table']; + throw new DataNotFoundException('table data not Found:' . $table, $table, $options); } /** * 查找多条记录 如果不存在则抛出异常 * @access public - * @param array|string|Query|\Closure $data + * @param array|string|Query|\Closure $data * @return array|\PDOStatement|string|Model * @throws DbException * @throws ModelNotFoundException @@ -2034,7 +2984,7 @@ class Query /** * 查找单条记录 如果不存在则抛出异常 * @access public - * @param array|string|Query|\Closure $data + * @param array|string|Query|\Closure $data * @return array|\PDOStatement|string|Model * @throws DbException * @throws ModelNotFoundException @@ -2048,50 +2998,89 @@ class Query /** * 分批数据返回处理 * @access public - * @param integer $count 每次处理的数据数量 - * @param callable $callback 处理回调方法 - * @param string $column 分批处理的字段名 + * @param integer $count 每次处理的数据数量 + * @param callable $callback 处理回调方法 + * @param string|array $column 分批处理的字段名 + * @param string $order 字段排序 * @return boolean + * @throws DbException */ - public function chunk($count, $callback, $column = null) + public function chunk($count, $callback, $column = null, $order = 'asc') { - $options = $this->getOptions(); - $column = $column ?: $this->getPk(isset($options['table']) ? $options['table'] : ''); - $bind = $this->bind; - $resultSet = $this->limit($count)->order($column, 'asc')->select(); + $options = $this->getOptions(); + $column = $column ?: $this->getPk($options); + + if (isset($options['order'])) { + if (Container::get('app')->isDebug()) { + throw new DbException('chunk not support call order'); + } + unset($options['order']); + } + + $bind = $this->bind; + + if (is_array($column)) { + $times = 1; + $query = $this->options($options)->page($times, $count); + } else { + $query = $this->options($options)->limit($count); + + if (strpos($column, '.')) { + list($alias, $key) = explode('.', $column); + } else { + $key = $column; + } + } + + $resultSet = $query->order($column, $order)->select(); + + while (count($resultSet) > 0) { + if ($resultSet instanceof Collection) { + $resultSet = $resultSet->all(); + } - while (!empty($resultSet)) { if (false === call_user_func($callback, $resultSet)) { return false; } - $end = end($resultSet); - $lastId = is_array($end) ? $end[$column] : $end->$column; - $resultSet = $this->options($options) - ->limit($count) - ->bind($bind) - ->where($column, '>', $lastId) - ->order($column, 'asc') - ->select(); + + if (isset($times)) { + $times++; + $query = $this->options($options)->page($times, $count); + } else { + $end = end($resultSet); + $lastId = is_array($end) ? $end[$key] : $end->getData($key); + + $query = $this->options($options) + ->limit($count) + ->where($column, 'asc' == strtolower($order) ? '>' : '<', $lastId); + } + + $resultSet = $query->bind($bind)->order($column, $order)->select(); } + return true; } /** * 获取绑定的参数 并清空 * @access public + * @param bool $clear * @return array */ - public function getBind() + public function getBind($clear = true) { - $bind = $this->bind; - $this->bind = []; + $bind = $this->bind; + if ($clear) { + $this->bind = []; + } + return $bind; } /** * 创建子查询SQL * @access public - * @param bool $sub + * @param bool $sub * @return string * @throws DbException */ @@ -2101,50 +3090,97 @@ class Query } /** - * 删除记录 - * @access public - * @param mixed $data 表达式 true 表示强制删除 - * @return int - * @throws Exception - * @throws PDOException + * 视图查询处理 + * @access protected + * @param array $options 查询参数 + * @return void */ - public function delete($data = null) + protected function parseView(&$options) { - // 分析查询表达式 - $options = $this->parseExpress(); - if (isset($options['cache']) && is_string($options['cache'])) { - $key = $options['cache']; + foreach (['AND', 'OR'] as $logic) { + if (isset($options['where'][$logic])) { + foreach ($options['where'][$logic] as $key => $val) { + if (array_key_exists($key, $options['map'])) { + array_shift($val); + array_unshift($val, $options['map'][$key]); + $options['where'][$logic][$options['map'][$key]] = $val; + unset($options['where'][$logic][$key]); + } + } + } } - if (!is_null($data) && true !== $data) { - if (!isset($key) && !is_array($data)) { - // 缓存标识 - $key = 'think:' . $options['table'] . '|' . $data; + if (isset($options['order'])) { + // 视图查询排序处理 + if (is_string($options['order'])) { + $options['order'] = explode(',', $options['order']); + } + foreach ($options['order'] as $key => $val) { + if (is_numeric($key)) { + if (strpos($val, ' ')) { + list($field, $sort) = explode(' ', $val); + if (array_key_exists($field, $options['map'])) { + $options['order'][$options['map'][$field]] = $sort; + unset($options['order'][$key]); + } + } elseif (array_key_exists($val, $options['map'])) { + $options['order'][$options['map'][$val]] = 'asc'; + unset($options['order'][$key]); + } + } elseif (array_key_exists($key, $options['map'])) { + $options['order'][$options['map'][$key]] = $val; + unset($options['order'][$key]); + } } - // AR模式分析主键条件 - $this->parsePkWhere($data, $options); } + } + + /** + * 把主键值转换为查询条件 支持复合主键 + * @access public + * @param array|string $data 主键数据 + * @return void + * @throws Exception + */ + public function parsePkWhere($data) + { + $pk = $this->getPk($this->options); + // 获取当前数据表 + $table = is_array($this->options['table']) ? key($this->options['table']) : $this->options['table']; - if (true !== $data && empty($options['where'])) { - // 如果条件为空 不进行删除操作 除非设置 1=1 - throw new Exception('delete without condition'); + if (!empty($this->options['alias'][$table])) { + $alias = $this->options['alias'][$table]; } - // 生成删除SQL语句 - $sql = $this->builder()->delete($options); - // 获取参数绑定 - $bind = $this->getBind(); - if ($options['fetch_sql']) { - // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $bind); + + if (is_string($pk)) { + $key = isset($alias) ? $alias . '.' . $pk : $pk; + // 根据主键查询 + if (is_array($data)) { + $where[$pk] = isset($data[$pk]) ? [$key, '=', $data[$pk]] : [$key, 'in', $data]; + } else { + $where[$pk] = strpos($data, ',') ? [$key, 'IN', $data] : [$key, '=', $data]; + } + } elseif (is_array($pk) && is_array($data) && !empty($data)) { + // 根据复合主键查询 + foreach ($pk as $key) { + if (isset($data[$key])) { + $attr = isset($alias) ? $alias . '.' . $key : $key; + $where[$key] = [$attr, '=', $data[$key]]; + } else { + throw new Exception('miss complex primary data'); + } + } } - // 检测缓存 - if (isset($key) && Cache::get($key)) { - // 删除缓存 - Cache::rm($key); + if (!empty($where)) { + if (isset($this->options['where']['AND'])) { + $this->options['where']['AND'] = array_merge($this->options['where']['AND'], $where); + } else { + $this->options['where']['AND'] = $where; + } } - // 执行操作 - return $this->execute($sql, $bind); + + return; } /** @@ -2152,9 +3188,9 @@ class Query * @access protected * @return array */ - protected function parseExpress() + protected function parseOptions() { - $options = $this->options; + $options = $this->getOptions(); // 获取数据表 if (empty($options['table'])) { @@ -2165,62 +3201,34 @@ class Query $options['where'] = []; } elseif (isset($options['view'])) { // 视图查询条件处理 - foreach (['AND', 'OR'] as $logic) { - if (isset($options['where'][$logic])) { - foreach ($options['where'][$logic] as $key => $val) { - if (array_key_exists($key, $options['map'])) { - $options['where'][$logic][$options['map'][$key]] = $val; - unset($options['where'][$logic][$key]); - } - } - } - } - - if (isset($options['order'])) { - // 视图查询排序处理 - if (is_string($options['order'])) { - $options['order'] = explode(',', $options['order']); - } - foreach ($options['order'] as $key => $val) { - if (is_numeric($key)) { - if (strpos($val, ' ')) { - list($field, $sort) = explode(' ', $val); - if (array_key_exists($field, $options['map'])) { - $options['order'][$options['map'][$field]] = $sort; - unset($options['order'][$key]); - } - } elseif (array_key_exists($val, $options['map'])) { - $options['order'][$options['map'][$val]] = 'asc'; - unset($options['order'][$key]); - } - } elseif (array_key_exists($key, $options['map'])) { - $options['order'][$options['map'][$key]] = $val; - unset($options['order'][$key]); - } - } - } - } - - // 表别名 - if (!empty($options['alias'])) { - $options['table'] .= ' ' . $options['alias']; + $this->parseView($options); } if (!isset($options['field'])) { $options['field'] = '*'; } + foreach (['data', 'order'] as $name) { + if (!isset($options[$name])) { + $options[$name] = []; + } + } + if (!isset($options['strict'])) { $options['strict'] = $this->getConfig('fields_strict'); } - foreach (['master', 'lock', 'fetch_class', 'fetch_sql', 'distinct'] as $name) { + foreach (['master', 'lock', 'fetch_pdo', 'fetch_sql', 'distinct'] as $name) { if (!isset($options[$name])) { $options[$name] = false; } } - foreach (['join', 'union', 'group', 'having', 'limit', 'order', 'force', 'comment'] as $name) { + if (isset(static::$readMaster['*']) || (is_string($options['table']) && isset(static::$readMaster[$options['table']]))) { + $options['master'] = true; + } + + foreach (['join', 'union', 'group', 'having', 'limit', 'force', 'comment'] as $name) { if (!isset($options[$name])) { $options[$name] = ''; } @@ -2235,8 +3243,38 @@ class Query $options['limit'] = $offset . ',' . $listRows; } - $this->options = []; + $this->options = $options; + return $options; } + /** + * 注册回调方法 + * @access public + * @param string $event 事件名 + * @param callable $callback 回调方法 + * @return void + */ + public static function event($event, $callback) + { + self::$event[$event] = $callback; + } + + /** + * 触发事件 + * @access public + * @param string $event 事件名 + * @return bool + */ + public function trigger($event) + { + $result = false; + + if (isset(self::$event[$event])) { + $result = Container::getInstance()->invoke(self::$event[$event], [$this]); + } + + return $result; + } + } diff --git a/library/think/db/builder/Mysql.php b/library/think/db/builder/Mysql.php index 04586906510ef91fddee3fb567486381d70a57e6..ab21648e157a48e1c011fe5f079befd98f6d411c 100644 --- a/library/think/db/builder/Mysql.php +++ b/library/think/db/builder/Mysql.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,40 +12,156 @@ namespace think\db\builder; use think\db\Builder; +use think\db\Expression; +use think\db\Query; /** * mysql数据库驱动 */ class Mysql extends Builder { - protected $updateSql = 'UPDATE %TABLE% %JOIN% SET %SET% %WHERE% %ORDER%%LIMIT% %LOCK%%COMMENT%'; + // 查询表达式解析 + protected $parser = [ + 'parseCompare' => ['=', '<>', '>', '>=', '<', '<='], + 'parseLike' => ['LIKE', 'NOT LIKE'], + 'parseBetween' => ['NOT BETWEEN', 'BETWEEN'], + 'parseIn' => ['NOT IN', 'IN'], + 'parseExp' => ['EXP'], + 'parseRegexp' => ['REGEXP', 'NOT REGEXP'], + 'parseNull' => ['NOT NULL', 'NULL'], + 'parseBetweenTime' => ['BETWEEN TIME', 'NOT BETWEEN TIME'], + 'parseTime' => ['< TIME', '> TIME', '<= TIME', '>= TIME'], + 'parseExists' => ['NOT EXISTS', 'EXISTS'], + 'parseColumn' => ['COLUMN'], + ]; + + protected $insertAllSql = '%INSERT% INTO %TABLE% (%FIELD%) VALUES %DATA% %COMMENT%'; + protected $updateSql = 'UPDATE %TABLE% %JOIN% SET %SET% %WHERE% %ORDER%%LIMIT% %LOCK%%COMMENT%'; /** - * 字段和表名处理 + * 生成insertall SQL + * @access public + * @param Query $query 查询对象 + * @param array $dataSet 数据集 + * @param bool $replace 是否replace + * @return string + */ + public function insertAll(Query $query, $dataSet, $replace = false) + { + $options = $query->getOptions(); + + // 获取合法的字段 + if ('*' == $options['field']) { + $allowFields = $this->connection->getTableFields($options['table']); + } else { + $allowFields = $options['field']; + } + + // 获取绑定信息 + $bind = $this->connection->getFieldsBind($options['table']); + + foreach ($dataSet as $k => $data) { + $data = $this->parseData($query, $data, $allowFields, $bind, '_' . $k); + + $values[] = '( ' . implode(',', array_values($data)) . ' )'; + + if (!isset($insertFields)) { + $insertFields = array_keys($data); + } + } + + $fields = []; + foreach ($insertFields as $field) { + $fields[] = $this->parseKey($query, $field); + } + + return str_replace( + ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'], + [ + $replace ? 'REPLACE' : 'INSERT', + $this->parseTable($query, $options['table']), + implode(' , ', $fields), + implode(' , ', $values), + $this->parseComment($query, $options['comment']), + ], + $this->insertAllSql); + } + + /** + * 正则查询 * @access protected - * @param string $key + * @param Query $query 查询对象 + * @param string $key + * @param string $exp + * @param Expression $value + * @param string $field * @return string */ - protected function parseKey($key) + protected function parseRegexp(Query $query, $key, $exp, Expression $value, $field) { + return $key . ' ' . $exp . ' ' . $value->getValue(); + } + + /** + * 字段和表名处理 + * @access public + * @param Query $query 查询对象 + * @param mixed $key 字段名 + * @param bool $strict 严格检测 + * @return string + */ + public function parseKey(Query $query, $key, $strict = false) + { + if (is_numeric($key)) { + return $key; + } elseif ($key instanceof Expression) { + return $key->getValue(); + } + $key = trim($key); - if (strpos($key, '$.') && false === strpos($key, '(')) { + + if (strpos($key, '->') && false === strpos($key, '(')) { // JSON字段支持 - list($field, $name) = explode('$.', $key); - $key = 'json_extract(' . $field . ', \'$.' . $name . '\')'; + list($field, $name) = explode('->', $key, 2); + + return 'json_extract(' . $this->parseKey($query, $field) . ', \'$.' . str_replace('->', '.', $name) . '\')'; + } elseif (strpos($key, '.') && !preg_match('/[,\'\"\(\)`\s]/', $key)) { + list($table, $key) = explode('.', $key, 2); + + $alias = $query->getOptions('alias'); + + if ('__TABLE__' == $table) { + $table = $query->getOptions('table'); + $table = is_array($table) ? array_shift($table) : $table; + } + + if (isset($alias[$table])) { + $table = $alias[$table]; + } } - if (!preg_match('/[,\'\"\*\(\)`.\s]/', $key)) { + + if ('*' != $key && ($strict || !preg_match('/[,\'\"\*\(\)`.\s]/', $key))) { $key = '`' . $key . '`'; } + + if (isset($table)) { + if (strpos($table, '.')) { + $table = str_replace('.', '`.`', $table); + } + + $key = '`' . $table . '`.' . $key; + } + return $key; } /** * 随机排序 * @access protected + * @param Query $query 查询对象 * @return string */ - protected function parseRand() + protected function parseRand(Query $query) { return 'rand()'; } diff --git a/library/think/db/builder/Pgsql.php b/library/think/db/builder/Pgsql.php index 0a955a5b71cc4d68efddbb1cb752f18aaca98432..742c7db3795658db928c57f420893dafffd6df19 100644 --- a/library/think/db/builder/Pgsql.php +++ b/library/think/db/builder/Pgsql.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,6 +12,7 @@ namespace think\db\builder; use think\db\Builder; +use think\db\Query; /** * Pgsql数据库驱动 @@ -19,15 +20,20 @@ use think\db\Builder; class Pgsql extends Builder { + protected $insertSql = 'INSERT INTO %TABLE% (%FIELD%) VALUES (%DATA%) %COMMENT%'; + protected $insertAllSql = 'INSERT INTO %TABLE% (%FIELD%) %DATA% %COMMENT%'; + /** * limit分析 * @access protected - * @param mixed $limit + * @param Query $query 查询对象 + * @param mixed $limit * @return string */ - public function parseLimit($limit) + public function parseLimit(Query $query, $limit) { $limitStr = ''; + if (!empty($limit)) { $limit = explode(',', $limit); if (count($limit) > 1) { @@ -36,32 +42,61 @@ class Pgsql extends Builder $limitStr .= ' LIMIT ' . $limit[0] . ' '; } } + return $limitStr; } /** * 字段和表名处理 - * @access protected - * @param string $key + * @access public + * @param Query $query 查询对象 + * @param mixed $key 字段名 + * @param bool $strict 严格检测 * @return string */ - protected function parseKey($key) + public function parseKey(Query $query, $key, $strict = false) { + if (is_numeric($key)) { + return $key; + } elseif ($key instanceof Expression) { + return $key->getValue(); + } + $key = trim($key); - if (strpos($key, '$.') && false === strpos($key, '(')) { + + if (strpos($key, '->') && false === strpos($key, '(')) { // JSON字段支持 - list($field, $name) = explode('$.', $key); + list($field, $name) = explode('->', $key); $key = $field . '->>\'' . $name . '\''; + } elseif (strpos($key, '.')) { + list($table, $key) = explode('.', $key, 2); + + $alias = $query->getOptions('alias'); + + if ('__TABLE__' == $table) { + $table = $query->getOptions('table'); + $table = is_array($table) ? array_shift($table) : $table; + } + + if (isset($alias[$table])) { + $table = $alias[$table]; + } } + + if (isset($table)) { + $key = $table . '.' . $key; + } + return $key; } /** * 随机排序 * @access protected + * @param Query $query 查询对象 * @return string */ - protected function parseRand() + protected function parseRand(Query $query) { return 'RANDOM()'; } diff --git a/library/think/db/builder/Sqlite.php b/library/think/db/builder/Sqlite.php index 17e59cb25d75a00b32cdd8e2608ca91190645d28..2b887ca8ef55bcc78be6a1cabcffaa3b13a1ba39 100644 --- a/library/think/db/builder/Sqlite.php +++ b/library/think/db/builder/Sqlite.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -12,6 +12,7 @@ namespace think\db\builder; use think\db\Builder; +use think\db\Query; /** * Sqlite数据库驱动 @@ -22,11 +23,14 @@ class Sqlite extends Builder /** * limit * @access public + * @param Query $query 查询对象 + * @param mixed $limit * @return string */ - public function parseLimit($limit) + public function parseLimit(Query $query, $limit) { $limitStr = ''; + if (!empty($limit)) { $limit = explode(',', $limit); if (count($limit) > 1) { @@ -35,17 +39,58 @@ class Sqlite extends Builder $limitStr .= ' LIMIT ' . $limit[0] . ' '; } } + return $limitStr; } /** * 随机排序 * @access protected + * @param Query $query 查询对象 * @return string */ - protected function parseRand() + protected function parseRand(Query $query) { return 'RANDOM()'; } + /** + * 字段和表名处理 + * @access public + * @param Query $query 查询对象 + * @param mixed $key 字段名 + * @param bool $strict 严格检测 + * @return string + */ + public function parseKey(Query $query, $key, $strict = false) + { + if (is_numeric($key)) { + return $key; + } elseif ($key instanceof Expression) { + return $key->getValue(); + } + + $key = trim($key); + + if (strpos($key, '.')) { + list($table, $key) = explode('.', $key, 2); + + $alias = $query->getOptions('alias'); + + if ('__TABLE__' == $table) { + $table = $query->getOptions('table'); + $table = is_array($table) ? array_shift($table) : $table; + } + + if (isset($alias[$table])) { + $table = $alias[$table]; + } + } + + if (isset($table)) { + $key = $table . '.' . $key; + } + + return $key; + } } diff --git a/library/think/db/builder/Sqlsrv.php b/library/think/db/builder/Sqlsrv.php index bf630d90ffdb0e07715c06330f65f72a8a8c7557..25da4d9fda92aaa716515cfbc4e05a3016ab1506 100644 --- a/library/think/db/builder/Sqlsrv.php +++ b/library/think/db/builder/Sqlsrv.php @@ -12,6 +12,8 @@ namespace think\db\builder; use think\db\Builder; +use think\db\Expression; +use think\db\Query; /** * Sqlsrv数据库驱动 @@ -21,85 +23,129 @@ class Sqlsrv extends Builder protected $selectSql = 'SELECT T1.* FROM (SELECT thinkphp.*, ROW_NUMBER() OVER (%ORDER%) AS ROW_NUMBER FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%) AS thinkphp) AS T1 %LIMIT%%COMMENT%'; protected $selectInsertSql = 'SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%'; protected $updateSql = 'UPDATE %TABLE% SET %SET% FROM %TABLE% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; - protected $deleteSql = 'DELETE FROM %TABLE% %USING% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; + protected $deleteSql = 'DELETE FROM %TABLE% %USING% FROM %TABLE% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; + protected $insertSql = 'INSERT INTO %TABLE% (%FIELD%) VALUES (%DATA%) %COMMENT%'; + protected $insertAllSql = 'INSERT INTO %TABLE% (%FIELD%) %DATA% %COMMENT%'; /** * order分析 * @access protected - * @param mixed $order + * @param Query $query 查询对象 + * @param mixed $order * @return string */ - protected function parseOrder($order) + protected function parseOrder(Query $query, $order) { - if (is_array($order)) { - $array = []; - foreach ($order as $key => $val) { + if (empty($order)) { + return ' ORDER BY rand()'; + } + + $array = []; + + foreach ($order as $key => $val) { + if ($val instanceof Expression) { + $array[] = $val->getValue(); + } elseif ('[rand]' == $val) { + $array[] = $this->parseRand($query); + } else { if (is_numeric($key)) { - if (false === strpos($val, '(')) { - $array[] = $this->parseKey($val); - } elseif ('[rand]' == $val) { - $array[] = $this->parseRand(); - } + list($key, $sort) = explode(' ', strpos($val, ' ') ? $val : $val . ' '); } else { - $sort = in_array(strtolower(trim($val)), ['asc', 'desc']) ? ' ' . $val : ''; - $array[] = $this->parseKey($key) . ' ' . $sort; + $sort = $val; } + + $sort = in_array(strtolower($sort), ['asc', 'desc'], true) ? ' ' . $sort : ''; + $array[] = $this->parseKey($query, $key, true) . $sort; } - $order = implode(',', $array); } - return !empty($order) ? ' ORDER BY ' . $order : ' ORDER BY rand()'; + + return ' ORDER BY ' . implode(',', $array); } /** * 随机排序 * @access protected + * @param Query $query 查询对象 * @return string */ - protected function parseRand() + protected function parseRand(Query $query) { return 'rand()'; } /** - * 字段名分析 - * @access protected - * @param string $key + * 字段和表名处理 + * @access public + * @param Query $query 查询对象 + * @param mixed $key 字段名 + * @param bool $strict 严格检测 * @return string */ - protected function parseKey($key) + public function parseKey(Query $query, $key, $strict = false) { + if (is_numeric($key)) { + return $key; + } elseif ($key instanceof Expression) { + return $key->getValue(); + } + $key = trim($key); - if (!is_numeric($key) && !preg_match('/[,\'\"\*\(\)\[.\s]/', $key)) { + + if (strpos($key, '.') && !preg_match('/[,\'\"\(\)\[\s]/', $key)) { + list($table, $key) = explode('.', $key, 2); + + $alias = $query->getOptions('alias'); + + if ('__TABLE__' == $table) { + $table = $query->getOptions('table'); + $table = is_array($table) ? array_shift($table) : $table; + } + + if (isset($alias[$table])) { + $table = $alias[$table]; + } + } + + if ('*' != $key && ($strict || !preg_match('/[,\'\"\*\(\)\[.\s]/', $key))) { $key = '[' . $key . ']'; } + + if (isset($table)) { + $key = '[' . $table . '].' . $key; + } + return $key; } /** * limit * @access protected - * @param mixed $limit + * @param Query $query 查询对象 + * @param mixed $limit * @return string */ - protected function parseLimit($limit) + protected function parseLimit(Query $query, $limit) { if (empty($limit)) { return ''; } $limit = explode(',', $limit); + if (count($limit) > 1) { $limitStr = '(T1.ROW_NUMBER BETWEEN ' . $limit[0] . ' + 1 AND ' . $limit[0] . ' + ' . $limit[1] . ')'; } else { $limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND ' . $limit[0] . ")"; } + return 'WHERE ' . $limitStr; } - public function selectInsert($fields, $table, $options) + public function selectInsert(Query $query, $fields, $table) { $this->selectSql = $this->selectInsertSql; - return parent::selectInsert($fields, $table, $options); + + return parent::selectInsert($query, $fields, $table); } } diff --git a/library/think/db/connector/Mysql.php b/library/think/db/connector/Mysql.php index 47b069fbd3c413326081454a5ea6ef4bdd8cf357..93b8a1825bde159ecb0cf11cf6b7e1eca3d70c90 100644 --- a/library/think/db/connector/Mysql.php +++ b/library/think/db/connector/Mysql.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,7 +13,7 @@ namespace think\db\connector; use PDO; use think\db\Connection; -use think\Log; +use think\db\Query; /** * mysql数据库驱动 @@ -21,47 +21,76 @@ use think\Log; class Mysql extends Connection { + protected $builder = '\\think\\db\\builder\\Mysql'; + + /** + * 初始化 + * @access protected + * @return void + */ + protected function initialize() + { + // Point类型支持 + Query::extend('point', function ($query, $field, $value = null, $fun = 'GeomFromText', $type = 'POINT') { + if (!is_null($value)) { + $query->data($field, ['point', $value, $fun, $type]); + } else { + if (is_string($field)) { + $field = explode(',', $field); + } + $query->setOption('point', $field); + } + + return $query; + }); + } + /** * 解析pdo连接的dsn信息 * @access protected - * @param array $config 连接信息 + * @param array $config 连接信息 * @return string */ protected function parseDsn($config) { - $dsn = 'mysql:dbname=' . $config['database'] . ';host=' . $config['hostname']; - if (!empty($config['hostport'])) { - $dsn .= ';port=' . $config['hostport']; - } elseif (!empty($config['socket'])) { - $dsn .= ';unix_socket=' . $config['socket']; + if (!empty($config['socket'])) { + $dsn = 'mysql:unix_socket=' . $config['socket']; + } elseif (!empty($config['hostport'])) { + $dsn = 'mysql:host=' . $config['hostname'] . ';port=' . $config['hostport']; + } else { + $dsn = 'mysql:host=' . $config['hostname']; } + $dsn .= ';dbname=' . $config['database']; + if (!empty($config['charset'])) { $dsn .= ';charset=' . $config['charset']; } + return $dsn; } /** * 取得数据表的字段信息 * @access public - * @param string $tableName + * @param string $tableName * @return array */ public function getFields($tableName) { - $this->initConnect(true); list($tableName) = explode(' ', $tableName); - if (strpos($tableName, '.')) { - $tableName = str_replace('.', '`.`', $tableName); + + if (false === strpos($tableName, '`')) { + if (strpos($tableName, '.')) { + $tableName = str_replace('.', '`.`', $tableName); + } + $tableName = '`' . $tableName . '`'; } - $sql = 'SHOW COLUMNS FROM `' . $tableName . '`'; - // 调试开始 - $this->debug(true); - $pdo = $this->linkID->query($sql); - // 调试结束 - $this->debug(false, $sql); + + $sql = 'SHOW COLUMNS FROM ' . $tableName; + $pdo = $this->query($sql, [], false, true); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; + if ($result) { foreach ($result as $key => $val) { $val = array_change_key_case($val); @@ -75,36 +104,34 @@ class Mysql extends Connection ]; } } + return $this->fieldCase($info); } /** * 取得数据库的表信息 * @access public - * @param string $dbName + * @param string $dbName * @return array */ public function getTables($dbName = '') { - $this->initConnect(true); - $sql = !empty($dbName) ? 'SHOW TABLES FROM ' . $dbName : 'SHOW TABLES '; - // 调试开始 - $this->debug(true); - $pdo = $this->linkID->query($sql); - // 调试结束 - $this->debug(false, $sql); + $sql = !empty($dbName) ? 'SHOW TABLES FROM ' . $dbName : 'SHOW TABLES '; + $pdo = $this->query($sql, [], false, true); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; + foreach ($result as $key => $val) { $info[$key] = current($val); } + return $info; } /** * SQL性能分析 * @access protected - * @param string $sql + * @param string $sql * @return array */ protected function getExplain($sql) @@ -112,11 +139,13 @@ class Mysql extends Connection $pdo = $this->linkID->query("EXPLAIN " . $sql); $result = $pdo->fetch(PDO::FETCH_ASSOC); $result = array_change_key_case($result); + if (isset($result['extra'])) { if (strpos($result['extra'], 'filesort') || strpos($result['extra'], 'temporary')) { - Log::record('SQL:' . $this->queryStr . '[' . $result['extra'] . ']', 'warn'); + $this->log('SQL:' . $this->queryStr . '[' . $result['extra'] . ']', 'warn'); } } + return $result; } @@ -124,4 +153,57 @@ class Mysql extends Connection { return true; } + + /** + * 启动XA事务 + * @access public + * @param string $xid XA事务id + * @return void + */ + public function startTransXa($xid) + { + $this->initConnect(true); + if (!$this->linkID) { + return false; + } + + $this->execute("XA START '$xid'"); + } + + /** + * 预编译XA事务 + * @access public + * @param string $xid XA事务id + * @return void + */ + public function prepareXa($xid) + { + $this->initConnect(true); + $this->execute("XA END '$xid'"); + $this->execute("XA PREPARE '$xid'"); + } + + /** + * 提交XA事务 + * @access public + * @param string $xid XA事务id + * @return void + */ + public function commitXa($xid) + { + $this->initConnect(true); + $this->execute("XA COMMIT '$xid'"); + } + + /** + * 回滚XA事务 + * @access public + * @param string $xid XA事务id + * @return void + */ + public function rollbackXa($xid) + { + $this->initConnect(true); + $this->execute("XA ROLLBACK '$xid'"); + } } diff --git a/library/think/db/connector/Pgsql.php b/library/think/db/connector/Pgsql.php index e9866cf31302599f77fac730accae7421f9e7736..ee9fca017da3144e776a92cc658af8b93ba35318 100644 --- a/library/think/db/connector/Pgsql.php +++ b/library/think/db/connector/Pgsql.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -19,40 +19,48 @@ use think\db\Connection; */ class Pgsql extends Connection { + protected $builder = '\\think\\db\\builder\\Pgsql'; + + // PDO连接参数 + protected $params = [ + PDO::ATTR_CASE => PDO::CASE_NATURAL, + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, + PDO::ATTR_STRINGIFY_FETCHES => false, + ]; /** * 解析pdo连接的dsn信息 * @access protected - * @param array $config 连接信息 + * @param array $config 连接信息 * @return string */ protected function parseDsn($config) { $dsn = 'pgsql:dbname=' . $config['database'] . ';host=' . $config['hostname']; + if (!empty($config['hostport'])) { $dsn .= ';port=' . $config['hostport']; } + return $dsn; } /** * 取得数据表的字段信息 * @access public - * @param string $tableName + * @param string $tableName * @return array */ public function getFields($tableName) { - $this->initConnect(true); list($tableName) = explode(' ', $tableName); $sql = 'select fields_name as "field",fields_type as "type",fields_not_null as "null",fields_key_name as "key",fields_default as "default",fields_default as "extra" from table_msg(\'' . $tableName . '\');'; - // 调试开始 - $this->debug(true); - $pdo = $this->linkID->query($sql); - // 调试结束 - $this->debug(false, $sql); + + $pdo = $this->query($sql, [], false, true); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; + if ($result) { foreach ($result as $key => $val) { $val = array_change_key_case($val); @@ -66,36 +74,34 @@ class Pgsql extends Connection ]; } } + return $this->fieldCase($info); } /** * 取得数据库的表信息 * @access public - * @param string $dbName + * @param string $dbName * @return array */ public function getTables($dbName = '') { - $this->initConnect(true); - $sql = "select tablename as Tables_in_test from pg_tables where schemaname ='public'"; - // 调试开始 - $this->debug(true); - $pdo = $this->linkID->query($sql); - // 调试结束 - $this->debug(false, $sql); + $sql = "select tablename as Tables_in_test from pg_tables where schemaname ='public'"; + $pdo = $this->query($sql, [], false, true); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; + foreach ($result as $key => $val) { $info[$key] = current($val); } + return $info; } /** * SQL性能分析 * @access protected - * @param string $sql + * @param string $sql * @return array */ protected function getExplain($sql) diff --git a/library/think/db/connector/Sqlite.php b/library/think/db/connector/Sqlite.php index 95b023e5b268805a400efd9ca7b87f836ee39d40..5b9b3fa64d9aa428f2c96c7c01215b49b6ee6f8a 100644 --- a/library/think/db/connector/Sqlite.php +++ b/library/think/db/connector/Sqlite.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -20,36 +20,36 @@ use think\db\Connection; class Sqlite extends Connection { + protected $builder = '\\think\\db\\builder\\Sqlite'; + /** * 解析pdo连接的dsn信息 * @access protected - * @param array $config 连接信息 + * @param array $config 连接信息 * @return string */ protected function parseDsn($config) { $dsn = 'sqlite:' . $config['database']; + return $dsn; } /** * 取得数据表的字段信息 * @access public - * @param string $tableName + * @param string $tableName * @return array */ public function getFields($tableName) { - $this->initConnect(true); list($tableName) = explode(' ', $tableName); $sql = 'PRAGMA table_info( ' . $tableName . ' )'; - // 调试开始 - $this->debug(true); - $pdo = $this->linkID->query($sql); - // 调试结束 - $this->debug(false, $sql); + + $pdo = $this->query($sql, [], false, true); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; + if ($result) { foreach ($result as $key => $val) { $val = array_change_key_case($val); @@ -63,38 +63,37 @@ class Sqlite extends Connection ]; } } + return $this->fieldCase($info); } /** * 取得数据库的表信息 * @access public - * @param string $dbName + * @param string $dbName * @return array */ public function getTables($dbName = '') { - $this->initConnect(true); $sql = "SELECT name FROM sqlite_master WHERE type='table' " . "UNION ALL SELECT name FROM sqlite_temp_master " . "WHERE type='table' ORDER BY name"; - // 调试开始 - $this->debug(true); - $pdo = $this->linkID->query($sql); - // 调试结束 - $this->debug(false, $sql); + + $pdo = $this->query($sql, [], false, true); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; + foreach ($result as $key => $val) { $info[$key] = current($val); } + return $info; } /** * SQL性能分析 * @access protected - * @param string $sql + * @param string $sql * @return array */ protected function getExplain($sql) diff --git a/library/think/db/connector/Sqlsrv.php b/library/think/db/connector/Sqlsrv.php index 18148051362093ad13d1aae27212e84ba35b042c..adefbb35c3a14e5d7ff4e0043e3ba2656ab83cdb 100644 --- a/library/think/db/connector/Sqlsrv.php +++ b/library/think/db/connector/Sqlsrv.php @@ -23,48 +23,51 @@ class Sqlsrv extends Connection protected $params = [ PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, ]; + protected $builder = '\\think\\db\\builder\\Sqlsrv'; + /** * 解析pdo连接的dsn信息 * @access protected - * @param array $config 连接信息 + * @param array $config 连接信息 * @return string */ protected function parseDsn($config) { $dsn = 'sqlsrv:Database=' . $config['database'] . ';Server=' . $config['hostname']; + if (!empty($config['hostport'])) { $dsn .= ',' . $config['hostport']; } + return $dsn; } /** * 取得数据表的字段信息 * @access public - * @param string $tableName + * @param string $tableName * @return array */ public function getFields($tableName) { - $this->initConnect(true); list($tableName) = explode(' ', $tableName); - $sql = "SELECT column_name, data_type, column_default, is_nullable + + $sql = "SELECT column_name, data_type, column_default, is_nullable FROM information_schema.tables AS t JOIN information_schema.columns AS c ON t.table_catalog = c.table_catalog AND t.table_schema = c.table_schema AND t.table_name = c.table_name WHERE t.table_name = '$tableName'"; - // 调试开始 - $this->debug(true); - $pdo = $this->linkID->query($sql); - // 调试结束 - $this->debug(false, $sql); + + $pdo = $this->query($sql, [], false, true); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; + if ($result) { foreach ($result as $key => $val) { $val = array_change_key_case($val); @@ -78,49 +81,148 @@ class Sqlsrv extends Connection ]; } } + $sql = "SELECT column_name FROM information_schema.key_column_usage WHERE table_name='$tableName'"; + // 调试开始 $this->debug(true); + $pdo = $this->linkID->query($sql); + // 调试结束 $this->debug(false, $sql); + $result = $pdo->fetch(PDO::FETCH_ASSOC); + if ($result) { $info[$result['column_name']]['primary'] = true; } + return $this->fieldCase($info); } /** * 取得数据表的字段信息 * @access public - * @param string $dbName + * @param string $dbName * @return array */ public function getTables($dbName = '') { - $this->initConnect(true); $sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' "; - // 调试开始 - $this->debug(true); - $pdo = $this->linkID->query($sql); - // 调试结束 - $this->debug(false, $sql); + + $pdo = $this->query($sql, [], false, true); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; + foreach ($result as $key => $val) { $info[$key] = current($val); } + return $info; } + /** + * 得到某个列的数组 + * @access public + * @param Query $query 查询对象 + * @param string $field 字段名 多个字段用逗号分隔 + * @param string $key 索引 + * @return array + */ + public function column(Query $query, $field, $key = '') + { + $options = $query->getOptions(); + + if (empty($options['fetch_sql']) && !empty($options['cache'])) { + // 判断查询缓存 + $cache = $options['cache']; + + $guid = is_string($cache['key']) ? $cache['key'] : $this->getCacheKey($query, $field); + + $result = Container::get('cache')->get($guid); + + if (false !== $result) { + return $result; + } + } + + if (isset($options['field'])) { + $query->removeOption('field'); + } + + if (is_null($field)) { + $field = '*'; + } elseif ($key && '*' != $field) { + $field = $key . ',' . $field; + } + + if (is_string($field)) { + $field = array_map('trim', explode(',', $field)); + } + + $query->setOption('field', $field); + + // 生成查询SQL + $sql = $this->builder->select($query); + + $bind = $query->getBind(); + + if (!empty($options['fetch_sql'])) { + // 获取实际执行的SQL语句 + return $this->getRealSql($sql, $bind); + } + + // 执行查询操作 + $pdo = $this->query($sql, $bind, $options['master'], true); + + if (1 == $pdo->columnCount()) { + $result = $pdo->fetchAll(PDO::FETCH_COLUMN); + } else { + $resultSet = $pdo->fetchAll(PDO::FETCH_ASSOC); + + if ('*' == $field && $key) { + $result = array_column($resultSet, null, $key); + } elseif ($resultSet) { + $fields = array_keys($resultSet[0]); + $count = count($fields); + $key1 = array_shift($fields); + $key2 = $fields ? array_shift($fields) : ''; + $key = $key ?: $key1; + + if (strpos($key, '.')) { + list($alias, $key) = explode('.', $key); + } + + if (3 == $count) { + $column = $key2; + } elseif ($count < 3) { + $column = $key1; + } else { + $column = null; + } + + $result = array_column($resultSet, $column, $key); + } else { + $result = []; + } + } + + if (isset($cache) && isset($guid)) { + // 缓存数据 + $this->cacheData($guid, $result, $cache); + } + + return $result; + } + /** * SQL性能分析 * @access protected - * @param string $sql + * @param string $sql * @return array */ protected function getExplain($sql) diff --git a/library/think/db/exception/BindParamException.php b/library/think/db/exception/BindParamException.php index 585a0d73aec6f027f8c71536ecc932d361c075c0..dce0c7bfcd4d0b9925ad5458bc853c4ba3ae31ee 100644 --- a/library/think/db/exception/BindParamException.php +++ b/library/think/db/exception/BindParamException.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -16,16 +16,17 @@ use think\exception\DbException; /** * PDO参数绑定异常 */ -class BindParamException extends DbException +class BindParamException extends DbException { /** * BindParamException constructor. - * @param string $message - * @param array $config - * @param string $sql - * @param array $bind - * @param int $code + * @access public + * @param string $message + * @param array $config + * @param string $sql + * @param array $bind + * @param int $code */ public function __construct($message, $config, $sql, $bind, $code = 10502) { diff --git a/library/think/db/exception/DataNotFoundException.php b/library/think/db/exception/DataNotFoundException.php index efd66d3bfc8f49edbf7db87061672258f9c8b533..883e333e356d7fa0f80ddc79cd779ed592b74c91 100644 --- a/library/think/db/exception/DataNotFoundException.php +++ b/library/think/db/exception/DataNotFoundException.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,20 +13,21 @@ namespace think\db\exception; use think\exception\DbException; -class DataNotFoundException extends DbException +class DataNotFoundException extends DbException { protected $table; /** * DbException constructor. - * @param string $message - * @param string $table - * @param array $config + * @access public + * @param string $message + * @param string $table + * @param array $config */ - public function __construct($message, $table = '', Array $config = []) + public function __construct($message, $table = '', array $config = []) { - $this->message = $message; - $this->table = $table; + $this->message = $message; + $this->table = $table; $this->setData('Database Config', $config); } diff --git a/library/think/db/exception/ModelNotFoundException.php b/library/think/db/exception/ModelNotFoundException.php index 69b70965bf0d7724a5ee9419fa3bbb5d99d52950..ae52baf3b36de62f0c0ea613d96fb00e94e6d9fe 100644 --- a/library/think/db/exception/ModelNotFoundException.php +++ b/library/think/db/exception/ModelNotFoundException.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -13,19 +13,21 @@ namespace think\db\exception; use think\exception\DbException; -class ModelNotFoundException extends DbException +class ModelNotFoundException extends DbException { protected $model; /** * 构造方法 - * @param string $message - * @param string $model + * @access public + * @param string $message + * @param string $model + * @param array $config */ - public function __construct($message, $model = '', Array $config = []) + public function __construct($message, $model = '', array $config = []) { - $this->message = $message; - $this->model = $model; + $this->message = $message; + $this->model = $model; $this->setData('Database Config', $config); } diff --git a/library/think/debug/Console.php b/library/think/debug/Console.php index 8a232c8c1bc8a9c525f3e335eb8dea0e95ad3700..dd063c1c32026e500ff7ad6a80bc42e77482eabd 100644 --- a/library/think/debug/Console.php +++ b/library/think/debug/Console.php @@ -11,11 +11,8 @@ namespace think\debug; -use think\Cache; -use think\Config; +use think\Container; use think\Db; -use think\Debug; -use think\Request; use think\Response; /** @@ -24,7 +21,7 @@ use think\Response; class Console { protected $config = [ - 'trace_tabs' => ['base' => '基本', 'file' => '文件', 'info' => '流程', 'notice|error' => '错误', 'sql' => 'SQL', 'debug|log' => '调试'], + 'tabs' => ['base' => '基本', 'file' => '文件', 'info' => '流程', 'notice|error' => '错误', 'sql' => 'SQL', 'debug|log' => '调试'], ]; // 实例化并传入参数 @@ -38,13 +35,13 @@ class Console /** * 调试输出接口 * @access public - * @param Response $response Response对象 - * @param array $log 日志信息 + * @param Response $response Response对象 + * @param array $log 日志信息 * @return bool */ public function output(Response $response, array $log = []) { - $request = Request::instance(); + $request = Container::get('request'); $contentType = $response->getHeader('Content-Type'); $accept = $request->header('accept'); if (strpos($accept, 'application/json') === 0 || $request->isAjax()) { @@ -53,9 +50,9 @@ class Console return false; } // 获取基本信息 - $runtime = number_format(microtime(true) - THINK_START_TIME, 10); + $runtime = number_format(microtime(true) - Container::get('app')->getBeginTime(), 10); $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞'; - $mem = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2); + $mem = number_format((memory_get_usage() - Container::get('app')->getBeginMem()) / 1024, 2); if (isset($_SERVER['HTTP_HOST'])) { $uri = $_SERVER['SERVER_PROTOCOL'] . ' ' . $_SERVER['REQUEST_METHOD'] . ' : ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; @@ -68,19 +65,18 @@ class Console '请求信息' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']) . ' ' . $uri, '运行时间' => number_format($runtime, 6) . 's [ 吞吐率:' . $reqs . 'req/s ] 内存消耗:' . $mem . 'kb 文件加载:' . count(get_included_files()), '查询信息' => Db::$queryTimes . ' queries ' . Db::$executeTimes . ' writes ', - '缓存信息' => Cache::$readTimes . ' reads,' . Cache::$writeTimes . ' writes', - '配置加载' => count(Config::get()), + '缓存信息' => Container::get('cache')->getReadTimes() . ' reads,' . Container::get('cache')->getWriteTimes() . ' writes', ]; if (session_id()) { $base['会话信息'] = 'SESSION_ID=' . session_id(); } - $info = Debug::getFile(true); + $info = Container::get('debug')->getFile(true); // 页面Trace信息 $trace = []; - foreach ($this->config['trace_tabs'] as $name => $title) { + foreach ($this->config['tabs'] as $name => $title) { $name = strtolower($name); switch ($name) { case 'base': // 基本信息 @@ -121,7 +117,7 @@ JS; protected function console($type, $msg) { $type = strtolower($type); - $trace_tabs = array_values($this->config['trace_tabs']); + $trace_tabs = array_values($this->config['tabs']); $line[] = ($type == $trace_tabs[0] || '调试' == $type || '错误' == $type) ? "console.group('{$type}');" : "console.groupCollapsed('{$type}');"; @@ -137,12 +133,12 @@ JS; } break; case '错误': - $msg = str_replace("\n", '\n', $m); + $msg = str_replace("\n", '\n', addslashes(is_scalar($m) ? $m : json_encode($m))); $style = 'color:#F4006B;font-size:14px;'; $line[] = "console.error(\"%c{$msg}\", \"{$style}\");"; break; case 'sql': - $msg = str_replace("\n", '\n', $m); + $msg = str_replace("\n", '\n', addslashes($m)); $style = "color:#009bb4;"; $line[] = "console.log(\"%c{$msg}\", \"{$style}\");"; break; diff --git a/library/think/debug/Html.php b/library/think/debug/Html.php index f8651aa9277b72f6559db1328e4b9c8426ee8d41..85f354af00140c0c10d4498c56c93a16ea0e4dc9 100644 --- a/library/think/debug/Html.php +++ b/library/think/debug/Html.php @@ -11,11 +11,8 @@ namespace think\debug; -use think\Cache; -use think\Config; +use think\Container; use think\Db; -use think\Debug; -use think\Request; use think\Response; /** @@ -24,27 +21,26 @@ use think\Response; class Html { protected $config = [ - 'trace_file' => '', - 'trace_tabs' => ['base' => '基本', 'file' => '文件', 'info' => '流程', 'notice|error' => '错误', 'sql' => 'SQL', 'debug|log' => '调试'], + 'file' => '', + 'tabs' => ['base' => '基本', 'file' => '文件', 'info' => '流程', 'notice|error' => '错误', 'sql' => 'SQL', 'debug|log' => '调试'], ]; // 实例化并传入参数 public function __construct(array $config = []) { - $this->config['trace_file'] = THINK_PATH . 'tpl/page_trace.tpl'; - $this->config = array_merge($this->config, $config); + $this->config = array_merge($this->config, $config); } /** * 调试输出接口 * @access public - * @param Response $response Response对象 - * @param array $log 日志信息 + * @param Response $response Response对象 + * @param array $log 日志信息 * @return bool */ public function output(Response $response, array $log = []) { - $request = Request::instance(); + $request = Container::get('request'); $contentType = $response->getHeader('Content-Type'); $accept = $request->header('accept'); if (strpos($accept, 'application/json') === 0 || $request->isAjax()) { @@ -53,9 +49,9 @@ class Html return false; } // 获取基本信息 - $runtime = number_format(microtime(true) - THINK_START_TIME, 10); + $runtime = number_format(microtime(true) - Container::get('app')->getBeginTime(), 10, '.', ''); $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞'; - $mem = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2); + $mem = number_format((memory_get_usage() - Container::get('app')->getBeginMem()) / 1024, 2); // 页面Trace信息 if (isset($_SERVER['HTTP_HOST'])) { @@ -67,19 +63,18 @@ class Html '请求信息' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']) . ' ' . $uri, '运行时间' => number_format($runtime, 6) . 's [ 吞吐率:' . $reqs . 'req/s ] 内存消耗:' . $mem . 'kb 文件加载:' . count(get_included_files()), '查询信息' => Db::$queryTimes . ' queries ' . Db::$executeTimes . ' writes ', - '缓存信息' => Cache::$readTimes . ' reads,' . Cache::$writeTimes . ' writes', - '配置加载' => count(Config::get()), + '缓存信息' => Container::get('cache')->getReadTimes() . ' reads,' . Container::get('cache')->getWriteTimes() . ' writes', ]; if (session_id()) { $base['会话信息'] = 'SESSION_ID=' . session_id(); } - $info = Debug::getFile(true); + $info = Container::get('debug')->getFile(true); // 页面Trace信息 $trace = []; - foreach ($this->config['trace_tabs'] as $name => $title) { + foreach ($this->config['tabs'] as $name => $title) { $name = strtolower($name); switch ($name) { case 'base': // 基本信息 @@ -104,7 +99,7 @@ class Html } // 调用Trace页面模板 ob_start(); - include $this->config['trace_file']; + include $this->config['file']; return ob_get_clean(); } diff --git a/library/think/exception/DbException.php b/library/think/exception/DbException.php index bd6fb442712489ba1d38992017cb016532d76361..0f504257c821b5233abd06cdc560dfa89600b9f9 100644 --- a/library/think/exception/DbException.php +++ b/library/think/exception/DbException.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -20,10 +20,11 @@ class DbException extends Exception { /** * DbException constructor. - * @param string $message - * @param array $config - * @param string $sql - * @param int $code + * @access public + * @param string $message + * @param array $config + * @param string $sql + * @param int $code */ public function __construct($message, array $config, $sql, $code = 10500) { @@ -36,6 +37,7 @@ class DbException extends Exception 'Error SQL' => $sql, ]); + unset($config['username'], $config['password']); $this->setData('Database Config', $config); } diff --git a/library/think/exception/ErrorException.php b/library/think/exception/ErrorException.php index 2f1525c0584ccb4ba300d65e70873785cdd15876..3143b8f703203364ea095cdc504e239e4c6bd64d 100644 --- a/library/think/exception/ErrorException.php +++ b/library/think/exception/ErrorException.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -29,25 +29,24 @@ class ErrorException extends Exception /** * 错误异常构造函数 - * @param integer $severity 错误级别 - * @param string $message 错误详细信息 - * @param string $file 出错文件路径 - * @param integer $line 出错行号 - * @param array $context 错误上下文,会包含错误触发处作用域内所有变量的数组 + * @access public + * @param integer $severity 错误级别 + * @param string $message 错误详细信息 + * @param string $file 出错文件路径 + * @param integer $line 出错行号 */ - public function __construct($severity, $message, $file, $line, array $context = []) + public function __construct($severity, $message, $file, $line) { $this->severity = $severity; $this->message = $message; $this->file = $file; $this->line = $line; $this->code = 0; - - empty($context) || $this->setData('Error Context', $context); } /** * 获取错误级别 + * @access public * @return integer 错误级别 */ final public function getSeverity() diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index 8b6e6c40db1deede87d82353625aba93fb1efc7c..02c85ec1397324aa5ea847b639cc8fa6bb47bf5e 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -12,23 +12,26 @@ namespace think\exception; use Exception; -use think\App; -use think\Config; use think\console\Output; -use think\Lang; -use think\Log; +use think\Container; use think\Response; class Handle { - + protected $render; protected $ignoreReport = [ '\\think\\exception\\HttpException', ]; + public function setRender($render) + { + $this->render = $render; + } + /** * Report or log an exception. * + * @access public * @param \Exception $exception * @return void */ @@ -36,7 +39,7 @@ class Handle { if (!$this->isIgnoreReport($exception)) { // 收集异常数据 - if (App::$debug) { + if (Container::get('app')->isDebug()) { $data = [ 'file' => $exception->getFile(), 'line' => $exception->getLine(), @@ -52,7 +55,11 @@ class Handle $log = "[{$data['code']}]{$data['message']}"; } - Log::record($log, 'error'); + if (Container::get('app')->config('log.record_trace')) { + $log .= "\r\n" . $exception->getTraceAsString(); + } + + Container::get('log')->record($log, 'error'); } } @@ -63,17 +70,27 @@ class Handle return true; } } + return false; } /** * Render an exception into an HTTP response. * + * @access public * @param \Exception $e * @return Response */ public function render(Exception $e) { + if ($this->render && $this->render instanceof \Closure) { + $result = call_user_func_array($this->render, [$e]); + + if ($result) { + return $result; + } + } + if ($e instanceof HttpException) { return $this->renderHttpException($e); } else { @@ -82,26 +99,30 @@ class Handle } /** - * @param Output $output - * @param Exception $e + * @access public + * @param Output $output + * @param Exception $e */ public function renderForConsole(Output $output, Exception $e) { - if (App::$debug) { + if (Container::get('app')->isDebug()) { $output->setVerbosity(Output::VERBOSITY_DEBUG); } + $output->renderException($e); } /** - * @param HttpException $e + * @access protected + * @param HttpException $e * @return Response */ protected function renderHttpException(HttpException $e) { $status = $e->getStatusCode(); - $template = Config::get('http_exception_template'); - if (!App::$debug && !empty($template[$status])) { + $template = Container::get('app')->config('http_exception_template'); + + if (!Container::get('app')->isDebug() && !empty($template[$status])) { return Response::create($template[$status], 'view', $status)->assign(['e' => $e]); } else { return $this->convertExceptionToResponse($e); @@ -109,13 +130,14 @@ class Handle } /** - * @param Exception $exception + * @access protected + * @param Exception $exception * @return Response */ protected function convertExceptionToResponse(Exception $exception) { // 收集异常数据 - if (App::$debug) { + if (Container::get('app')->isDebug()) { // 调试模式,获取详细的错误信息 $data = [ 'name' => get_class($exception), @@ -144,9 +166,9 @@ class Handle 'message' => $this->getMessage($exception), ]; - if (!Config::get('show_error_msg')) { + if (!Container::get('app')->config('show_error_msg')) { // 不显示详细错误信息 - $data['message'] = Config::get('error_message'); + $data['message'] = Container::get('app')->config('error_message'); } } @@ -159,10 +181,11 @@ class Handle ob_start(); extract($data); - include Config::get('exception_tmpl'); + include Container::get('app')->config('exception_tmpl'); + // 获取并清空缓存 $content = ob_get_clean(); - $response = new Response($content, 'html'); + $response = Response::create($content, 'html'); if ($exception instanceof HttpException) { $statusCode = $exception->getStatusCode(); @@ -173,52 +196,62 @@ class Handle $statusCode = 500; } $response->code($statusCode); + return $response; } /** * 获取错误编码 * ErrorException则使用错误级别作为错误编码 + * @access protected * @param \Exception $exception * @return integer 错误编码 */ protected function getCode(Exception $exception) { $code = $exception->getCode(); + if (!$code && $exception instanceof ErrorException) { $code = $exception->getSeverity(); } + return $code; } /** * 获取错误信息 * ErrorException则使用错误级别作为错误编码 + * @access protected * @param \Exception $exception * @return string 错误信息 */ protected function getMessage(Exception $exception) { $message = $exception->getMessage(); - if (IS_CLI) { + + if (PHP_SAPI == 'cli') { return $message; } + $lang = Container::get('lang'); + if (strpos($message, ':')) { $name = strstr($message, ':', true); - $message = Lang::has($name) ? Lang::get($name) . strstr($message, ':') : $message; + $message = $lang->has($name) ? $lang->get($name) . strstr($message, ':') : $message; } elseif (strpos($message, ',')) { $name = strstr($message, ',', true); - $message = Lang::has($name) ? Lang::get($name) . ':' . substr(strstr($message, ','), 1) : $message; - } elseif (Lang::has($message)) { - $message = Lang::get($message); + $message = $lang->has($name) ? $lang->get($name) . ':' . substr(strstr($message, ','), 1) : $message; + } elseif ($lang->has($message)) { + $message = $lang->get($message); } + return $message; } /** * 获取出错文件内容 * 获取错误的前9行和后9行 + * @access protected * @param \Exception $exception * @return array 错误文件内容 */ @@ -237,30 +270,37 @@ class Handle } catch (Exception $e) { $source = []; } + return $source; } /** * 获取异常扩展信息 * 用于非调试模式html返回类型显示 + * @access protected * @param \Exception $exception * @return array 异常类定义的扩展数据 */ protected function getExtendData(Exception $exception) { $data = []; + if ($exception instanceof \think\Exception) { $data = $exception->getData(); } + return $data; } /** * 获取常量列表 + * @access private * @return array 常量列表 */ private static function getConst() { - return get_defined_constants(true)['user']; + $const = get_defined_constants(true); + + return isset($const['user']) ? $const['user'] : []; } } diff --git a/library/think/exception/PDOException.php b/library/think/exception/PDOException.php index 677092b9cb2594d84fc31de9ba76e3d7a1fc22b8..25240b6806f1b5f0c04e96459573e90cb70c34f0 100644 --- a/library/think/exception/PDOException.php +++ b/library/think/exception/PDOException.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,8 +11,6 @@ namespace think\exception; -use think\exception\DbException; - /** * PDO异常处理类 * 重新封装了系统的\PDOException类 @@ -21,10 +19,11 @@ class PDOException extends DbException { /** * PDOException constructor. - * @param \PDOException $exception - * @param array $config - * @param string $sql - * @param int $code + * @access public + * @param \PDOException $exception + * @param array $config + * @param string $sql + * @param int $code */ public function __construct(\PDOException $exception, array $config, $sql, $code = 10501) { diff --git a/console.php b/library/think/exception/RouteNotFoundException.php similarity index 76% rename from console.php rename to library/think/exception/RouteNotFoundException.php index 3d518e78fae75e2ec0474feed2f60fa972393ae0..d22e3a63792e126963562c83b8e644aa4e027444 100644 --- a/console.php +++ b/library/think/exception/RouteNotFoundException.php @@ -9,12 +9,14 @@ // | Author: yunwuxin <448901948@qq.com> // +---------------------------------------------------------------------- -namespace think; +namespace think\exception; -// ThinkPHP 引导文件 -// 加载基础文件 -require __DIR__ . '/base.php'; +class RouteNotFoundException extends HttpException +{ -// 执行应用 -App::initCommon(); -Console::init(); \ No newline at end of file + public function __construct() + { + parent::__construct(404, 'Route Not Found'); + } + +} diff --git a/library/think/facade/App.php b/library/think/facade/App.php new file mode 100644 index 0000000000000000000000000000000000000000..37d995106860a562031d0e1e7e298309f742afdc --- /dev/null +++ b/library/think/facade/App.php @@ -0,0 +1,54 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\App + * @mixin \think\App + * @method \think\App bind(string $bind) static 绑定模块或者控制器 + * @method void initialize() static 初始化应用 + * @method void init(string $module='') static 初始化模块 + * @method \think\Response run() static 执行应用 + * @method \think\App dispatch(\think\route\Dispatch $dispatch) static 设置当前请求的调度信息 + * @method void log(mixed $log, string $type = 'info') static 记录调试信息 + * @method mixed config(string $name='') static 获取配置参数 + * @method \think\route\Dispatch routeCheck() static URL路由检测(根据PATH_INFO) + * @method \think\App routeMust(bool $must = false) static 设置应用的路由检测机制 + * @method \think\Model model(string $name = '', string $layer = 'model', bool $appendSuffix = false, string $common = 'common') static 实例化模型 + * @method object controller(string $name, string $layer = 'controller', bool $appendSuffix = false, string $empty = '') static 实例化控制器 + * @method \think\Validate validate(string $name = '', string $layer = 'validate', bool $appendSuffix = false, string $common = 'common') static 实例化验证器类 + * @method \think\db\Query db(mixed $config = [], mixed $name = false) static 数据库初始化 + * @method mixed action(string $url, $vars = [], $layer = 'controller', $appendSuffix = false) static 调用模块的操作方法 + * @method string parseClass(string $module, string $layer, string $name, bool $appendSuffix = false) static 解析应用类的类名 + * @method string version() static 获取框架版本 + * @method bool isDebug() static 是否为调试模式 + * @method string getModulePath() static 获取当前模块路径 + * @method void setModulePath(string $path) static 设置当前模块路径 + * @method string getRootPath() static 获取应用根目录 + * @method string getAppPath() static 获取应用类库目录 + * @method string getRuntimePath() static 获取应用运行时目录 + * @method string getThinkPath() static 获取核心框架目录 + * @method string getRoutePath() static 获取路由目录 + * @method string getConfigPath() static 获取应用配置目录 + * @method string getConfigExt() static 获取配置后缀 + * @method string setNamespace(string $namespace) static 设置应用类库命名空间 + * @method string getNamespace() static 获取应用类库命名空间 + * @method string getSuffix() static 是否启用类库后缀 + * @method float getBeginTime() static 获取应用开启时间 + * @method integer getBeginMem() static 获取应用初始内存占用 + * @method \think\Container container() static 获取容器实例 + */ +class App extends Facade +{ +} diff --git a/library/think/facade/Build.php b/library/think/facade/Build.php new file mode 100644 index 0000000000000000000000000000000000000000..465962367394438521f4960ccc125c433f8230c2 --- /dev/null +++ b/library/think/facade/Build.php @@ -0,0 +1,24 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Build + * @mixin \think\Build + * @method void run(array $build = [], string $namespace = 'app', bool $suffix = false) static 根据传入的build资料创建目录和文件 + * @method void module(string $module = '', array $list = [], string $namespace = 'app', bool $suffix = false) static 创建模块 + */ +class Build extends Facade +{ +} diff --git a/library/think/facade/Cache.php b/library/think/facade/Cache.php new file mode 100644 index 0000000000000000000000000000000000000000..3011d6b3a5ae7073a6a792b05a461d1173c70277 --- /dev/null +++ b/library/think/facade/Cache.php @@ -0,0 +1,36 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Cache + * @mixin \think\Cache + * @method \think\cache\Driver connect(array $options = [], mixed $name = false) static 连接缓存 + * @method \think\cache\Driver init(array $options = []) static 初始化缓存 + * @method \think\cache\Driver store(string $name = '') static 切换缓存类型 + * @method bool has(string $name) static 判断缓存是否存在 + * @method mixed get(string $name, mixed $default = false) static 读取缓存 + * @method mixed pull(string $name) static 读取缓存并删除 + * @method mixed set(string $name, mixed $value, int $expire = null) static 设置缓存 + * @method mixed remember(string $name, mixed $value, int $expire = null) static 如果不存在则写入缓存 + * @method mixed inc(string $name, int $step = 1) static 自增缓存(针对数值缓存) + * @method mixed dec(string $name, int $step = 1) static 自减缓存(针对数值缓存) + * @method bool rm(string $name) static 删除缓存 + * @method bool clear(string $tag = null) static 清除缓存 + * @method mixed tag(string $name, mixed $keys = null, bool $overlay = false) static 缓存标签 + * @method object handler() static 返回句柄对象,可执行其它高级方法 + */ +class Cache extends Facade +{ +} diff --git a/tests/thinkphp/library/think/log/driver/fileTest.php b/library/think/facade/Config.php similarity index 50% rename from tests/thinkphp/library/think/log/driver/fileTest.php rename to library/think/facade/Config.php index 3453c09ba998f10858ecbffab9a065b6e15be2bb..3332413b8a2e35e0db3ee725b08dc6ee832078dc 100644 --- a/tests/thinkphp/library/think/log/driver/fileTest.php +++ b/library/think/facade/Config.php @@ -1,34 +1,27 @@ - -// +---------------------------------------------------------------------- - -/** - * Test File Log - */ -namespace tests\thinkphp\library\think\log\driver; - -use think\Log; - -class fileTest extends \PHPUnit_Framework_TestCase -{ - protected function setUp() - { - Log::init(['type' => 'file']); - } - - public function testRecord() - { - $record_msg = 'record'; - Log::record($record_msg, 'notice'); - $logs = Log::getLog(); - - $this->assertNotFalse(array_search($record_msg, $logs['notice'])); - } -} + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Config + * @mixin \think\Config + * @method bool has(string $name) static 检测配置是否存在 + * @method array pull(string $name) static 获取一级配置 + * @method mixed get(string $name) static 获取配置参数 + * @method mixed set(string $name, mixed $value = null) static 设置配置参数 + * @method array reset(string $prefix ='') static 重置配置参数 + */ +class Config extends Facade +{ +} diff --git a/tests/thinkphp/library/think/cache/driver/fileTest.php b/library/think/facade/Cookie.php similarity index 39% rename from tests/thinkphp/library/think/cache/driver/fileTest.php rename to library/think/facade/Cookie.php index aee0bd46f816e7631ba2e692bce8676301c59f11..18efbde0cb82e48c5afe8a48610e1e3607422490 100644 --- a/tests/thinkphp/library/think/cache/driver/fileTest.php +++ b/library/think/facade/Cookie.php @@ -1,46 +1,30 @@ - -// +---------------------------------------------------------------------- - -/** - * File缓存驱动测试 - * @author 刘志淳 - */ - -namespace tests\thinkphp\library\think\cache\driver; - -class fileTest extends cacheTestCase -{ - private $_cacheInstance = null; - - /** - * 基境缓存类型 - */ - protected function setUp() - { - \think\Cache::connect(['type' => 'File', 'path' => CACHE_PATH]); - } - - /** - * @return FileCache - */ - protected function getCacheInstance() - { - if (null === $this->_cacheInstance) { - $this->_cacheInstance = new \think\cache\driver\File(); - } - return $this->_cacheInstance; - } - - // skip testExpire - public function testExpire() - { - } -} + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Cookie + * @mixin \think\Cookie + * @method void init(array $config = []) static 初始化 + * @method bool has(string $name,string $prefix = null) static 判断Cookie数据 + * @method mixed prefix(string $prefix = '') static 设置或者获取cookie作用域(前缀) + * @method mixed get(string $name,string $prefix = null) static Cookie获取 + * @method mixed set(string $name, mixed $value = null, mixed $option = null) static 设置Cookie + * @method void forever(string $name, mixed $value = null, mixed $option = null) static 永久保存Cookie数据 + * @method void delete(string $name, string $prefix = null) static Cookie删除 + * @method void clear($prefix = null) static Cookie清空 + */ +class Cookie extends Facade +{ +} diff --git a/library/think/facade/Debug.php b/library/think/facade/Debug.php new file mode 100644 index 0000000000000000000000000000000000000000..ac482a41eb29ff89c45f468c8343cbbf0d8cc167 --- /dev/null +++ b/library/think/facade/Debug.php @@ -0,0 +1,31 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Debug + * @mixin \think\Debug + * @method void remark(string $name, mixed $value = '') static 记录时间(微秒)和内存使用情况 + * @method int getRangeTime(string $start, string $end, mixed $dec = 6) static 统计某个区间的时间(微秒)使用情况 + * @method int getUseTime(int $dec = 6) static 统计从开始到统计时的时间(微秒)使用情况 + * @method string getThroughputRate(string $start, string $end, mixed $dec = 6) static 获取当前访问的吞吐率情况 + * @method string getRangeMem(string $start, string $end, mixed $dec = 2) static 记录区间的内存使用情况 + * @method int getUseMem(int $dec = 2) static 统计从开始到统计时的内存使用情况 + * @method string getMemPeak(string $start, string $end, mixed $dec = 2) static 统计区间的内存峰值情况 + * @method mixed getFile(bool $detail = false) static 获取文件加载信息 + * @method mixed dump(mixed $var, bool $echo = true, string $label = null, int $flags = ENT_SUBSTITUTE) static 浏览器友好的变量输出 + */ +class Debug extends Facade +{ +} diff --git a/library/think/facade/Env.php b/library/think/facade/Env.php new file mode 100644 index 0000000000000000000000000000000000000000..d430d683fda675f8c3575718e346f58d7fdf71f8 --- /dev/null +++ b/library/think/facade/Env.php @@ -0,0 +1,25 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Env + * @mixin \think\Env + * @method void load(string $file) static 读取环境变量定义文件 + * @method mixed get(string $name = null, mixed $default = null) static 获取环境变量值 + * @method void set(mixed $env, string $value = null) static 设置环境变量值 + */ +class Env extends Facade +{ +} diff --git a/tests/thinkphp/library/think/config/driver/xmlTest.php b/library/think/facade/Hook.php similarity index 43% rename from tests/thinkphp/library/think/config/driver/xmlTest.php rename to library/think/facade/Hook.php index 9ab1d257dfa4eac110897dbe2fdc3cc69b75ea9a..e18f83b5d5ecbe34a6186203cf4f3f4b9695abf6 100644 --- a/tests/thinkphp/library/think/config/driver/xmlTest.php +++ b/library/think/facade/Hook.php @@ -2,32 +2,27 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st // +---------------------------------------------------------------------- -/** - * Xml配置测试 - * @author 7IN0SAN9 - */ - -namespace tests\thinkphp\library\think\config\driver; +namespace think\facade; -use think\config; +use think\Facade; -class xmlTest extends \PHPUnit_Framework_TestCase +/** + * @see \think\Hook + * @mixin \think\Hook + * @method \think\Hook alias(mixed $name, mixed $behavior = null) static 指定行为标识 + * @method void add(string $tag, mixed $behavior, bool $first = false) static 动态添加行为扩展到某个标签 + * @method void import(array $tags, bool $recursive = true) static 批量导入插件 + * @method array get(string $tag = '') static 获取插件信息 + * @method mixed listen(string $tag, mixed $params = null, bool $once = false) static 监听标签的行为 + * @method mixed exec(mixed $class, mixed $params = null) static 执行行为 + */ +class Hook extends Facade { - public function testParse() - { - Config::parse('1', 'xml'); - $this->assertEquals(1, Config::get('xmlstring')); - Config::reset(); - Config::parse(__DIR__ . '/fixtures/config.xml'); - $this->assertTrue(Config::has('xmlfile.istrue')); - $this->assertEquals(1, Config::get('xmlfile.istrue')); - Config::reset(); - } } diff --git a/tests/thinkphp/library/think/cache/driver/memcacheTest.php b/library/think/facade/Lang.php similarity index 34% rename from tests/thinkphp/library/think/cache/driver/memcacheTest.php rename to library/think/facade/Lang.php index 15dfaa5a182838ce11c73466c3830c63869e252d..3eb5d4acd2a752faf12adecbc9860522e406ff77 100644 --- a/tests/thinkphp/library/think/cache/driver/memcacheTest.php +++ b/library/think/facade/Lang.php @@ -1,49 +1,32 @@ - -// +---------------------------------------------------------------------- - -/** - * Memcache缓存驱动测试 - * @author 刘志淳 - */ - -namespace tests\thinkphp\library\think\cache\driver; - -class memcacheTest extends cacheTestCase -{ - private $_cacheInstance = null; - - /** - * 基境缓存类型 - */ - protected function setUp() - { - if (!extension_loaded('memcache')) { - $this->markTestSkipped("Memcache没有安装,已跳过测试!"); - } - \think\Cache::connect(['type' => 'memcache', 'expire' => 2]); - } - - /** - * @return ApcCache - */ - protected function getCacheInstance() - { - if (null === $this->_cacheInstance) { - $this->_cacheInstance = new \think\cache\driver\Memcache(['length' => 3]); - } - return $this->_cacheInstance; - } - - // skip testExpire - public function testExpire() - { - } -} + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Lang + * @mixin \think\Lang + * @method mixed range($range = '') static 设定当前的语言 + * @method mixed set(mixed $name, string $value = null, string $range = '') static 设置语言定义 + * @method array load(mixed $file, string $range = '') static 加载语言定义 + * @method mixed get(string $name = null, array $vars = [], string $range = '') static 获取语言定义 + * @method mixed has(string $name, string $range = '') static 获取语言定义 + * @method string detect() static 自动侦测设置获取语言选择 + * @method void saveToCookie(string $lang = null) static 设置当前语言到Cookie + * @method void setLangDetectVar(string $var) static 设置语言自动侦测的变量 + * @method void setLangCookieVar(string $var) static 设置语言的cookie保存变量 + * @method void setAllowLangList(array $list) static 设置允许的语言列表 + */ +class Lang extends Facade +{ +} diff --git a/library/think/facade/Log.php b/library/think/facade/Log.php new file mode 100644 index 0000000000000000000000000000000000000000..3a1fbf88ff9d907b3d4f5d38398868f51695bb39 --- /dev/null +++ b/library/think/facade/Log.php @@ -0,0 +1,40 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Log + * @mixin \think\Log + * @method \think\Log init(array $config = []) static 日志初始化 + * @method mixed getLog(string $type = '') static 获取日志信息 + * @method \think\Log record(mixed $msg, string $type = 'info', array $context = []) static 记录日志信息 + * @method \think\Log clear() static 清空日志信息 + * @method \think\Log key(string $key) static 当前日志记录的授权key + * @method bool check(array $config) static 检查日志写入权限 + * @method bool save() static 保存调试信息 + * @method void write(mixed $msg, string $type = 'info', bool $force = false) static 实时写入日志信息 + * @method void log(string $level,mixed $message, array $context = []) static 记录日志信息 + * @method void emergency(mixed $message, array $context = []) static 记录emergency信息 + * @method void alert(mixed $message, array $context = []) static 记录alert信息 + * @method void critical(mixed $message, array $context = []) static 记录critical信息 + * @method void error(mixed $message, array $context = []) static 记录error信息 + * @method void warning(mixed $message, array $context = []) static 记录warning信息 + * @method void notice(mixed $message, array $context = []) static 记录notice信息 + * @method void info(mixed $message, array $context = []) static 记录info信息 + * @method void debug(mixed $message, array $context = []) static 记录debug信息 + * @method void sql(mixed $message, array $context = []) static 记录sql信息 + */ +class Log extends Facade +{ +} diff --git a/library/think/facade/Middleware.php b/library/think/facade/Middleware.php new file mode 100644 index 0000000000000000000000000000000000000000..46827964246dadbbdbde099b5702168ea411dde3 --- /dev/null +++ b/library/think/facade/Middleware.php @@ -0,0 +1,27 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Middleware + * @mixin \think\Middleware + * @method void import(array $middlewares = []) static 批量设置中间件 + * @method void add(mixed $middleware) static 添加中间件到队列 + * @method void unshift(mixed $middleware) static 添加中间件到队列开头 + * @method array all() static 获取中间件队列 + * @method \think\Response dispatch(\think\Request $request) static 执行中间件调度 + */ +class Middleware extends Facade +{ +} diff --git a/library/think/facade/Request.php b/library/think/facade/Request.php new file mode 100644 index 0000000000000000000000000000000000000000..d0eedb2463d0b1ea4e33b74c119f7a7d97339024 --- /dev/null +++ b/library/think/facade/Request.php @@ -0,0 +1,88 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Request + * @mixin \think\Request + * @method void hook(mixed $method, mixed $callback = null) static Hook 方法注入 + * @method \think\Request create(string $uri, string $method = 'GET', array $params = [], array $cookie = [], array $files = [], array $server = [], string $content = null) static 创建一个URL请求 + * @method mixed domain(bool $port = false) static 获取当前包含协议、端口的域名 + * @method mixed url(bool $domain = false) static 获取当前完整URL + * @method mixed baseUrl(bool $domain = false) static 获取当前URL + * @method mixed baseFile(bool $domain = false) static 获取当前执行的文件 + * @method mixed root(bool $domain = false) static 获取URL访问根地址 + * @method string rootUrl() static 获取URL访问根目录 + * @method string pathinfo() static 获取当前请求URL的pathinfo信息(含URL后缀) + * @method string path() static 获取当前请求URL的pathinfo信息(不含URL后缀) + * @method string ext() static 当前URL的访问后缀 + * @method float time(bool $float = false) static 获取当前请求的时间 + * @method mixed type() static 当前请求的资源类型 + * @method void mimeType(mixed $type, string $val = '') static 设置资源类型 + * @method string method(bool $method = false) static 当前的请求类型 + * @method bool isGet() static 是否为GET请求 + * @method bool isPost() static 是否为POST请求 + * @method bool isPut() static 是否为PUT请求 + * @method bool isDelete() static 是否为DELTE请求 + * @method bool isHead() static 是否为HEAD请求 + * @method bool isPatch() static 是否为PATCH请求 + * @method bool isOptions() static 是否为OPTIONS请求 + * @method bool isCli() static 是否为cli + * @method bool isCgi() static 是否为cgi + * @method mixed param(string $name = '', mixed $default = null, mixed $filter = '') static 获取当前请求的参数 + * @method mixed route(string $name = '', mixed $default = null, mixed $filter = '') static 设置获取路由参数 + * @method mixed get(string $name = '', mixed $default = null, mixed $filter = '') static 设置获取GET参数 + * @method mixed post(string $name = '', mixed $default = null, mixed $filter = '') static 设置获取POST参数 + * @method mixed put(string $name = '', mixed $default = null, mixed $filter = '') static 设置获取PUT参数 + * @method mixed delete(string $name = '', mixed $default = null, mixed $filter = '') static 设置获取DELETE参数 + * @method mixed patch(string $name = '', mixed $default = null, mixed $filter = '') static 设置获取PATCH参数 + * @method mixed request(string $name = '', mixed $default = null, mixed $filter = '') static 获取request变量 + * @method mixed session(string $name = '', mixed $default = null, mixed $filter = '') static 获取session数据 + * @method mixed cookie(string $name = '', mixed $default = null, mixed $filter = '') static 获取cookie参数 + * @method mixed server(string $name = '', mixed $default = null, mixed $filter = '') static 获取server参数 + * @method mixed env(string $name = '', mixed $default = null, mixed $filter = '') static 获取环境变量 + * @method mixed file(string $name = '') static 获取上传的文件信息 + * @method mixed header(string $name = '', mixed $default = null) static 设置或者获取当前的Header + * @method mixed input(array $data,mixed $name = '', mixed $default = null, mixed $filter = '') static 获取变量 支持过滤和默认值 + * @method mixed filter(mixed $filter = null) static 设置或获取当前的过滤规则 + * @method mixed has(string $name, string $type = 'param', bool $checkEmpty = false) static 是否存在某个请求参数 + * @method mixed only(mixed $name, string $type = 'param') static 获取指定的参数 + * @method mixed except(mixed $name, string $type = 'param') static 排除指定参数获取 + * @method bool isSsl() static 当前是否ssl + * @method bool isAjax(bool $ajax = false) static 当前是否Ajax请求 + * @method bool isPjax(bool $pjax = false) static 当前是否Pjax请求 + * @method mixed ip(int $type = 0, bool $adv = true) static 获取客户端IP地址 + * @method bool isMobile() static 检测是否使用手机访问 + * @method string scheme() static 当前URL地址中的scheme参数 + * @method string query() static 当前请求URL地址中的query参数 + * @method string host(bool $stric = false) static 当前请求的host + * @method string port() static 当前请求URL地址中的port参数 + * @method string protocol() static 当前请求 SERVER_PROTOCOL + * @method string remotePort() static 当前请求 REMOTE_PORT + * @method string contentType() static 当前请求 HTTP_CONTENT_TYPE + * @method array routeInfo() static 获取当前请求的路由信息 + * @method array dispatch() static 获取当前请求的调度信息 + * @method string module() static 获取当前的模块名 + * @method string controller(bool $convert = false) static 获取当前的控制器名 + * @method string action(bool $convert = false) static 获取当前的操作名 + * @method string langset() static 获取当前的语言 + * @method string getContent() static 设置或者获取当前请求的content + * @method string getInput() static 获取当前请求的php://input + * @method string token(string $name = '__token__', mixed $type = 'md5') static 生成请求令牌 + * @method string cache(string $key, mixed $expire = null, array $except = [], string $tag = null) static 设置当前地址的请求缓存 + * @method string getCache() static 读取请求缓存设置 + */ +class Request extends Facade +{ +} diff --git a/library/think/facade/Response.php b/library/think/facade/Response.php new file mode 100644 index 0000000000000000000000000000000000000000..4a4de71298008056dc58d0dc1ec5ccb941706937 --- /dev/null +++ b/library/think/facade/Response.php @@ -0,0 +1,38 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Response + * @mixin \think\Response + * @method \think\response create(mixed $data = '', string $type = '', int $code = 200, array $header = [], array $options = []) static 创建Response对象 + * @method void send() static 发送数据到客户端 + * @method \think\Response options(mixed $options = []) static 输出的参数 + * @method \think\Response data(mixed $data) static 输出数据设置 + * @method \think\Response header(mixed $name, string $value = null) static 设置响应头 + * @method \think\Response content(mixed $content) static 设置页面输出内容 + * @method \think\Response code(int $code) static 发送HTTP状态 + * @method \think\Response lastModified(string $time) static LastModified + * @method \think\Response expires(string $time) static expires + * @method \think\Response eTag(string $eTag) static eTag + * @method \think\Response cacheControl(string $cache) static 页面缓存控制 + * @method \think\Response contentType(string $contentType, string $charset = 'utf-8') static 页面输出类型 + * @method mixed getHeader(string $name) static 获取头部信息 + * @method mixed getData() static 获取原始数据 + * @method mixed getContent() static 获取输出数据 + * @method int getCode() static 获取状态码 + */ +class Response extends Facade +{ +} diff --git a/library/think/facade/Route.php b/library/think/facade/Route.php new file mode 100644 index 0000000000000000000000000000000000000000..c9f843d9067993e91772dd7a2e661412932c846c --- /dev/null +++ b/library/think/facade/Route.php @@ -0,0 +1,48 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Route + * @mixin \think\Route + * @method \think\route\Domain domain(mixed $name, mixed $rule = '', array $option = [], array $pattern = []) static 注册域名路由 + * @method \think\Route pattern(mixed $name, string $rule = '') static 注册变量规则 + * @method \think\Route option(mixed $name, mixed $value = '') static 注册路由参数 + * @method \think\Route bind(string $bind) static 设置路由绑定 + * @method mixed getBind(string $bind) static 读取路由绑定 + * @method \think\Route name(string $name) static 设置当前路由标识 + * @method mixed getName(string $name) static 读取路由标识 + * @method void setName(string $name) static 批量导入路由标识 + * @method void import(array $rules, string $type = '*') static 导入配置文件的路由规则 + * @method \think\route\RuleItem rule(string $rule, mixed $route, string $method = '*', array $option = [], array $pattern = []) static 注册路由规则 + * @method void rules(array $rules, string $method = '*', array $option = [], array $pattern = []) static 批量注册路由规则 + * @method \think\route\RuleGroup group(string|array $name, mixed $route, string $method = '*', array $option = [], array $pattern = []) static 注册路由分组 + * @method \think\route\RuleItem any(string $rule, mixed $route, array $option = [], array $pattern = []) static 注册路由 + * @method \think\route\RuleItem get(string $rule, mixed $route, array $option = [], array $pattern = []) static 注册路由 + * @method \think\route\RuleItem post(string $rule, mixed $route, array $option = [], array $pattern = []) static 注册路由 + * @method \think\route\RuleItem put(string $rule, mixed $route, array $option = [], array $pattern = []) static 注册路由 + * @method \think\route\RuleItem delete(string $rule, mixed $route, array $option = [], array $pattern = []) static 注册路由 + * @method \think\route\RuleItem patch(string $rule, mixed $route, array $option = [], array $pattern = []) static 注册路由 + * @method \think\route\Resource resource(string $rule, mixed $route, array $option = [], array $pattern = []) static 注册资源路由 + * @method \think\Route controller(string $rule, mixed $route, array $option = [], array $pattern = []) static 注册控制器路由 + * @method \think\Route alias(string $rule, mixed $route, array $option = [], array $pattern = []) static 注册别名路由 + * @method \think\Route setMethodPrefix(mixed $method, string $prefix = '') static 设置不同请求类型下面的方法前缀 + * @method \think\Route rest(string $name, array $resource = []) static rest方法定义和修改 + * @method \think\Route\RuleItem miss(string $route, string $method = '*', array $option = []) static 注册未匹配路由规则后的处理 + * @method \think\Route\RuleItem auto(string $route) static 注册一个自动解析的URL路由 + * @method \think\Route\Dispatch check(string $url, string $depr = '/', bool $must = false, bool $completeMatch = false) static 检测URL路由 + */ +class Route extends Facade +{ +} diff --git a/library/think/facade/Session.php b/library/think/facade/Session.php new file mode 100644 index 0000000000000000000000000000000000000000..a68db382a3b028ff1cbc3bc097c6dd4dad8dc47f --- /dev/null +++ b/library/think/facade/Session.php @@ -0,0 +1,37 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Session + * @mixin \think\Session + * @method void init(array $config = []) static session初始化 + * @method bool has(string $name,string $prefix = null) static 判断session数据 + * @method mixed prefix(string $prefix = '') static 设置或者获取session作用域(前缀) + * @method mixed get(string $name = '',string $prefix = null) static session获取 + * @method mixed pull(string $name,string $prefix = null) static session获取并删除 + * @method void push(string $key, mixed $value) static 添加数据到一个session数组 + * @method void set(string $name, mixed $value , string $prefix = null) static 设置session数据 + * @method void flash(string $name, mixed $value = null) static session设置 下一次请求有效 + * @method void flush() static 清空当前请求的session数据 + * @method void delete(string $name, string $prefix = null) static 删除session数据 + * @method void clear($prefix = null) static 清空session数据 + * @method void start() static 启动session + * @method void destroy() static 销毁session + * @method void pause() static 暂停session + * @method void regenerate(bool $delete = false) static 重新生成session_id + */ +class Session extends Facade +{ +} diff --git a/library/think/facade/Url.php b/library/think/facade/Url.php new file mode 100644 index 0000000000000000000000000000000000000000..db5a16f2be19a73289b4a3b0cf9cb45e1d924e35 --- /dev/null +++ b/library/think/facade/Url.php @@ -0,0 +1,24 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Url + * @mixin \think\Url + * @method string build(string $url = '', mixed $vars = '', mixed $suffix = true, mixed $domain = false) static URL生成 支持路由反射 + * @method void root(string $root) static 指定当前生成URL地址的root + */ +class Url extends Facade +{ +} diff --git a/library/think/facade/Validate.php b/library/think/facade/Validate.php new file mode 100644 index 0000000000000000000000000000000000000000..423446d4de625a0d84b17f0d811096d1c3385b62 --- /dev/null +++ b/library/think/facade/Validate.php @@ -0,0 +1,65 @@ + +// +---------------------------------------------------------------------- + +namespace think\facade; + +use think\Facade; + +/** + * @see \think\Validate + * @mixin \think\Validate + * @method \think\Validate make(array $rules = [], array $message = [], array $field = []) static 创建一个验证器类 + * @method \think\Validate rule(mixed $name, mixed $rule = '') static 添加字段验证规则 + * @method void extend(string $type, mixed $callback = null) static 注册扩展验证(类型)规则 + * @method void setTypeMsg(mixed $type, string $msg = null) static 设置验证规则的默认提示信息 + * @method \think\Validate message(mixed $name, string $message = '') static 设置提示信息 + * @method \think\Validate scene(string $name) static 设置验证场景 + * @method bool hasScene(string $name) static 判断是否存在某个验证场景 + * @method \think\Validate batch(bool $batch = true) static 设置批量验证 + * @method \think\Validate only(array $fields) static 指定需要验证的字段列表 + * @method \think\Validate remove(mixed $field, mixed $rule = true) static 移除某个字段的验证规则 + * @method \think\Validate append(mixed $field, mixed $rule = null) static 追加某个字段的验证规则 + * @method bool confirm(mixed $value, mixed $rule, array $data = [], string $field = '') static 验证是否和某个字段的值一致 + * @method bool different(mixed $value, mixed $rule, array $data = []) static 验证是否和某个字段的值是否不同 + * @method bool egt(mixed $value, mixed $rule, array $data = []) static 验证是否大于等于某个值 + * @method bool gt(mixed $value, mixed $rule, array $data = []) static 验证是否大于某个值 + * @method bool elt(mixed $value, mixed $rule, array $data = []) static 验证是否小于等于某个值 + * @method bool lt(mixed $value, mixed $rule, array $data = []) static 验证是否小于某个值 + * @method bool eq(mixed $value, mixed $rule) static 验证是否等于某个值 + * @method bool must(mixed $value, mixed $rule) static 必须验证 + * @method bool is(mixed $value, mixed $rule, array $data = []) static 验证字段值是否为有效格式 + * @method bool ip(mixed $value, mixed $rule) static 验证是否有效IP + * @method bool requireIf(mixed $value, mixed $rule) static 验证某个字段等于某个值的时候必须 + * @method bool requireCallback(mixed $value, mixed $rule,array $data) static 通过回调方法验证某个字段是否必须 + * @method bool requireWith(mixed $value, mixed $rule, array $data) static 验证某个字段有值的情况下必须 + * @method bool filter(mixed $value, mixed $rule) static 使用filter_var方式验证 + * @method bool in(mixed $value, mixed $rule) static 验证是否在范围内 + * @method bool notIn(mixed $value, mixed $rule) static 验证是否不在范围内 + * @method bool between(mixed $value, mixed $rule) static between验证数据 + * @method bool notBetween(mixed $value, mixed $rule) static 使用notbetween验证数据 + * @method bool length(mixed $value, mixed $rule) static 验证数据长度 + * @method bool max(mixed $value, mixed $rule) static 验证数据最大长度 + * @method bool min(mixed $value, mixed $rule) static 验证数据最小长度 + * @method bool after(mixed $value, mixed $rule) static 验证日期 + * @method bool before(mixed $value, mixed $rule) static 验证日期 + * @method bool expire(mixed $value, mixed $rule) static 验证有效期 + * @method bool allowIp(mixed $value, mixed $rule) static 验证IP许可 + * @method bool denyIp(mixed $value, mixed $rule) static 验证IP禁用 + * @method bool regex(mixed $value, mixed $rule) static 使用正则验证数据 + * @method bool token(mixed $value, mixed $rule) static 验证表单令牌 + * @method bool dateFormat(mixed $value, mixed $rule) static 验证时间和日期是否符合指定格式 + * @method bool unique(mixed $value, mixed $rule, array $data = [], string $field = '') static 验证是否唯一 + * @method bool check(array $data, mixed $rules = [], string $scene = '') static 数据自动验证 + * @method mixed getError(mixed $value, mixed $rule) static 获取错误信息 + */ +class Validate extends Facade +{ +} diff --git a/tests/thinkphp/library/think/logTest.php b/library/think/facade/View.php similarity index 35% rename from tests/thinkphp/library/think/logTest.php rename to library/think/facade/View.php index 554cf60d153343f5fbd41de547eac9146189eb3d..0309a760fb9e5d21d6c3dce32b619a50e69b7662 100644 --- a/tests/thinkphp/library/think/logTest.php +++ b/library/think/facade/View.php @@ -2,50 +2,30 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st // +---------------------------------------------------------------------- -/** - * Log测试 - * @author liu21st - */ -namespace tests\thinkphp\library\think; +namespace think\facade; -use think\Log; +use think\Facade; -class logTest extends \PHPUnit_Framework_TestCase +/** + * @see \think\View + * @mixin \think\View + * @method \think\View init(mixed $engine = [], array $replace = []) static 初始化 + * @method \think\View share(mixed $name, mixed $value = '') static 模板变量静态赋值 + * @method \think\View assign(mixed $name, mixed $value = '') static 模板变量赋值 + * @method \think\View config(mixed $name, mixed $value = '') static 配置模板引擎 + * @method \think\View exists(mixed $name) static 检查模板是否存在 + * @method \think\View filter(Callable $filter) static 视图内容过滤 + * @method \think\View engine(mixed $engine = []) static 设置当前模板解析的引擎 + * @method string fetch(string $template = '', array $vars = [], array $replace = [], array $config = [], bool $renderContent = false) static 解析和获取模板内容 + * @method string display(string $content = '', array $vars = [], array $replace = [], array $config = []) static 渲染内容输出 + */ +class View extends Facade { - - public function testRecord() - { - Log::clear(); - Log::record('test'); - $this->assertEquals(['log' => ['test']], Log::getLog()); - Log::record('hello', 'info'); - $this->assertEquals(['log' => ['test'], 'info' => ['hello']], Log::getLog()); - Log::clear(); - Log::info('test'); - $this->assertEquals(['info' => ['test']], Log::getLog()); - } - - public function testSave() - { - Log::init(['type' => 'test']); - Log::clear(); - Log::record('test'); - Log::record([1, 2, 3]); - $this->assertTrue(Log::save()); - } - - public function testWrite() - { - Log::init(['type' => 'test']); - Log::clear(); - $this->assertTrue(Log::write('hello', 'info')); - $this->assertTrue(Log::write([1, 2, 3], 'log')); - } } diff --git a/library/think/log/driver/File.php b/library/think/log/driver/File.php index c4e462794744b9ccb6bc8629e27480129a20c237..dfd963c28c768f6e4d2ee8ea12dd27d858ecd337 100644 --- a/library/think/log/driver/File.php +++ b/library/think/log/driver/File.php @@ -11,6 +11,8 @@ namespace think\log\driver; +use think\App; + /** * 本地化调试输出到文件 */ @@ -18,74 +20,261 @@ class File { protected $config = [ 'time_format' => ' c ', + 'single' => false, 'file_size' => 2097152, - 'path' => LOG_PATH, + 'path' => '', 'apart_level' => [], + 'max_files' => 0, + 'json' => false, ]; + protected $app; + // 实例化并传入参数 - public function __construct($config = []) + public function __construct(App $app, $config = []) { + $this->app = $app; + if (is_array($config)) { $this->config = array_merge($this->config, $config); } + + if (empty($this->config['path'])) { + $this->config['path'] = $this->app->getRuntimePath() . 'log' . DIRECTORY_SEPARATOR; + } elseif (substr($this->config['path'], -1) != DIRECTORY_SEPARATOR) { + $this->config['path'] .= DIRECTORY_SEPARATOR; + } } /** * 日志写入接口 * @access public - * @param array $log 日志信息 + * @param array $log 日志信息 + * @param bool $append 是否追加请求信息 * @return bool */ - public function save(array $log = []) + public function save(array $log = [], $append = false) { - $now = date($this->config['time_format']); - $destination = $this->config['path'] . date('Ym') . DS . date('d') . '.log'; + $destination = $this->getMasterLogFile(); $path = dirname($destination); !is_dir($path) && mkdir($path, 0755, true); - //检测日志文件大小,超过配置大小则备份日志文件重新生成 - if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) { - rename($destination, dirname($destination) . DS . $_SERVER['REQUEST_TIME'] . '-' . basename($destination)); - } - - // 获取基本信息 - if (isset($_SERVER['HTTP_HOST'])) { - $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; - } else { - $current_uri = "cmd:" . implode(' ', $_SERVER['argv']); - } + $info = []; - $runtime = number_format(microtime(true) - THINK_START_TIME, 10); - $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞'; - $time_str = ' [运行时间:' . number_format($runtime, 6) . 's][吞吐率:' . $reqs . 'req/s]'; - $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2); - $memory_str = ' [内存消耗:' . $memory_use . 'kb]'; - $file_load = ' [文件加载:' . count(get_included_files()) . ']'; - - $info = '[ log ] ' . $current_uri . $time_str . $memory_str . $file_load . "\r\n"; - $server = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '0.0.0.0'; - $remote = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0'; - $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'CLI'; - $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; foreach ($log as $type => $val) { - $level = ''; + foreach ($val as $msg) { if (!is_string($msg)) { $msg = var_export($msg, true); } - $level .= '[ ' . $type . ' ] ' . $msg . "\r\n"; + + $info[$type][] = $this->config['json'] ? $msg : '[ ' . $type . ' ] ' . $msg; } - if (in_array($type, $this->config['apart_level'])) { + + if (!$this->config['json'] && (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level']))) { // 独立记录的日志级别 - $filename = $path . DS . date('d') . '_' . $type . '.log'; - error_log("[{$now}] {$server} {$remote} {$method} {$uri}\r\n{$level}\r\n---------------------------------------------------------------\r\n", 3, $filename); + $filename = $this->getApartLevelFile($path, $type); + + $this->write($info[$type], $filename, true, $append); + + unset($info[$type]); + } + } + + if ($info) { + return $this->write($info, $destination, false, $append); + } + + return true; + } + + /** + * 日志写入 + * @access protected + * @param array $message 日志信息 + * @param string $destination 日志文件 + * @param bool $apart 是否独立文件写入 + * @param bool $append 是否追加请求信息 + * @return bool + */ + protected function write($message, $destination, $apart = false, $append = false) + { + // 检测日志文件大小,超过配置大小则备份日志文件重新生成 + $this->checkLogSize($destination); + + // 日志信息封装 + $info['timestamp'] = date($this->config['time_format']); + + foreach ($message as $type => $msg) { + $info[$type] = is_array($msg) ? implode("\r\n", $msg) : $msg; + } + + if (PHP_SAPI == 'cli') { + $message = $this->parseCliLog($info); + } else { + // 添加调试日志 + $this->getDebugLog($info, $append, $apart); + + $message = $this->parseLog($info); + } + + return error_log($message, 3, $destination); + } + + /** + * 获取主日志文件名 + * @access public + * @return string + */ + protected function getMasterLogFile() + { + if ($this->config['single']) { + $name = is_string($this->config['single']) ? $this->config['single'] : 'single'; + + $destination = $this->config['path'] . $name . '.log'; + } else { + $cli = PHP_SAPI == 'cli' ? '_cli' : ''; + + if ($this->config['max_files']) { + $filename = date('Ymd') . $cli . '.log'; + $files = glob($this->config['path'] . '*.log'); + + try { + if (count($files) > $this->config['max_files']) { + unlink($files[0]); + } + } catch (\Exception $e) { + } } else { - $info .= $level; + $filename = date('Ym') . DIRECTORY_SEPARATOR . date('d') . $cli . '.log'; + } + + $destination = $this->config['path'] . $filename; + } + + return $destination; + } + + /** + * 获取独立日志文件名 + * @access public + * @param string $path 日志目录 + * @param string $type 日志类型 + * @return string + */ + protected function getApartLevelFile($path, $type) + { + $cli = PHP_SAPI == 'cli' ? '_cli' : ''; + + if ($this->config['single']) { + $name = is_string($this->config['single']) ? $this->config['single'] : 'single'; + + $name .= '_' . $type; + } elseif ($this->config['max_files']) { + $name = date('Ymd') . '_' . $type . $cli; + } else { + $name = date('d') . '_' . $type . $cli; + } + + return $path . DIRECTORY_SEPARATOR . $name . '.log'; + } + + /** + * 检查日志文件大小并自动生成备份文件 + * @access protected + * @param string $destination 日志文件 + * @return void + */ + protected function checkLogSize($destination) + { + if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) { + try { + rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . time() . '-' . basename($destination)); + } catch (\Exception $e) { } } - return error_log("[{$now}] {$server} {$remote} {$method} {$uri}\r\n{$info}\r\n---------------------------------------------------------------\r\n", 3, $destination); } + /** + * CLI日志解析 + * @access protected + * @param array $info 日志信息 + * @return string + */ + protected function parseCliLog($info) + { + if ($this->config['json']) { + $message = json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n"; + } else { + $now = $info['timestamp']; + unset($info['timestamp']); + + $message = implode("\r\n", $info); + + $message = "[{$now}]" . $message . "\r\n"; + } + + return $message; + } + + /** + * 解析日志 + * @access protected + * @param array $info 日志信息 + * @return string + */ + protected function parseLog($info) + { + $requestInfo = [ + 'ip' => $this->app['request']->ip(), + 'method' => $this->app['request']->method(), + 'host' => $this->app['request']->host(), + 'uri' => $this->app['request']->url(), + ]; + + if ($this->config['json']) { + $info = $requestInfo + $info; + return json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n"; + } + + array_unshift($info, "---------------------------------------------------------------\r\n[{$info['timestamp']}] {$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}"); + unset($info['timestamp']); + + return implode("\r\n", $info) . "\r\n"; + } + + protected function getDebugLog(&$info, $append, $apart) + { + if ($this->app->isDebug() && $append) { + + if ($this->config['json']) { + // 获取基本信息 + $runtime = round(microtime(true) - $this->app->getBeginTime(), 10); + $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞'; + + $memory_use = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2); + + $info = [ + 'runtime' => number_format($runtime, 6) . 's', + 'reqs' => $reqs . 'req/s', + 'memory' => $memory_use . 'kb', + 'file' => count(get_included_files()), + ] + $info; + + } elseif (!$apart) { + // 增加额外的调试信息 + $runtime = round(microtime(true) - $this->app->getBeginTime(), 10); + $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞'; + + $memory_use = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2); + + $time_str = '[运行时间:' . number_format($runtime, 6) . 's] [吞吐率:' . $reqs . 'req/s]'; + $memory_str = ' [内存消耗:' . $memory_use . 'kb]'; + $file_load = ' [文件加载:' . count(get_included_files()) . ']'; + + array_unshift($info, $time_str . $memory_str . $file_load); + } + } + } } diff --git a/library/think/log/driver/Socket.php b/library/think/log/driver/Socket.php index f24b6091db6ac73281772911521d2aae54a3fbc9..b4a2cadc7050c8b473d87609f1c399f96ab4cc51 100644 --- a/library/think/log/driver/Socket.php +++ b/library/think/log/driver/Socket.php @@ -11,6 +11,8 @@ namespace think\log\driver; +use think\App; + /** * github: https://github.com/luofei614/SocketLog * @author luofei614 @@ -39,14 +41,17 @@ class Socket ]; protected $allowForceClientIds = []; //配置强制推送且被授权的client_id + protected $app; /** * 架构函数 - * @param array $config 缓存参数 * @access public + * @param array $config 缓存参数 */ - public function __construct(array $config = []) + public function __construct(App $app, array $config = []) { + $this->app = $app; + if (!empty($config)) { $this->config = array_merge($this->config, $config); } @@ -55,32 +60,38 @@ class Socket /** * 调试输出接口 * @access public - * @param array $log 日志信息 + * @param array $log 日志信息 * @return bool */ - public function save(array $log = []) + public function save(array $log = [], $append = false) { if (!$this->check()) { return false; } - $runtime = number_format(microtime(true) - THINK_START_TIME, 10); - $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞'; - $time_str = ' [运行时间:' . number_format($runtime, 6) . 's][吞吐率:' . $reqs . 'req/s]'; - $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2); - $memory_str = ' [内存消耗:' . $memory_use . 'kb]'; - $file_load = ' [文件加载:' . count(get_included_files()) . ']'; - - if (isset($_SERVER['HTTP_HOST'])) { - $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; - } else { - $current_uri = 'cmd:' . implode(' ', $_SERVER['argv']); + + $trace = []; + + if ($this->app->isDebug()) { + $runtime = round(microtime(true) - $this->app->getBeginTime(), 10); + $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞'; + $time_str = ' [运行时间:' . number_format($runtime, 6) . 's][吞吐率:' . $reqs . 'req/s]'; + $memory_use = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2); + $memory_str = ' [内存消耗:' . $memory_use . 'kb]'; + $file_load = ' [文件加载:' . count(get_included_files()) . ']'; + + if (isset($_SERVER['HTTP_HOST'])) { + $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; + } else { + $current_uri = 'cmd:' . implode(' ', $_SERVER['argv']); + } + + // 基本信息 + $trace[] = [ + 'type' => 'group', + 'msg' => $current_uri . $time_str . $memory_str . $file_load, + 'css' => $this->css['page'], + ]; } - // 基本信息 - $trace[] = [ - 'type' => 'group', - 'msg' => $current_uri . $time_str . $memory_str . $file_load, - 'css' => $this->css['page'], - ]; foreach ($log as $type => $val) { $trace[] = [ @@ -88,6 +99,7 @@ class Socket 'msg' => '[ ' . $type . ' ]', 'css' => isset($this->css[$type]) ? $this->css[$type] : '', ]; + foreach ($val as $msg) { if (!is_string($msg)) { $msg = var_export($msg, true); @@ -98,6 +110,7 @@ class Socket 'css' => '', ]; } + $trace[] = [ 'type' => 'groupEnd', 'msg' => '', @@ -111,11 +124,13 @@ class Socket 'msg' => '[ file ]', 'css' => '', ]; + $trace[] = [ 'type' => 'log', 'msg' => implode("\n", get_included_files()), 'css' => '', ]; + $trace[] = [ 'type' => 'groupEnd', 'msg' => '', @@ -130,6 +145,7 @@ class Socket ]; $tabid = $this->getClientArg('tabid'); + if (!$client_id = $this->getClientArg('client_id')) { $client_id = ''; } @@ -143,16 +159,18 @@ class Socket } else { $this->sendToClient($tabid, $client_id, $trace, ''); } + return true; } /** * 发送给指定客户端 + * @access protected * @author Zjmainstay - * @param $tabid - * @param $client_id - * @param $logs - * @param $force_client_id + * @param $tabid + * @param $client_id + * @param $logs + * @param $force_client_id */ protected function sendToClient($tabid, $client_id, $logs, $force_client_id) { @@ -162,20 +180,25 @@ class Socket 'logs' => $logs, 'force_client_id' => $force_client_id, ]; + $msg = @json_encode($logs); $address = '/' . $client_id; //将client_id作为地址, server端通过地址判断将日志发布给谁 + $this->send($this->config['host'], $msg, $address); } protected function check() { $tabid = $this->getClientArg('tabid'); + //是否记录日志的检查 if (!$tabid && !$this->config['force_client_ids']) { return false; } + //用户认证 $allow_client_ids = $this->config['allow_client_ids']; + if (!empty($allow_client_ids)) { //通过数组交集得出授权强制推送的client_id $this->allowForceClientIds = array_intersect($allow_client_ids, $this->config['force_client_ids']); @@ -190,6 +213,7 @@ class Socket } else { $this->allowForceClientIds = $this->config['force_client_ids']; } + return true; } @@ -204,41 +228,49 @@ class Socket } if (!isset($_SERVER[$key])) { - return null; + return; } + if (empty($args)) { if (!preg_match('/SocketLog\((.*?)\)/', $_SERVER[$key], $match)) { $args = ['tabid' => null]; - return null; + return; } parse_str($match[1], $args); } + if (isset($args[$name])) { return $args[$name]; } - return null; + + return; } /** - * @param string $host - $host of socket server - * @param string $message - 发送的消息 - * @param string $address - 地址 + * @access protected + * @param string $host - $host of socket server + * @param string $message - 发送的消息 + * @param string $address - 地址 * @return bool */ protected function send($host, $message = '', $address = '/') { $url = 'http://' . $host . ':' . $this->port . $address; $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $message); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 10); + $headers = [ "Content-Type: application/json;charset=UTF-8", ]; + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //设置header + return curl_exec($ch); } diff --git a/library/think/log/driver/Test.php b/library/think/log/driver/Test.php index 7f663384ccf8fcaba287243a75f008be6aa417ef..e67f747279fb1f26b3483e65a1b2099779b675cb 100644 --- a/library/think/log/driver/Test.php +++ b/library/think/log/driver/Test.php @@ -19,7 +19,7 @@ class Test /** * 日志写入接口 * @access public - * @param array $log 日志信息 + * @param array $log 日志信息 * @return bool */ public function save(array $log = []) diff --git a/library/think/model/Collection.php b/library/think/model/Collection.php new file mode 100644 index 0000000000000000000000000000000000000000..3a9b60f590586baee595960c665035f6b8477e4b --- /dev/null +++ b/library/think/model/Collection.php @@ -0,0 +1,96 @@ + +// +---------------------------------------------------------------------- + +namespace think\model; + +use think\Collection as BaseCollection; +use think\Model; + +class Collection extends BaseCollection +{ + /** + * 返回数组中指定的一列 + * @access public + * @param string $column_key + * @param string|null $index_key + * @return array + */ + public function column($column_key, $index_key = null) + { + return array_column($this->toArray(), $column_key, $index_key); + } + + /** + * 延迟预载入关联查询 + * @access public + * @param mixed $relation 关联 + * @return $this + */ + public function load($relation) + { + $item = current($this->items); + $item->eagerlyResultSet($this->items, $relation); + + return $this; + } + + /** + * 设置需要隐藏的输出属性 + * @access public + * @param array $hidden 属性列表 + * @param bool $override 是否覆盖 + * @return $this + */ + public function hidden($hidden = [], $override = false) + { + $this->each(function ($model) use ($hidden, $override) { + /** @var Model $model */ + $model->hidden($hidden, $override); + }); + + return $this; + } + + /** + * 设置需要输出的属性 + * @access public + * @param array $visible + * @param bool $override 是否覆盖 + * @return $this + */ + public function visible($visible = [], $override = false) + { + $this->each(function ($model) use ($visible, $override) { + /** @var Model $model */ + $model->visible($visible, $override); + }); + + return $this; + } + + /** + * 设置需要追加的输出属性 + * @access public + * @param array $append 属性列表 + * @param bool $override 是否覆盖 + * @return $this + */ + public function append($append = [], $override = false) + { + $this->each(function ($model) use ($append, $override) { + /** @var Model $model */ + $model && $model->append($append, $override); + }); + + return $this; + } + +} diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php deleted file mode 100644 index c28d0fd7558635f52abd851a7f7e9e407c264b30..0000000000000000000000000000000000000000 --- a/library/think/model/Merge.php +++ /dev/null @@ -1,315 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace think\model; - -use think\Db; -use think\Model; - -class Merge extends Model -{ - - protected $relationModel = []; // HAS ONE 关联的模型列表 - protected $fk = ''; // 外键名 默认为主表名_id - protected $mapFields = []; // 需要处理的模型映射字段,避免混淆 array( id => 'user.id' ) - - /** - * 架构函数 - * @access public - * @param array|object $data 数据 - */ - public function __construct($data = []) - { - parent::__construct($data); - - // 设置默认外键名 仅支持单一外键 - if (empty($this->fk)) { - $this->fk = strtolower($this->name) . '_id'; - } - } - - /** - * 查找单条记录 - * @access public - * @param mixed $data 主键值或者查询条件(闭包) - * @param string $with 关联预查询 - * @param bool $cache 是否缓存 - * @return \think\Model - */ - public static function get($data = null, $with = [], $cache = false) - { - $query = self::parseQuery($data, $with, $cache); - $query = self::attachQuery($query); - return $query->find($data); - } - - /** - * 附加查询表达式 - * @access protected - * @param \think\db\Query $query 查询对象 - * @return \think\db\Query - */ - protected static function attachQuery($query) - { - $class = new static(); - $master = $class->name; - $fields = self::getModelField($query, $master, '', $class->mapFields); - $query->alias($master)->field($fields); - - foreach ($class->relationModel as $key => $model) { - $name = is_int($key) ? $model : $key; - $table = is_int($key) ? $query->getTable($name) : $model; - $query->join($table . ' ' . $name, $name . '.' . $class->fk . '=' . $master . '.' . $class->getPk()); - $fields = self::getModelField($query, $name, $table, $class->mapFields); - $query->field($fields); - } - return $query; - } - - /** - * 获取关联模型的字段 并解决混淆 - * @access protected - * @param \think\db\Query $query 查询对象 - * @param string $name 模型名称 - * @param string $table 关联表名称 - * @param array $map 字段映射 - * @return array - */ - protected static function getModelField($query, $name, $table = '', $map = []) - { - // 获取模型的字段信息 - $fields = $query->getTableInfo($table, 'fields'); - $array = []; - foreach ($fields as $field) { - if ($key = array_search($name . '.' . $field, $map)) { - // 需要处理映射字段 - $array[] = $name . '.' . $field . ' AS ' . $key; - } else { - $array[] = $field; - } - } - return $array; - } - - /** - * 查找所有记录 - * @access public - * @param mixed $data 主键列表或者查询条件(闭包) - * @param string $with 关联预查询 - * @return array|false|string - */ - public static function all($data = null, $with = [], $cache = false) - { - $query = self::parseQuery($data, $with, $cache); - $query = self::attachQuery($query); - return $query->select($data); - } - - /** - * 处理写入的模型数据 - * @access public - * @param string $model 模型名称 - * @param array $data 数据 - * @param bool $insert 是否新增 - * @return void - */ - protected function parseData($model, $data, $insert = false) - { - $item = []; - foreach ($data as $key => $val) { - if ($insert || in_array($key, $this->change) || $this->isPk($key)) { - if ($this->fk != $key && array_key_exists($key, $this->mapFields)) { - list($name, $key) = explode('.', $this->mapFields[$key]); - if ($model == $name) { - $item[$key] = $val; - } - } else { - $item[$key] = $val; - } - } - } - return $item; - } - - /** - * 保存模型数据 以及关联数据 - * @access public - * @param mixed $data 数据 - * @param array $where 更新条件 - * @param string $sequence 自增序列名 - * @return integer|false - */ - public function save($data = [], $where = [], $sequence = null) - { - if (!empty($data)) { - // 数据自动验证 - if (!$this->validateData($data)) { - return false; - } - // 数据对象赋值 - foreach ($data as $key => $value) { - $this->setAttr($key, $value); - } - if (!empty($where)) { - $this->isUpdate = true; - } - } - - // 数据自动完成 - $this->autoCompleteData($this->auto); - - // 自动写入更新时间 - if ($this->autoWriteTimestamp && $this->updateTime) { - $this->setAttr($this->updateTime, null); - } - - $db = $this->db(); - $db->startTrans(); - try { - if ($this->isUpdate) { - // 自动写入 - $this->autoCompleteData($this->update); - - if (false === $this->trigger('before_update', $this)) { - return false; - } - - if (empty($where) && !empty($this->updateWhere)) { - $where = $this->updateWhere; - } - - if (!empty($where)) { - $pk = $this->getPk(); - - if (isset($this->mapFields[$pk])) { - $pk = $this->mapFields[$pk]; - } - if (isset($where[$pk])) { - unset($where[$pk]); - } - } - - // 处理模型数据 - $data = $this->parseData($this->name, $this->data); - // 写入主表数据 - $result = $db->strict(false)->where($where)->update($data); - - // 写入附表数据 - foreach ($this->relationModel as $key => $model) { - $name = is_int($key) ? $model : $key; - $table = is_int($key) ? $db->getTable($model) : $model; - // 处理关联模型数据 - $data = $this->parseData($name, $this->data); - $query = clone $db; - if ($query->table($table)->strict(false)->where($this->fk, $this->data[$this->getPk()])->update($data)) { - $result = 1; - } - } - // 清空change - $this->change = []; - // 新增回调 - $this->trigger('after_update', $this); - } else { - // 自动写入 - $this->autoCompleteData($this->insert); - - // 自动写入创建时间 - if ($this->autoWriteTimestamp && $this->createTime) { - $this->setAttr($this->createTime, null); - } - - if (false === $this->trigger('before_insert', $this)) { - return false; - } - - // 处理模型数据 - $data = $this->parseData($this->name, $this->data, true); - // 写入主表数据 - $result = $db->name($this->name)->strict(false)->insert($data); - if ($result) { - $insertId = $db->getLastInsID($sequence); - // 写入外键数据 - $pk = $this->getPk(); - if ($insertId) { - if (is_string($pk)) { - $this->data[$pk] = $insertId; - if ($this->fk == $pk) { - $this->change[] = $pk; - } - } - $this->data[$this->fk] = $insertId; - } - - // 写入附表数据 - $source = $this->data; - if ($insertId && is_string($pk) && isset($source[$pk]) && $this->fk != $pk) { - unset($source[$pk]); - } - foreach ($this->relationModel as $key => $model) { - $name = is_int($key) ? $model : $key; - $table = is_int($key) ? $db->getTable($model) : $model; - // 处理关联模型数据 - $data = $this->parseData($name, $source, true); - $query = clone $db; - $query->table($table)->strict(false)->insert($data); - } - } - // 标记为更新 - $this->isUpdate = true; - // 清空change - $this->change = []; - // 新增回调 - $this->trigger('after_insert', $this); - } - $db->commit(); - return $result; - } catch (\Exception $e) { - $db->rollback(); - throw $e; - } - } - - /** - * 删除当前的记录 并删除关联数据 - * @access public - * @return integer - */ - public function delete() - { - if (false === $this->trigger('before_delete', $this)) { - return false; - } - - $db = $this->db(); - $db->startTrans(); - try { - $result = $db->delete($this->data); - if ($result) { - // 获取主键数据 - $pk = $this->data[$this->getPk()]; - - // 删除关联数据 - foreach ($this->relationModel as $key => $model) { - $table = is_int($key) ? $db->getTable($model) : $model; - $query = clone $db; - $query->table($table)->where($this->fk, $pk)->delete(); - } - } - $this->trigger('after_delete', $this); - $db->commit(); - return $result; - } catch (\Exception $e) { - $db->rollback(); - throw $e; - } - } - -} diff --git a/library/think/model/Pivot.php b/library/think/model/Pivot.php index 24034b07c91c4376668e3a352eb71c17b83c1854..a3a395e3fb267ac6ec93232e15be670aa0076931 100644 --- a/library/think/model/Pivot.php +++ b/library/think/model/Pivot.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -16,21 +16,27 @@ use think\Model; class Pivot extends Model { + /** @var Model */ + public $parent; + + protected $autoWriteTimestamp = false; + /** * 架构函数 * @access public - * @param array|object $data 数据 - * @param string $table 中间数据表名 + * @param array|object $data 数据 + * @param Model $parent 上级模型 + * @param string $table 中间数据表名 */ - public function __construct($data = [], $table = '') + public function __construct($data = [], Model $parent = null, $table = '') { - if (is_object($data)) { - $this->data = get_object_vars($data); - } else { - $this->data = $data; + $this->parent = $parent; + + if (is_null($this->name)) { + $this->name = $table; } - $this->table = $table; + parent::__construct($data); } } diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index 22670bdd55ef9feb4cd9246b661626b1a9de6f0f..b969bca2aa1d8c2f01c76652ad53b725d5a50df0 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,691 +11,154 @@ namespace think\model; -use think\Db; +use think\db\Query; use think\Exception; -use think\Loader; use think\Model; -use think\model\Pivot; -class Relation +/** + * Class Relation + * @package think\model + * + * @mixin Query + */ +abstract class Relation { - const HAS_ONE = 1; - const HAS_MANY = 2; - const HAS_MANY_THROUGH = 5; - const BELONGS_TO = 3; - const BELONGS_TO_MANY = 4; - // 父模型对象 protected $parent; /** @var Model 当前关联的模型类 */ protected $model; - // 中间表模型 - protected $middle; - // 当前关联类型 - protected $type; + /** @var Query 关联模型查询对象 */ + protected $query; // 关联表外键 protected $foreignKey; - // 中间关联表外键 - protected $throughKey; // 关联表主键 protected $localKey; - // 数据表别名 - protected $alias; - // 当前关联的JOIN类型 - protected $joinType; - // 关联模型查询对象 - protected $query; - // 关联查询条件 - protected $where; - - /** - * 架构函数 - * @access public - * @param Model $model 上级模型对象 - */ - public function __construct(Model $model) - { - $this->parent = $model; - } - - /** - * 获取当前关联信息 - * @access public - * @param string $name 关联信息 - * @return array|string|integer - */ - public function getRelationInfo($name = '') - { - $info = [ - 'type' => $this->type, - 'model' => $this->model, - 'middle' => $this->middle, - 'foreignKey' => $this->foreignKey, - 'localKey' => $this->localKey, - 'alias' => $this->alias, - 'joinType' => $this->joinType, - ]; - return $name ? $info[$name] : $info; - } - - // 获取关联数据 - public function getRelation($name) - { - // 执行关联定义方法 - $relation = $this->parent->$name(); - $foreignKey = $this->foreignKey; - $localKey = $this->localKey; - - // 判断关联类型执行查询 - switch ($this->type) { - case self::HAS_ONE: - $result = $relation->where($foreignKey, $this->parent->$localKey)->find(); - break; - case self::BELONGS_TO: - $result = $relation->where($localKey, $this->parent->$foreignKey)->find(); - break; - case self::HAS_MANY: - $result = $relation->select(); - break; - case self::HAS_MANY_THROUGH: - $result = $relation->select(); - break; - case self::BELONGS_TO_MANY: - // 关联查询 - $pk = $this->parent->getPk(); - $condition['pivot.' . $localKey] = $this->parent->$pk; - $result = $this->belongsToManyQuery($relation, $this->middle, $foreignKey, $localKey, $condition)->select(); - foreach ($result as $set) { - $pivot = []; - foreach ($set->getData() as $key => $val) { - if (strpos($key, '__')) { - list($name, $attr) = explode('__', $key, 2); - if ('pivot' == $name) { - $pivot[$attr] = $val; - unset($set->$key); - } - } - } - $set->pivot = new Pivot($pivot, $this->middle); - } - break; - default: - // 直接返回 - $result = $relation; - } - return $result; - } + // 基础查询 + protected $baseQuery; + // 是否为自关联 + protected $selfRelation; /** - * 预载入关联查询 返回数据集 + * 获取关联的所属模型 * @access public - * @param array $resultSet 数据集 - * @param string $relation 关联名 - * @param string $class 数据集对象名 为空表示数组 - * @return array - */ - public function eagerlyResultSet($resultSet, $relation, $class = '') - { - /** @var array $relations */ - $relations = is_string($relation) ? explode(',', $relation) : $relation; - - foreach ($relations as $key => $relation) { - $subRelation = ''; - $closure = false; - if ($relation instanceof \Closure) { - $closure = $relation; - $relation = $key; - } - if (strpos($relation, '.')) { - list($relation, $subRelation) = explode('.', $relation); - } - // 执行关联方法 - $model = $this->parent->$relation(); - // 获取关联信息 - $localKey = $this->localKey; - $foreignKey = $this->foreignKey; - switch ($this->type) { - case self::HAS_ONE: - case self::BELONGS_TO: - foreach ($resultSet as $result) { - // 模型关联组装 - $this->match($this->model, $relation, $result); - } - break; - case self::HAS_MANY: - $range = []; - foreach ($resultSet as $result) { - // 获取关联外键列表 - if (isset($result->$localKey)) { - $range[] = $result->$localKey; - } - } - - if (!empty($range)) { - $this->where[$foreignKey] = ['in', $range]; - $data = $this->eagerlyOneToMany($model, [ - $foreignKey => [ - 'in', - $range, - ], - ], $relation, $subRelation, $closure); - - // 关联数据封装 - foreach ($resultSet as $result) { - if (!isset($data[$result->$localKey])) { - $data[$result->$localKey] = []; - } - $result->setAttr($relation, $this->resultSetBuild($data[$result->$localKey], $class)); - } - } - break; - case self::BELONGS_TO_MANY: - $pk = $resultSet[0]->getPk(); - $range = []; - foreach ($resultSet as $result) { - // 获取关联外键列表 - if (isset($result->$pk)) { - $range[] = $result->$pk; - } - } - - if (!empty($range)) { - // 查询关联数据 - $data = $this->eagerlyManyToMany($model, [ - 'pivot.' . $localKey => [ - 'in', - $range, - ], - ], $relation, $subRelation); - - // 关联数据封装 - foreach ($resultSet as $result) { - if (!isset($data[$result->$pk])) { - $data[$result->$pk] = []; - } - - $result->setAttr($relation, $this->resultSetBuild($data[$result->$pk], $class)); - } - } - break; - } - } - return $resultSet; - } - - /** - * 封装关联数据集 - * @access public - * @param array $resultSet 数据集 - * @param string $class 数据集类名 - * @return mixed - */ - protected function resultSetBuild($resultSet, $class = '') - { - return $class ? new $class($resultSet) : $resultSet; - } - - /** - * 预载入关联查询 返回模型对象 - * @access public - * @param Model $result 数据对象 - * @param string $relation 关联名 - * @param string $class 数据集对象名 为空表示数组 * @return Model */ - public function eagerlyResult($result, $relation, $class = '') - { - $relations = is_string($relation) ? explode(',', $relation) : $relation; - - foreach ($relations as $key => $relation) { - $subRelation = ''; - $closure = false; - if ($relation instanceof \Closure) { - $closure = $relation; - $relation = $key; - } - if (strpos($relation, '.')) { - list($relation, $subRelation) = explode('.', $relation); - } - // 执行关联方法 - $model = $this->parent->$relation(); - $localKey = $this->localKey; - $foreignKey = $this->foreignKey; - switch ($this->type) { - case self::HAS_ONE: - case self::BELONGS_TO: - // 模型关联组装 - $this->match($this->model, $relation, $result); - break; - case self::HAS_MANY: - if (isset($result->$localKey)) { - $data = $this->eagerlyOneToMany($model, [$foreignKey => $result->$localKey], $relation, $subRelation, $closure); - // 关联数据封装 - if (!isset($data[$result->$localKey])) { - $data[$result->$localKey] = []; - } - $result->setAttr($relation, $this->resultSetBuild($data[$result->$localKey], $class)); - } - break; - case self::BELONGS_TO_MANY: - $pk = $result->getPk(); - if (isset($result->$pk)) { - $pk = $result->$pk; - // 查询管理数据 - $data = $this->eagerlyManyToMany($model, ['pivot.' . $localKey => $pk], $relation, $subRelation); - - // 关联数据封装 - if (!isset($data[$pk])) { - $data[$pk] = []; - } - $result->setAttr($relation, $this->resultSetBuild($data[$pk], $class)); - } - break; - - } - } - return $result; - } - - /** - * 一对一 关联模型预查询拼装 - * @access public - * @param string $model 模型名称 - * @param string $relation 关联名 - * @param Model $result 模型对象实例 - * @return void - */ - protected function match($model, $relation, &$result) - { - // 重新组装模型数据 - foreach ($result->getData() as $key => $val) { - if (strpos($key, '__')) { - list($name, $attr) = explode('__', $key, 2); - if ($name == $relation) { - $list[$name][$attr] = $val; - unset($result->$key); - } - } - } - - $result->setAttr($relation, !isset($list[$relation]) ? null : (new $model($list[$relation]))->isUpdate(true)); - } - - /** - * 一对多 关联模型预查询 - * @access public - * @param object $model 关联模型对象 - * @param array $where 关联预查询条件 - * @param string $relation 关联名 - * @param string $subRelation 子关联 - * @param bool $closure - * @return array - */ - protected function eagerlyOneToMany($model, $where, $relation, $subRelation = '', $closure = false) + public function getParent() { - $foreignKey = $this->foreignKey; - // 预载入关联查询 支持嵌套预载入 - if ($closure) { - call_user_func_array($closure, [ & $model]); - } - $list = $model->where($where)->with($subRelation)->select(); - - // 组装模型数据 - $data = []; - foreach ($list as $set) { - $data[$set->$foreignKey][] = $set; - } - return $data; + return $this->parent; } /** - * 多对多 关联模型预查询 + * 获取当前的关联模型类的实例 * @access public - * @param object $model 关联模型对象 - * @param array $where 关联预查询条件 - * @param string $relation 关联名 - * @param string $subRelation 子关联 - * @return array + * @return Model */ - protected function eagerlyManyToMany($model, $where, $relation, $subRelation = '') + public function getModel() { - $foreignKey = $this->foreignKey; - $localKey = $this->localKey; - // 预载入关联查询 支持嵌套预载入 - $list = $this->belongsToManyQuery($model, $this->middle, $foreignKey, $localKey, $where)->with($subRelation)->select(); - - // 组装模型数据 - $data = []; - foreach ($list as $set) { - $pivot = []; - foreach ($set->getData() as $key => $val) { - if (strpos($key, '__')) { - list($name, $attr) = explode('__', $key, 2); - if ('pivot' == $name) { - $pivot[$attr] = $val; - unset($set->$key); - } - } - } - $set->pivot = new Pivot($pivot, $this->middle); - $data[$pivot[$localKey]][] = $set; - } - return $data; + return $this->query->getModel(); } /** - * 设置当前关联定义的数据表别名 + * 设置当前关联为自关联 * @access public - * @param array $alias 别名定义 + * @param bool $self 是否自关联 * @return $this */ - public function setAlias($alias) + public function selfRelation($self = true) { - $this->alias = $alias; + $this->selfRelation = $self; return $this; } /** - * HAS ONE 关联定义 + * 当前关联是否为自关联 * @access public - * @param string $model 模型名 - * @param string $foreignKey 关联外键 - * @param string $localKey 关联主键 - * @param array $alias 别名定义 - * @param string $joinType JOIN类型 - * @return $this + * @return bool */ - public function hasOne($model, $foreignKey, $localKey, $alias = [], $joinType = 'INNER') + public function isSelfRelation() { - $this->type = self::HAS_ONE; - $this->model = $model; - $this->foreignKey = $foreignKey; - $this->localKey = $localKey; - $this->alias = $alias; - $this->joinType = $joinType; - $this->query = (new $model)->db(); - // 返回关联的模型对象 - return $this; + return $this->selfRelation; } /** - * BELONGS TO 关联定义 + * 封装关联数据集 * @access public - * @param string $model 模型名 - * @param string $foreignKey 关联外键 - * @param string $otherKey 关联主键 - * @param array $alias 别名定义 - * @param string $joinType JOIN类型 - * @return $this + * @param array $resultSet 数据集 + * @return mixed */ - public function belongsTo($model, $foreignKey, $otherKey, $alias = [], $joinType = 'INNER') + protected function resultSetBuild($resultSet) { - // 记录当前关联信息 - $this->type = self::BELONGS_TO; - $this->model = $model; - $this->foreignKey = $foreignKey; - $this->localKey = $otherKey; - $this->alias = $alias; - $this->joinType = $joinType; - $this->query = (new $model)->db(); - // 返回关联的模型对象 - return $this; + return (new $this->model)->toCollection($resultSet); } - /** - * HAS MANY 关联定义 - * @access public - * @param string $model 模型名 - * @param string $foreignKey 关联外键 - * @param string $localKey 关联主键 - * @param array $alias 别名定义 - * @return $this - */ - public function hasMany($model, $foreignKey, $localKey, $alias) + protected function getQueryFields($model) { - // 记录当前关联信息 - $this->type = self::HAS_MANY; - $this->model = $model; - $this->foreignKey = $foreignKey; - $this->localKey = $localKey; - $this->alias = $alias; - $this->query = (new $model)->db(); - // 返回关联的模型对象 - return $this; + $fields = $this->query->getOptions('field'); + return $this->getRelationQueryFields($fields, $model); } - /** - * HAS MANY 远程关联定义 - * @access public - * @param string $model 模型名 - * @param string $through 中间模型名 - * @param string $firstkey 关联外键 - * @param string $secondKey 关联外键 - * @param string $localKey 关联主键 - * @param array $alias 别名定义 - * @return $this - */ - public function hasManyThrough($model, $through, $foreignKey, $throughKey, $localKey, $alias) + protected function getRelationQueryFields($fields, $model) { - // 记录当前关联信息 - $this->type = self::HAS_MANY_THROUGH; - $this->model = $model; - $this->middle = $through; - $this->foreignKey = $foreignKey; - $this->throughKey = $throughKey; - $this->localKey = $localKey; - $this->alias = $alias; - $this->query = (new $model)->db(); - // 返回关联的模型对象 - return $this; - } + if ($fields) { - /** - * BELONGS TO MANY 关联定义 - * @access public - * @param string $model 模型名 - * @param string $table 中间表名 - * @param string $foreignKey 关联模型外键 - * @param string $localKey 当前模型关联键 - * @param array $alias 别名定义 - * @return $this - */ - public function belongsToMany($model, $table, $foreignKey, $localKey, $alias) - { - // 记录当前关联信息 - $this->type = self::BELONGS_TO_MANY; - $this->model = $model; - $this->foreignKey = $foreignKey; - $this->localKey = $localKey; - $this->middle = $table; - $this->alias = $alias; - $this->query = (new $model)->db(); - // 返回关联的模型对象 - return $this; - } - - /** - * BELONGS TO MANY 关联查询 - * @access public - * @param object $model 关联模型对象 - * @param string $table 中间表名 - * @param string $foreignKey 关联模型关联键 - * @param string $localKey 当前模型关联键 - * @param array $condition 关联查询条件 - * @return \think\db\Query|string - */ - protected function belongsToManyQuery($model, $table, $foreignKey, $localKey, $condition = []) - { - // 关联查询封装 - $tableName = $model->getTable(); - $relationFk = $model->getPk(); - return $model::field($tableName . '.*') - ->field(true, false, $table, 'pivot', 'pivot__') - ->join($table . ' pivot', 'pivot.' . $foreignKey . '=' . $tableName . '.' . $relationFk) - ->where($condition); - } + if (is_string($fields)) { + $fields = explode(',', $fields); + } - /** - * 保存(新增)当前关联数据对象 - * @access public - * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键 - * @param array $pivot 中间表额外数据 - * @return integer - */ - public function save($data, array $pivot = []) - { - // 判断关联类型 - switch ($this->type) { - case self::HAS_ONE: - case self::BELONGS_TO: - case self::HAS_MANY: - if ($data instanceof Model) { - $data = $data->getData(); + foreach ($fields as &$field) { + if (false === strpos($field, '.')) { + $field = $model . '.' . $field; } - // 保存关联表数据 - $data[$this->foreignKey] = $this->parent->{$this->localKey}; - $model = new $this->model; - return $model->save($data); - case self::BELONGS_TO_MANY: - // 保存关联表/中间表数据 - return $this->attach($data, $pivot); + } + } else { + $fields = $model . '.*'; } + + return $fields; } - /** - * 批量保存当前关联数据对象 - * @access public - * @param array $dataSet 数据集 - * @param array $pivot 中间表额外数据 - * @return integer - */ - public function saveAll(array $dataSet, array $pivot = []) + protected function getQueryWhere(&$where, $relation) { - $result = false; - foreach ($dataSet as $key => $data) { - // 判断关联类型 - switch ($this->type) { - case self::HAS_MANY: - $data[$this->foreignKey] = $this->parent->{$this->localKey}; - $result = $this->save($data); - break; - case self::BELONGS_TO_MANY: - // TODO - $result = $this->attach($data, !empty($pivot) ? $pivot[$key] : []); - break; + foreach ($where as $key => $val) { + if (is_string($key)) { + $where[] = [false === strpos($key, '.') ? $relation . '.' . $key : $key, '=', $val]; + unset($where[$key]); } } - return $result; } /** - * 附加关联的一个中间表数据 + * 删除记录 * @access public - * @param mixed $data 数据 可以使用数组、关联模型对象 或者 关联对象的主键 - * @param array $pivot 中间表额外数据 - * @return integer + * @param mixed $data 表达式 true 表示强制删除 + * @return int + * @throws Exception + * @throws PDOException */ - public function attach($data, $pivot = []) + public function delete($data = null) { - if (is_array($data)) { - // 保存关联表数据 - $model = new $this->model; - $model->save($data); - $id = $model->getLastInsID(); - } elseif (is_numeric($data) || is_string($data)) { - // 根据关联表主键直接写入中间表 - $id = $data; - } elseif ($data instanceof Model) { - // 根据关联表主键直接写入中间表 - $relationFk = $data->getPk(); - $id = $data->$relationFk; - } - - if ($id) { - // 保存中间表数据 - $pk = $this->parent->getPk(); - $pivot[$this->localKey] = $this->parent->$pk; - $pivot[$this->foreignKey] = $id; - $query = clone $this->parent->db(); - return $query->table($this->middle)->insert($pivot); - } else { - throw new Exception('miss relation data'); - } + return $this->query->delete($data); } /** - * 解除关联的一个中间表数据 - * @access public - * @param integer|array $data 数据 可以使用关联对象的主键 - * @param bool $relationDel 是否同时删除关联表数据 - * @return integer + * 执行基础查询(仅执行一次) + * @access protected + * @return void */ - public function detach($data, $relationDel = false) - { - if (is_array($data)) { - $id = $data; - } elseif (is_numeric($data) || is_string($data)) { - // 根据关联表主键直接写入中间表 - $id = $data; - } elseif ($data instanceof Model) { - // 根据关联表主键直接写入中间表 - $relationFk = $data->getPk(); - $id = $data->$relationFk; - } - // 删除中间表数据 - $pk = $this->parent->getPk(); - $pivot[$this->localKey] = $this->parent->$pk; - if (isset($id)) { - $pivot[$this->foreignKey] = is_array($id) ? ['in', $id] : $id; - } - $query = clone $this->parent->db(); - $query->table($this->middle)->where($pivot)->delete(); - - // 删除关联表数据 - if (isset($id) && $relationDel) { - $model = $this->model; - $model::destroy($id); - } - } + protected function baseQuery() + {} public function __call($method, $args) { if ($this->query) { - switch ($this->type) { - case self::HAS_MANY: - if (isset($this->where)) { - $this->query->where($this->where); - } elseif (isset($this->parent->{$this->localKey})) { - // 关联查询带入关联条件 - $this->query->where($this->foreignKey, $this->parent->{$this->localKey}); - } - break; - case self::HAS_MANY_THROUGH: - $through = $this->middle; - $model = $this->model; - $alias = Loader::parseName(basename(str_replace('\\', '/', $model))); - $throughTable = $through::getTable(); - $pk = (new $this->model)->getPk(); - $throughKey = $this->throughKey; - $modelTable = $this->parent->getTable(); - $this->query->field($alias . '.*')->alias($alias) - ->join($throughTable, $throughTable . '.' . $pk . '=' . $alias . '.' . $throughKey) - ->join($modelTable, $modelTable . '.' . $this->localKey . '=' . $throughTable . '.' . $this->foreignKey) - ->where($throughTable . '.' . $this->foreignKey, $this->parent->{$this->localKey}); - break; - case self::BELONGS_TO_MANY: - // TODO + // 执行基础查询 + $this->baseQuery(); - } - $result = call_user_func_array([$this->query, $method], $args); - if ($result instanceof \think\db\Query) { - return $this; - } else { - return $result; - } + $result = call_user_func_array([$this->query->getModel(), $method], $args); + + return $result === $this->query ? $this : $result; } else { throw new Exception('method not exists:' . __CLASS__ . '->' . $method); } } - } diff --git a/library/think/model/concern/Attribute.php b/library/think/model/concern/Attribute.php new file mode 100644 index 0000000000000000000000000000000000000000..c65c557bb6b21c17bb0e1412744c46c208f7437b --- /dev/null +++ b/library/think/model/concern/Attribute.php @@ -0,0 +1,586 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\concern; + +use InvalidArgumentException; +use think\Exception; +use think\Loader; +use think\model\Relation; + +trait Attribute +{ + /** + * 数据表主键 复合主键使用数组定义 + * @var string|array + */ + protected $pk = 'id'; + + /** + * 数据表字段信息 留空则自动获取 + * @var array + */ + protected $field = []; + + /** + * JSON数据表字段 + * @var array + */ + protected $json = []; + + /** + * JSON数据取出是否需要转换为数组 + * @var bool + */ + protected $jsonAssoc = false; + + /** + * JSON数据表字段类型 + * @var array + */ + protected $jsonType = []; + + /** + * 数据表废弃字段 + * @var array + */ + protected $disuse = []; + + /** + * 数据表只读字段 + * @var array + */ + protected $readonly = []; + + /** + * 数据表字段类型 + * @var array + */ + protected $type = []; + + /** + * 当前模型数据 + * @var array + */ + private $data = []; + + /** + * 原始数据 + * @var array + */ + private $origin = []; + + /** + * 获取模型对象的主键 + * @access public + * @return string|array + */ + public function getPk() + { + return $this->pk; + } + + /** + * 判断一个字段名是否为主键字段 + * @access public + * @param string $key 名称 + * @return bool + */ + protected function isPk($key) + { + $pk = $this->getPk(); + if (is_string($pk) && $pk == $key) { + return true; + } elseif (is_array($pk) && in_array($key, $pk)) { + return true; + } + + return false; + } + + /** + * 设置允许写入的字段 + * @access public + * @param array|string|true $field 允许写入的字段 如果为true只允许写入数据表字段 + * @return $this + */ + public function allowField($field) + { + if (is_string($field)) { + $field = explode(',', $field); + } + + $this->field = $field; + + return $this; + } + + /** + * 设置只读字段 + * @access public + * @param array|string $field 只读字段 + * @return $this + */ + public function readonly($field) + { + if (is_string($field)) { + $field = explode(',', $field); + } + + $this->readonly = $field; + + return $this; + } + + /** + * 设置数据对象值 + * @access public + * @param mixed $data 数据或者属性名 + * @param mixed $value 值 + * @return $this + */ + public function data($data, $value = null) + { + if (is_string($data)) { + $this->data[$data] = $value; + return $this; + } + + // 清空数据 + $this->data = []; + + if (is_object($data)) { + $data = get_object_vars($data); + } + + if ($this->disuse) { + // 废弃字段 + foreach ((array) $this->disuse as $key) { + if (array_key_exists($key, $data)) { + unset($data[$key]); + } + } + } + + if (true === $value) { + // 数据对象赋值 + foreach ($data as $key => $value) { + $this->setAttr($key, $value, $data); + } + } elseif (is_array($value)) { + foreach ($value as $name) { + if (isset($data[$name])) { + $this->data[$name] = $data[$name]; + } + } + } else { + $this->data = $data; + } + + return $this; + } + + /** + * 批量设置数据对象值 + * @access public + * @param mixed $data 数据 + * @param bool $set 是否需要进行数据处理 + * @return $this + */ + public function appendData($data, $set = false) + { + if ($set) { + // 进行数据处理 + foreach ($data as $key => $value) { + $this->setAttr($key, $value, $data); + } + } else { + if (is_object($data)) { + $data = get_object_vars($data); + } + + $this->data = array_merge($this->data, $data); + } + + return $this; + } + + /** + * 获取对象原始数据 如果不存在指定字段返回null + * @access public + * @param string $name 字段名 留空获取全部 + * @return mixed + */ + public function getOrigin($name = null) + { + if (is_null($name)) { + return $this->origin; + } + return array_key_exists($name, $this->origin) ? $this->origin[$name] : null; + } + + /** + * 获取对象原始数据 如果不存在指定字段返回false + * @access public + * @param string $name 字段名 留空获取全部 + * @return mixed + * @throws InvalidArgumentException + */ + public function getData($name = null) + { + if (is_null($name)) { + return $this->data; + } elseif (array_key_exists($name, $this->data)) { + return $this->data[$name]; + } elseif (array_key_exists($name, $this->relation)) { + return $this->relation[$name]; + } + throw new InvalidArgumentException('property not exists:' . static::class . '->' . $name); + } + + /** + * 获取变化的数据 并排除只读数据 + * @access public + * @return array + */ + public function getChangedData() + { + if ($this->force) { + $data = $this->data; + } else { + $data = array_udiff_assoc($this->data, $this->origin, function ($a, $b) { + if ((empty($a) || empty($b)) && $a !== $b) { + return 1; + } + + return is_object($a) || $a != $b ? 1 : 0; + }); + } + + if (!empty($this->readonly)) { + // 只读字段不允许更新 + foreach ($this->readonly as $key => $field) { + if (isset($data[$field])) { + unset($data[$field]); + } + } + } + + return $data; + } + + /** + * 修改器 设置数据对象值 + * @access public + * @param string $name 属性名 + * @param mixed $value 属性值 + * @param array $data 数据 + * @return $this + */ + public function setAttr($name, $value, $data = []) + { + if (is_null($value) && $this->autoWriteTimestamp && in_array($name, [$this->createTime, $this->updateTime])) { + // 自动写入的时间戳字段 + $value = $this->autoWriteTimestamp($name); + } else { + // 检测修改器 + $method = 'set' . Loader::parseName($name, 1) . 'Attr'; + + if (method_exists($this, $method)) { + $value = $this->$method($value, array_merge($this->data, $data)); + } elseif (isset($this->type[$name])) { + // 类型转换 + $value = $this->writeTransform($value, $this->type[$name]); + } + } + + // 设置数据对象属性 + $this->data[$name] = $value; + + return $this; + } + + /** + * 是否需要自动写入时间字段 + * @access public + * @param bool $auto + * @return $this + */ + public function isAutoWriteTimestamp($auto) + { + $this->autoWriteTimestamp = $auto; + + return $this; + } + + /** + * 自动写入时间戳 + * @access protected + * @param string $name 时间戳字段 + * @return mixed + */ + protected function autoWriteTimestamp($name) + { + if (isset($this->type[$name])) { + $type = $this->type[$name]; + + if (strpos($type, ':')) { + list($type, $param) = explode(':', $type, 2); + } + + switch ($type) { + case 'datetime': + case 'date': + $format = !empty($param) ? $param : $this->dateFormat; + $value = $this->formatDateTime(time(), $format); + break; + case 'timestamp': + case 'integer': + default: + $value = time(); + break; + } + } elseif (is_string($this->autoWriteTimestamp) && in_array(strtolower($this->autoWriteTimestamp), [ + 'datetime', + 'date', + 'timestamp', + ])) { + $value = $this->formatDateTime(time(), $this->dateFormat); + } else { + $value = $this->formatDateTime(time(), $this->dateFormat, true); + } + + return $value; + } + + /** + * 数据写入 类型转换 + * @access protected + * @param mixed $value 值 + * @param string|array $type 要转换的类型 + * @return mixed + */ + protected function writeTransform($value, $type) + { + if (is_null($value)) { + return; + } + + if (is_array($type)) { + list($type, $param) = $type; + } elseif (strpos($type, ':')) { + list($type, $param) = explode(':', $type, 2); + } + + switch ($type) { + case 'integer': + $value = (int) $value; + break; + case 'float': + if (empty($param)) { + $value = (float) $value; + } else { + $value = (float) number_format($value, $param, '.', ''); + } + break; + case 'boolean': + $value = (bool) $value; + break; + case 'timestamp': + if (!is_numeric($value)) { + $value = strtotime($value); + } + break; + case 'datetime': + $format = !empty($param) ? $param : $this->dateFormat; + $value = is_numeric($value) ? $value : strtotime($value); + $value = $this->formatDateTime($value, $format); + break; + case 'object': + if (is_object($value)) { + $value = json_encode($value, JSON_FORCE_OBJECT); + } + break; + case 'array': + $value = (array) $value; + case 'json': + $option = !empty($param) ? (int) $param : JSON_UNESCAPED_UNICODE; + $value = json_encode($value, $option); + break; + case 'serialize': + $value = serialize($value); + break; + } + + return $value; + } + + /** + * 获取器 获取数据对象的值 + * @access public + * @param string $name 名称 + * @param array $item 数据 + * @return mixed + * @throws InvalidArgumentException + */ + public function getAttr($name, &$item = null) + { + try { + $notFound = false; + $value = $this->getData($name); + } catch (InvalidArgumentException $e) { + $notFound = true; + $value = null; + } + + // 检测属性获取器 + $method = 'get' . Loader::parseName($name, 1) . 'Attr'; + + if (method_exists($this, $method)) { + if ($notFound && $relation = $this->isRelationAttr($name)) { + $modelRelation = $this->$relation(); + $value = $this->getRelationData($modelRelation); + } + + $value = $this->$method($value, $this->data); + } elseif (isset($this->type[$name])) { + // 类型转换 + $value = $this->readTransform($value, $this->type[$name]); + } elseif ($this->autoWriteTimestamp && in_array($name, [$this->createTime, $this->updateTime])) { + if (is_string($this->autoWriteTimestamp) && in_array(strtolower($this->autoWriteTimestamp), [ + 'datetime', + 'date', + 'timestamp', + ])) { + $value = $this->formatDateTime(strtotime($value), $this->dateFormat); + } else { + $value = $this->formatDateTime($value, $this->dateFormat); + } + } elseif ($notFound) { + $value = $this->getRelationAttribute($name, $item); + } + + return $value; + } + + /** + * 获取关联属性值 + * @access protected + * @param string $name 属性名 + * @param array $item 数据 + * @return mixed + */ + protected function getRelationAttribute($name, &$item) + { + $relation = $this->isRelationAttr($name); + + if ($relation) { + $modelRelation = $this->$relation(); + if ($modelRelation instanceof Relation) { + $value = $this->getRelationData($modelRelation); + + if ($item && method_exists($modelRelation, 'getBindAttr') && $bindAttr = $modelRelation->getBindAttr()) { + + foreach ($bindAttr as $key => $attr) { + $key = is_numeric($key) ? $attr : $key; + + if (isset($item[$key])) { + throw new Exception('bind attr has exists:' . $key); + } else { + $item[$key] = $value ? $value->getAttr($attr) : null; + } + } + + return false; + } + + // 保存关联对象值 + $this->relation[$name] = $value; + + return $value; + } + } + + throw new InvalidArgumentException('property not exists:' . static::class . '->' . $name); + } + + /** + * 数据读取 类型转换 + * @access protected + * @param mixed $value 值 + * @param string|array $type 要转换的类型 + * @return mixed + */ + protected function readTransform($value, $type) + { + if (is_null($value)) { + return; + } + + if (is_array($type)) { + list($type, $param) = $type; + } elseif (strpos($type, ':')) { + list($type, $param) = explode(':', $type, 2); + } + + switch ($type) { + case 'integer': + $value = (int) $value; + break; + case 'float': + if (empty($param)) { + $value = (float) $value; + } else { + $value = (float) number_format($value, $param, '.', ''); + } + break; + case 'boolean': + $value = (bool) $value; + break; + case 'timestamp': + if (!is_null($value)) { + $format = !empty($param) ? $param : $this->dateFormat; + $value = $this->formatDateTime($value, $format); + } + break; + case 'datetime': + if (!is_null($value)) { + $format = !empty($param) ? $param : $this->dateFormat; + $value = $this->formatDateTime(strtotime($value), $format); + } + break; + case 'json': + $value = json_decode($value, true); + break; + case 'array': + $value = empty($value) ? [] : json_decode($value, true); + break; + case 'object': + $value = empty($value) ? new \stdClass() : json_decode($value); + break; + case 'serialize': + try { + $value = unserialize($value); + } catch (\Exception $e) { + $value = null; + } + break; + default: + if (false !== strpos($type, '\\')) { + // 对象类型 + $value = new $type($value); + } + } + + return $value; + } + +} diff --git a/library/think/model/concern/Conversion.php b/library/think/model/concern/Conversion.php new file mode 100644 index 0000000000000000000000000000000000000000..7494f76a000c99ff139db8e6ba8aa024f10705c5 --- /dev/null +++ b/library/think/model/concern/Conversion.php @@ -0,0 +1,276 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\concern; + +use think\Collection; +use think\Exception; +use think\Loader; +use think\Model; +use think\model\Collection as ModelCollection; + +/** + * 模型数据转换处理 + */ +trait Conversion +{ + /** + * 数据输出显示的属性 + * @var array + */ + protected $visible = []; + + /** + * 数据输出隐藏的属性 + * @var array + */ + protected $hidden = []; + + /** + * 数据输出需要追加的属性 + * @var array + */ + protected $append = []; + + /** + * 数据集对象名 + * @var string + */ + protected $resultSetType; + + /** + * 设置需要附加的输出属性 + * @access public + * @param array $append 属性列表 + * @param bool $override 是否覆盖 + * @return $this + */ + public function append(array $append = [], $override = false) + { + $this->append = $override ? $append : array_merge($this->append, $append); + + return $this; + } + + /** + * 设置附加关联对象的属性 + * @access public + * @param string $attr 关联属性 + * @param string|array $append 追加属性名 + * @return $this + * @throws Exception + */ + public function appendRelationAttr($attr, $append) + { + if (is_string($append)) { + $append = explode(',', $append); + } + + $relation = Loader::parseName($attr, 1, false); + if (isset($this->relation[$relation])) { + $model = $this->relation[$relation]; + } else { + $model = $this->getRelationData($this->$relation()); + } + + if ($model instanceof Model) { + foreach ($append as $key => $attr) { + $key = is_numeric($key) ? $attr : $key; + if (isset($this->data[$key])) { + throw new Exception('bind attr has exists:' . $key); + } else { + $this->data[$key] = $model->$attr; + } + } + } + + return $this; + } + + /** + * 设置需要隐藏的输出属性 + * @access public + * @param array $hidden 属性列表 + * @param bool $override 是否覆盖 + * @return $this + */ + public function hidden(array $hidden = [], $override = false) + { + $this->hidden = $override ? $hidden : array_merge($this->hidden, $hidden); + + return $this; + } + + /** + * 设置需要输出的属性 + * @access public + * @param array $visible + * @param bool $override 是否覆盖 + * @return $this + */ + public function visible(array $visible = [], $override = false) + { + $this->visible = $override ? $visible : array_merge($this->visible, $visible); + + return $this; + } + + /** + * 转换当前模型对象为数组 + * @access public + * @return array + */ + public function toArray() + { + $item = []; + $visible = []; + $hidden = []; + + // 合并关联数据 + $data = array_merge($this->data, $this->relation); + + // 过滤属性 + if (!empty($this->visible)) { + $array = $this->parseAttr($this->visible, $visible); + $data = array_intersect_key($data, array_flip($array)); + } elseif (!empty($this->hidden)) { + $array = $this->parseAttr($this->hidden, $hidden, false); + $data = array_diff_key($data, array_flip($array)); + } + + foreach ($data as $key => $val) { + if ($val instanceof Model || $val instanceof ModelCollection) { + // 关联模型对象 + if (isset($visible[$key])) { + $val->visible($visible[$key]); + } elseif (isset($hidden[$key])) { + $val->hidden($hidden[$key]); + } + // 关联模型对象 + $item[$key] = $val->toArray(); + } else { + // 模型属性 + $item[$key] = $this->getAttr($key); + } + } + + // 追加属性(必须定义获取器) + if (!empty($this->append)) { + foreach ($this->append as $key => $name) { + if (is_array($name)) { + // 追加关联对象属性 + $relation = $this->getAttr($key); + $item[$key] = $relation->visible($name)->append($name)->toArray(); + } elseif (strpos($name, '.')) { + list($key, $attr) = explode('.', $name); + // 追加关联对象属性 + $relation = $this->getAttr($key); + $item[$key] = $relation->visible([$attr])->append([$attr])->toArray(); + } else { + $value = $this->getAttr($name, $item); + if (false !== $value) { + $item[$name] = $value; + } + } + } + } + + return $item; + } + + /** + * 转换当前模型对象为JSON字符串 + * @access public + * @param integer $options json参数 + * @return string + */ + public function toJson($options = JSON_UNESCAPED_UNICODE) + { + return json_encode($this->toArray(), $options); + } + + /** + * 移除当前模型的关联属性 + * @access public + * @return $this + */ + public function removeRelation() + { + $this->relation = []; + return $this; + } + + public function __toString() + { + return $this->toJson(); + } + + // JsonSerializable + public function jsonSerialize() + { + return $this->toArray(); + } + + /** + * 转换数据集为数据集对象 + * @access public + * @param array|Collection $collection 数据集 + * @param string $resultSetType 数据集类 + * @return Collection + */ + public function toCollection($collection, $resultSetType = null) + { + $resultSetType = $resultSetType ?: $this->resultSetType; + + if ($resultSetType && false !== strpos($resultSetType, '\\')) { + $collection = new $resultSetType($collection); + } else { + $collection = new ModelCollection($collection); + } + + return $collection; + } + + /** + * 解析隐藏及显示属性 + * @access protected + * @param array $attrs 属性 + * @param array $result 结果集 + * @param bool $visible + * @return array + */ + protected function parseAttr($attrs, &$result, $visible = true) + { + $array = []; + + foreach ($attrs as $key => $val) { + if (is_array($val)) { + if ($visible) { + $array[] = $key; + } + + $result[$key] = $val; + } elseif (strpos($val, '.')) { + list($key, $name) = explode('.', $val); + + if ($visible) { + $array[] = $key; + } + + $result[$key][] = $name; + } else { + $array[] = $val; + } + } + + return $array; + } +} diff --git a/library/think/model/concern/ModelEvent.php b/library/think/model/concern/ModelEvent.php new file mode 100644 index 0000000000000000000000000000000000000000..2bb6d5fe0619ac18136fb7c7c8d5d8f60fb21386 --- /dev/null +++ b/library/think/model/concern/ModelEvent.php @@ -0,0 +1,236 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\concern; + +use think\Container; +use think\Loader; + +/** + * 模型事件处理 + */ +trait ModelEvent +{ + /** + * 模型回调 + * @var array + */ + private static $event = []; + + /** + * 模型事件观察 + * @var array + */ + protected static $observe = ['before_write', 'after_write', 'before_insert', 'after_insert', 'before_update', 'after_update', 'before_delete', 'after_delete', 'before_restore', 'after_restore']; + + /** + * 绑定模型事件观察者类 + * @var array + */ + protected $observerClass; + + /** + * 是否需要事件响应 + * @var bool + */ + private $withEvent = true; + + /** + * 注册回调方法 + * @access public + * @param string $event 事件名 + * @param callable $callback 回调方法 + * @param bool $override 是否覆盖 + * @return void + */ + public static function event($event, $callback, $override = false) + { + $class = static::class; + + if ($override) { + self::$event[$class][$event] = []; + } + + self::$event[$class][$event][] = $callback; + } + + /** + * 清除回调方法 + * @access public + * @return void + */ + public static function flushEvent() + { + self::$event[static::class] = []; + } + + /** + * 注册一个模型观察者 + * + * @param object|string $class + * @return void + */ + public static function observe($class) + { + foreach (static::$observe as $event) { + $eventFuncName = Loader::parseName($event, 1, false); + + if (method_exists($class, $eventFuncName)) { + static::event($event, [$class, $eventFuncName]); + } + } + } + + /** + * 当前操作的事件响应 + * @access protected + * @param bool $event 是否需要事件响应 + * @return $this + */ + public function withEvent($event) + { + $this->withEvent = $event; + return $this; + } + + /** + * 触发事件 + * @access protected + * @param string $event 事件名 + * @return bool + */ + protected function trigger($event) + { + $class = static::class; + + if ($this->withEvent && isset(self::$event[$class][$event])) { + foreach (self::$event[$class][$event] as $callback) { + $result = Container::getInstance()->invoke($callback, [$this]); + + if (false === $result) { + return false; + } + } + } + + return true; + } + + /** + * 模型before_insert事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function beforeInsert($callback, $override = false) + { + self::event('before_insert', $callback, $override); + } + + /** + * 模型after_insert事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function afterInsert($callback, $override = false) + { + self::event('after_insert', $callback, $override); + } + + /** + * 模型before_update事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function beforeUpdate($callback, $override = false) + { + self::event('before_update', $callback, $override); + } + + /** + * 模型after_update事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function afterUpdate($callback, $override = false) + { + self::event('after_update', $callback, $override); + } + + /** + * 模型before_write事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function beforeWrite($callback, $override = false) + { + self::event('before_write', $callback, $override); + } + + /** + * 模型after_write事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function afterWrite($callback, $override = false) + { + self::event('after_write', $callback, $override); + } + + /** + * 模型before_delete事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function beforeDelete($callback, $override = false) + { + self::event('before_delete', $callback, $override); + } + + /** + * 模型after_delete事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function afterDelete($callback, $override = false) + { + self::event('after_delete', $callback, $override); + } + + /** + * 模型before_restore事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function beforeRestore($callback, $override = false) + { + self::event('before_restore', $callback, $override); + } + + /** + * 模型after_restore事件快捷方法 + * @access protected + * @param callable $callback + * @param bool $override + */ + protected static function afterRestore($callback, $override = false) + { + self::event('after_restore', $callback, $override); + } +} diff --git a/library/think/model/concern/RelationShip.php b/library/think/model/concern/RelationShip.php new file mode 100644 index 0000000000000000000000000000000000000000..2c993bd2013411b5089f1700c779bf1a7e275641 --- /dev/null +++ b/library/think/model/concern/RelationShip.php @@ -0,0 +1,643 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\concern; + +use think\Collection; +use think\db\Query; +use think\Loader; +use think\Model; +use think\model\Relation; +use think\model\relation\BelongsTo; +use think\model\relation\BelongsToMany; +use think\model\relation\HasMany; +use think\model\relation\HasManyThrough; +use think\model\relation\HasOne; +use think\model\relation\MorphMany; +use think\model\relation\MorphOne; +use think\model\relation\MorphTo; + +/** + * 模型关联处理 + */ +trait RelationShip +{ + /** + * 父关联模型对象 + * @var object + */ + private $parent; + + /** + * 模型关联数据 + * @var array + */ + private $relation = []; + + /** + * 关联写入定义信息 + * @var array + */ + private $together; + + /** + * 关联自动写入信息 + * @var array + */ + protected $relationWrite; + + /** + * 设置父关联对象 + * @access public + * @param Model $model 模型对象 + * @return $this + */ + public function setParent($model) + { + $this->parent = $model; + + return $this; + } + + /** + * 获取父关联对象 + * @access public + * @return Model + */ + public function getParent() + { + return $this->parent; + } + + /** + * 获取当前模型的关联模型数据 + * @access public + * @param string $name 关联方法名 + * @return mixed + */ + public function getRelation($name = null) + { + if (is_null($name)) { + return $this->relation; + } elseif (array_key_exists($name, $this->relation)) { + return $this->relation[$name]; + } + return; + } + + /** + * 设置关联数据对象值 + * @access public + * @param string $name 属性名 + * @param mixed $value 属性值 + * @param array $data 数据 + * @return $this + */ + public function setRelation($name, $value, $data = []) + { + // 检测修改器 + $method = 'set' . Loader::parseName($name, 1) . 'Attr'; + + if (method_exists($this, $method)) { + $value = $this->$method($value, array_merge($this->data, $data)); + } + + $this->relation[$name] = $value; + + return $this; + } + + /** + * 关联数据写入 + * @access public + * @param array|string $relation 关联 + * @return $this + */ + public function together($relation) + { + if (is_string($relation)) { + $relation = explode(',', $relation); + } + + $this->together = $relation; + + $this->checkAutoRelationWrite(); + + return $this; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $relation 关联方法名 + * @param mixed $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @param string $joinType JOIN类型 + * @return Query + */ + public static function has($relation, $operator = '>=', $count = 1, $id = '*', $joinType = 'INNER') + { + $relation = (new static())->$relation(); + + if (is_array($operator) || $operator instanceof \Closure) { + return $relation->hasWhere($operator); + } + + return $relation->has($operator, $count, $id, $joinType); + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $relation 关联方法名 + * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $fields 字段 + * @return Query + */ + public static function hasWhere($relation, $where = [], $fields = '*') + { + return (new static())->$relation()->hasWhere($where, $fields); + } + + /** + * 查询当前模型的关联数据 + * @access public + * @param string|array $relations 关联名 + * @return $this + */ + public function relationQuery($relations) + { + if (is_string($relations)) { + $relations = explode(',', $relations); + } + + foreach ($relations as $key => $relation) { + $subRelation = ''; + $closure = null; + + if ($relation instanceof \Closure) { + // 支持闭包查询过滤关联条件 + $closure = $relation; + $relation = $key; + } + + if (is_array($relation)) { + $subRelation = $relation; + $relation = $key; + } elseif (strpos($relation, '.')) { + list($relation, $subRelation) = explode('.', $relation, 2); + } + + $method = Loader::parseName($relation, 1, false); + + $this->relation[$relation] = $this->$method()->getRelation($subRelation, $closure); + } + + return $this; + } + + /** + * 预载入关联查询 返回数据集 + * @access public + * @param array $resultSet 数据集 + * @param string $relation 关联名 + * @return array + */ + public function eagerlyResultSet(&$resultSet, $relation) + { + $relations = is_string($relation) ? explode(',', $relation) : $relation; + + foreach ($relations as $key => $relation) { + $subRelation = ''; + $closure = false; + + if ($relation instanceof \Closure) { + $closure = $relation; + $relation = $key; + } + + if (is_array($relation)) { + $subRelation = $relation; + $relation = $key; + } elseif (strpos($relation, '.')) { + list($relation, $subRelation) = explode('.', $relation, 2); + } + + $relation = Loader::parseName($relation, 1, false); + + $this->$relation()->eagerlyResultSet($resultSet, $relation, $subRelation, $closure); + } + } + + /** + * 预载入关联查询 返回模型对象 + * @access public + * @param Model $result 数据对象 + * @param string $relation 关联名 + * @return Model + */ + public function eagerlyResult(&$result, $relation) + { + $relations = is_string($relation) ? explode(',', $relation) : $relation; + + foreach ($relations as $key => $relation) { + $subRelation = ''; + $closure = false; + + if ($relation instanceof \Closure) { + $closure = $relation; + $relation = $key; + } + + if (is_array($relation)) { + $subRelation = $relation; + $relation = $key; + } elseif (strpos($relation, '.')) { + list($relation, $subRelation) = explode('.', $relation, 2); + } + + $relation = Loader::parseName($relation, 1, false); + + $this->$relation()->eagerlyResult($result, $relation, $subRelation, $closure); + } + } + + /** + * 关联统计 + * @access public + * @param Model $result 数据对象 + * @param array $relations 关联名 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return void + */ + public function relationCount(&$result, $relations, $aggregate = 'sum', $field = '*') + { + foreach ($relations as $key => $relation) { + $closure = false; + + if ($relation instanceof \Closure) { + $closure = $relation; + $relation = $key; + } elseif (is_string($key)) { + $name = $relation; + $relation = $key; + } + + $relation = Loader::parseName($relation, 1, false); + $count = $this->$relation()->relationCount($result, $closure, $aggregate, $field); + + if (!isset($name)) { + $name = Loader::parseName($relation) . '_' . $aggregate; + } + + $result->setAttr($name, $count); + } + } + + /** + * HAS ONE 关联定义 + * @access public + * @param string $model 模型名 + * @param string $foreignKey 关联外键 + * @param string $localKey 当前主键 + * @return HasOne + */ + public function hasOne($model, $foreignKey = '', $localKey = '') + { + // 记录当前关联信息 + $model = $this->parseModel($model); + $localKey = $localKey ?: $this->getPk(); + $foreignKey = $foreignKey ?: $this->getForeignKey($this->name); + + return new HasOne($this, $model, $foreignKey, $localKey); + } + + /** + * BELONGS TO 关联定义 + * @access public + * @param string $model 模型名 + * @param string $foreignKey 关联外键 + * @param string $localKey 关联主键 + * @return BelongsTo + */ + public function belongsTo($model, $foreignKey = '', $localKey = '') + { + // 记录当前关联信息 + $model = $this->parseModel($model); + $foreignKey = $foreignKey ?: $this->getForeignKey((new $model)->getName()); + $localKey = $localKey ?: (new $model)->getPk(); + $trace = debug_backtrace(false, 2); + $relation = Loader::parseName($trace[1]['function']); + + return new BelongsTo($this, $model, $foreignKey, $localKey, $relation); + } + + /** + * HAS MANY 关联定义 + * @access public + * @param string $model 模型名 + * @param string $foreignKey 关联外键 + * @param string $localKey 当前主键 + * @return HasMany + */ + public function hasMany($model, $foreignKey = '', $localKey = '') + { + // 记录当前关联信息 + $model = $this->parseModel($model); + $localKey = $localKey ?: $this->getPk(); + $foreignKey = $foreignKey ?: $this->getForeignKey($this->name); + + return new HasMany($this, $model, $foreignKey, $localKey); + } + + /** + * HAS MANY 远程关联定义 + * @access public + * @param string $model 模型名 + * @param string $through 中间模型名 + * @param string $foreignKey 关联外键 + * @param string $throughKey 关联外键 + * @param string $localKey 当前主键 + * @return HasManyThrough + */ + public function hasManyThrough($model, $through, $foreignKey = '', $throughKey = '', $localKey = '') + { + // 记录当前关联信息 + $model = $this->parseModel($model); + $through = $this->parseModel($through); + $localKey = $localKey ?: $this->getPk(); + $foreignKey = $foreignKey ?: $this->getForeignKey($this->name); + $throughKey = $throughKey ?: $this->getForeignKey((new $through)->getName()); + + return new HasManyThrough($this, $model, $through, $foreignKey, $throughKey, $localKey); + } + + /** + * BELONGS TO MANY 关联定义 + * @access public + * @param string $model 模型名 + * @param string $table 中间表名 + * @param string $foreignKey 关联外键 + * @param string $localKey 当前模型关联键 + * @return BelongsToMany + */ + public function belongsToMany($model, $table = '', $foreignKey = '', $localKey = '') + { + // 记录当前关联信息 + $model = $this->parseModel($model); + $name = Loader::parseName(basename(str_replace('\\', '/', $model))); + $table = $table ?: Loader::parseName($this->name) . '_' . $name; + $foreignKey = $foreignKey ?: $name . '_id'; + $localKey = $localKey ?: $this->getForeignKey($this->name); + + return new BelongsToMany($this, $model, $table, $foreignKey, $localKey); + } + + /** + * MORPH One 关联定义 + * @access public + * @param string $model 模型名 + * @param string|array $morph 多态字段信息 + * @param string $type 多态类型 + * @return MorphOne + */ + public function morphOne($model, $morph = null, $type = '') + { + // 记录当前关联信息 + $model = $this->parseModel($model); + + if (is_null($morph)) { + $trace = debug_backtrace(false, 2); + $morph = Loader::parseName($trace[1]['function']); + } + + if (is_array($morph)) { + list($morphType, $foreignKey) = $morph; + } else { + $morphType = $morph . '_type'; + $foreignKey = $morph . '_id'; + } + + $type = $type ?: get_class($this); + + return new MorphOne($this, $model, $foreignKey, $morphType, $type); + } + + /** + * MORPH MANY 关联定义 + * @access public + * @param string $model 模型名 + * @param string|array $morph 多态字段信息 + * @param string $type 多态类型 + * @return MorphMany + */ + public function morphMany($model, $morph = null, $type = '') + { + // 记录当前关联信息 + $model = $this->parseModel($model); + + if (is_null($morph)) { + $trace = debug_backtrace(false, 2); + $morph = Loader::parseName($trace[1]['function']); + } + + $type = $type ?: get_class($this); + + if (is_array($morph)) { + list($morphType, $foreignKey) = $morph; + } else { + $morphType = $morph . '_type'; + $foreignKey = $morph . '_id'; + } + + return new MorphMany($this, $model, $foreignKey, $morphType, $type); + } + + /** + * MORPH TO 关联定义 + * @access public + * @param string|array $morph 多态字段信息 + * @param array $alias 多态别名定义 + * @return MorphTo + */ + public function morphTo($morph = null, $alias = []) + { + $trace = debug_backtrace(false, 2); + $relation = Loader::parseName($trace[1]['function']); + + if (is_null($morph)) { + $morph = $relation; + } + + // 记录当前关联信息 + if (is_array($morph)) { + list($morphType, $foreignKey) = $morph; + } else { + $morphType = $morph . '_type'; + $foreignKey = $morph . '_id'; + } + + return new MorphTo($this, $morphType, $foreignKey, $alias, $relation); + } + + /** + * 解析模型的完整命名空间 + * @access protected + * @param string $model 模型名(或者完整类名) + * @return string + */ + protected function parseModel($model) + { + if (false === strpos($model, '\\')) { + $path = explode('\\', static::class); + array_pop($path); + array_push($path, Loader::parseName($model, 1)); + $model = implode('\\', $path); + } + + return $model; + } + + /** + * 获取模型的默认外键名 + * @access protected + * @param string $name 模型名 + * @return string + */ + protected function getForeignKey($name) + { + if (strpos($name, '\\')) { + $name = basename(str_replace('\\', '/', $name)); + } + + return Loader::parseName($name) . '_id'; + } + + /** + * 检查属性是否为关联属性 如果是则返回关联方法名 + * @access protected + * @param string $attr 关联属性名 + * @return string|false + */ + protected function isRelationAttr($attr) + { + $relation = Loader::parseName($attr, 1, false); + + if (method_exists($this, $relation)) { + return $relation; + } + + return false; + } + + /** + * 智能获取关联模型数据 + * @access protected + * @param Relation $modelRelation 模型关联对象 + * @return mixed + */ + protected function getRelationData(Relation $modelRelation) + { + if ($this->parent && !$modelRelation->isSelfRelation() && get_class($this->parent) == get_class($modelRelation->getModel())) { + $value = $this->parent; + } else { + // 获取关联数据 + $value = $modelRelation->getRelation(); + } + + return $value; + } + + /** + * 关联数据自动写入检查 + * @access protected + * @return void + */ + protected function checkAutoRelationWrite() + { + foreach ($this->together as $key => $name) { + if (is_array($name)) { + if (key($name) === 0) { + $this->relationWrite[$key] = []; + // 绑定关联属性 + foreach ((array) $name as $val) { + if (isset($this->data[$val])) { + $this->relationWrite[$key][$val] = $this->data[$val]; + } + } + } else { + // 直接传入关联数据 + $this->relationWrite[$key] = $name; + } + } elseif (isset($this->relation[$name])) { + $this->relationWrite[$name] = $this->relation[$name]; + } elseif (isset($this->data[$name])) { + $this->relationWrite[$name] = $this->data[$name]; + unset($this->data[$name]); + } + } + } + + /** + * 自动关联数据更新(针对一对一关联) + * @access protected + * @return void + */ + protected function autoRelationUpdate() + { + foreach ($this->relationWrite as $name => $val) { + if ($val instanceof Model) { + $val->isUpdate()->save(); + } else { + $model = $this->getRelation($name); + if ($model instanceof Model) { + $model->isUpdate()->save($val); + } + } + } + } + + /** + * 自动关联数据写入(针对一对一关联) + * @access protected + * @return void + */ + protected function autoRelationInsert() + { + foreach ($this->relationWrite as $name => $val) { + $method = Loader::parseName($name, 1, false); + $this->$method()->save($val); + } + } + + /** + * 自动关联数据删除(支持一对一及一对多关联) + * @access protected + * @return void + */ + protected function autoRelationDelete() + { + foreach ($this->relationWrite as $key => $name) { + $name = is_numeric($key) ? $name : $key; + $result = $this->getRelation($name); + + if ($result instanceof Model) { + $result->delete(); + } elseif ($result instanceof Collection) { + foreach ($result as $model) { + $model->delete(); + } + } + } + } +} diff --git a/library/traits/model/SoftDelete.php b/library/think/model/concern/SoftDelete.php similarity index 35% rename from library/traits/model/SoftDelete.php rename to library/think/model/concern/SoftDelete.php index e08d96aadd9a1798c5e17f627d8aaa69cf807e50..9091377d85fed0439bee244ba8567ffe6a16a393 100644 --- a/library/traits/model/SoftDelete.php +++ b/library/think/model/concern/SoftDelete.php @@ -1,10 +1,21 @@ getDeleteTimeField(); - if (!empty($this->data[$field])) { + + if ($field && !empty($this->getOrigin($field))) { return true; } + return false; } /** * 查询软删除数据 * @access public - * @return \think\db\Query + * @return Query */ public static function withTrashed() { $model = new static(); - return $model->db(); + + return $model->withTrashedData(true)->db(false); + } + + /** + * 是否包含软删除数据 + * @access protected + * @param bool $withTrashed 是否包含软删除数据 + * @return $this + */ + protected function withTrashedData($withTrashed) + { + $this->withTrashed = $withTrashed; + return $this; } /** * 只查询软删除数据 * @access public - * @return \think\db\Query + * @return Query */ public static function onlyTrashed() { $model = new static(); - $field = $model->getDeleteTimeField(); - return $model->db()->where($field, 'exp', 'is not null'); + $field = $model->getDeleteTimeField(true); + + if ($field) { + return $model + ->db(false, false) + ->useSoftDelete($field, $model->getWithTrashedExp()); + } + + return $model->db(false); + } + + /** + * 获取软删除数据的查询条件 + * @access protected + * @return array + */ + protected function getWithTrashedExp() + { + return is_null($this->defaultSoftDelete) ? + ['notnull', ''] : ['<>', $this->defaultSoftDelete]; } /** * 删除当前的记录 * @access public - * @param bool $force 是否强制删除 - * @return integer + * @return bool */ - public function delete($force = false) + public function delete() { - if (false === $this->trigger('before_delete', $this)) { + if (!$this->isExists() || false === $this->trigger('before_delete', $this)) { return false; } + $name = $this->getDeleteTimeField(); - if (!$force) { + + if ($name && !$this->isForce()) { // 软删除 - $this->change[] = $name; - $this->data[$name] = $this->autoWriteTimestamp($name); - $result = $this->isUpdate()->save(); + $this->data($name, $this->autoWriteTimestamp($name)); + + $result = $this->isUpdate()->withEvent(false)->save(); + + $this->withEvent(true); } else { - $result = $this->db()->delete($this->data); + // 读取更新条件 + $where = $this->getWhere(); + + // 删除当前模型数据 + $result = $this->db(false)->where($where)->delete(); + } + + // 关联删除 + if (!empty($this->relationWrite)) { + $this->autoRelationDelete(); } $this->trigger('after_delete', $this); - return $result; + + $this->exists(false); + + return true; } /** * 删除记录 * @access public - * @param mixed $data 主键列表 支持闭包查询条件 - * @param bool $force 是否强制删除 - * @return integer 成功删除的记录数 + * @param mixed $data 主键列表 支持闭包查询条件 + * @param bool $force 是否强制删除 + * @return bool */ public static function destroy($data, $force = false) { - $model = new static(); - $query = $model->db(); + // 包含软删除数据 + $query = self::withTrashed(); + if (is_array($data) && key($data) !== 0) { $query->where($data); $data = null; @@ -85,62 +145,93 @@ trait SoftDelete call_user_func_array($data, [ & $query]); $data = null; } elseif (is_null($data)) { - return 0; + return false; } $resultSet = $query->select($data); - $count = 0; + if ($resultSet) { foreach ($resultSet as $data) { - $result = $data->delete($force); - $count += $result; + $data->force($force)->delete(); } } - return $count; + + return true; } /** * 恢复被软删除的记录 * @access public - * @param array $where 更新条件 - * @return integer + * @param array $where 更新条件 + * @return bool */ public function restore($where = []) { $name = $this->getDeleteTimeField(); - // 恢复删除 - return $this->isUpdate()->save([$name => null], $where); - } + if ($name) { + if (false === $this->trigger('before_restore')) { + return false; + } - /** - * 查询默认不包含软删除数据 - * @access protected - * @param \think\db\Query $query 查询对象 - * @return void - */ - protected function base($query) - { - $field = $this->getDeleteTimeField(true); - $query->where($field, 'null'); + if (empty($where)) { + $pk = $this->getPk(); + + $where[] = [$pk, '=', $this->getData($pk)]; + } + + // 恢复删除 + $this->db(false) + ->where($where) + ->useSoftDelete($name, $this->getWithTrashedExp()) + ->update([$name => $this->defaultSoftDelete]); + + $this->trigger('after_restore'); + + return true; + } + + return false; } /** * 获取软删除字段 - * @access public - * @param bool $read 是否查询操作 写操作的时候会自动去掉表别名 - * @return string + * @access protected + * @param bool $read 是否查询操作 写操作的时候会自动去掉表别名 + * @return string|false */ protected function getDeleteTimeField($read = false) { - if (isset($this->deleteTime)) { - $field = $this->deleteTime; - } else { - $field = 'delete_time'; + $field = property_exists($this, 'deleteTime') && isset($this->deleteTime) ? $this->deleteTime : 'delete_time'; + + if (false === $field) { + return false; } + + if (!strpos($field, '.')) { + $field = '__TABLE__.' . $field; + } + if (!$read && strpos($field, '.')) { - list($alias, $field) = explode('.', $field); + $array = explode('.', $field); + $field = array_pop($array); } + return $field; } + + /** + * 查询的时候默认排除软删除数据 + * @access protected + * @param Query $query + * @return void + */ + protected function withNoTrashed($query) + { + $field = $this->getDeleteTimeField(true); + + if ($field) { + $query->useSoftDelete($field, $this->defaultSoftDelete); + } + } } diff --git a/library/think/model/concern/TimeStamp.php b/library/think/model/concern/TimeStamp.php new file mode 100644 index 0000000000000000000000000000000000000000..923b7d45331427515eb478afb2cfaad6e67a8d47 --- /dev/null +++ b/library/think/model/concern/TimeStamp.php @@ -0,0 +1,79 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\concern; + +/** + * 自动时间戳 + */ +trait TimeStamp +{ + /** + * 是否需要自动写入时间戳 如果设置为字符串 则表示时间字段的类型 + * @var bool|string + */ + protected $autoWriteTimestamp; + + /** + * 创建时间字段 false表示关闭 + * @var false|string + */ + protected $createTime = 'create_time'; + + /** + * 更新时间字段 false表示关闭 + * @var false|string + */ + protected $updateTime = 'update_time'; + + /** + * 时间字段显示格式 + * @var string + */ + protected $dateFormat; + + /** + * 时间日期字段格式化处理 + * @access protected + * @param mixed $time 时间日期表达式 + * @param mixed $format 日期格式 + * @param bool $timestamp 是否进行时间戳转换 + * @return mixed + */ + protected function formatDateTime($time, $format, $timestamp = false) + { + if (false !== strpos($format, '\\')) { + $time = new $format($time); + } elseif (!$timestamp && false !== $format) { + $time = date($format, $time); + } + + return $time; + } + + /** + * 检查时间字段写入 + * @access protected + * @return void + */ + protected function checkTimeStampWrite() + { + // 自动写入创建时间和更新时间 + if ($this->autoWriteTimestamp) { + if ($this->createTime && !isset($this->data[$this->createTime])) { + $this->data[$this->createTime] = $this->autoWriteTimestamp($this->createTime); + } + if ($this->updateTime && !isset($this->data[$this->updateTime])) { + $this->data[$this->updateTime] = $this->autoWriteTimestamp($this->updateTime); + } + } + } +} diff --git a/library/think/model/relation/BelongsTo.php b/library/think/model/relation/BelongsTo.php new file mode 100644 index 0000000000000000000000000000000000000000..bf2dbe53ae592d49578384d637920ed6405689da --- /dev/null +++ b/library/think/model/relation/BelongsTo.php @@ -0,0 +1,247 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use think\Loader; +use think\Model; + +class BelongsTo extends OneToOne +{ + /** + * 架构函数 + * @access public + * @param Model $parent 上级模型对象 + * @param string $model 模型名 + * @param string $foreignKey 关联外键 + * @param string $localKey 关联主键 + * @param string $relation 关联名 + */ + public function __construct(Model $parent, $model, $foreignKey, $localKey, $relation = null) + { + $this->parent = $parent; + $this->model = $model; + $this->foreignKey = $foreignKey; + $this->localKey = $localKey; + $this->joinType = 'INNER'; + $this->query = (new $model)->db(); + $this->relation = $relation; + } + + /** + * 延迟获取关联数据 + * @access public + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包查询条件 + * @return Model + */ + public function getRelation($subRelation = '', $closure = null) + { + if ($closure) { + $closure($this->query); + } + + $foreignKey = $this->foreignKey; + + $relationModel = $this->query + ->removeWhereField($this->localKey) + ->where($this->localKey, $this->parent->$foreignKey) + ->relation($subRelation) + ->find(); + + if ($relationModel) { + $relationModel->setParent(clone $this->parent); + } + + return $relationModel; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @param string $joinType JOIN类型 + * @return Query + */ + public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER') + { + return $this->parent; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $fields 字段 + * @return Query + */ + public function hasWhere($where = [], $fields = null) + { + $table = $this->query->getTable(); + $model = basename(str_replace('\\', '/', get_class($this->parent))); + $relation = basename(str_replace('\\', '/', $this->model)); + + if (is_array($where)) { + $this->getQueryWhere($where, $relation); + } + + $fields = $this->getRelationQueryFields($fields, $model); + + return $this->parent->db() + ->alias($model) + ->field($fields) + ->join([$table => $relation], $model . '.' . $this->foreignKey . '=' . $relation . '.' . $this->localKey, $this->joinType) + ->where($where); + } + + /** + * 预载入关联查询(数据集) + * @access protected + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + protected function eagerlySet(&$resultSet, $relation, $subRelation, $closure) + { + $localKey = $this->localKey; + $foreignKey = $this->foreignKey; + + $range = []; + foreach ($resultSet as $result) { + // 获取关联外键列表 + if (isset($result->$foreignKey)) { + $range[] = $result->$foreignKey; + } + } + + if (!empty($range)) { + $this->query->removeWhereField($localKey); + + $data = $this->eagerlyWhere([ + [$localKey, 'in', $range], + ], $localKey, $relation, $subRelation, $closure); + + // 关联属性名 + $attr = Loader::parseName($relation); + + // 关联数据封装 + foreach ($resultSet as $result) { + // 关联模型 + if (!isset($data[$result->$foreignKey])) { + $relationModel = null; + } else { + $relationModel = $data[$result->$foreignKey]; + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + } + + if (!empty($this->bindAttr)) { + // 绑定关联属性 + $this->bindAttr($relationModel, $result); + } else { + // 设置关联属性 + $result->setRelation($attr, $relationModel); + } + } + } + } + + /** + * 预载入关联查询(数据) + * @access protected + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + protected function eagerlyOne(&$result, $relation, $subRelation, $closure) + { + $localKey = $this->localKey; + $foreignKey = $this->foreignKey; + + $this->query->removeWhereField($localKey); + + $data = $this->eagerlyWhere([ + [$localKey, '=', $result->$foreignKey], + ], $localKey, $relation, $subRelation, $closure); + + // 关联模型 + if (!isset($data[$result->$foreignKey])) { + $relationModel = null; + } else { + $relationModel = $data[$result->$foreignKey]; + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + } + + if (!empty($this->bindAttr)) { + // 绑定关联属性 + $this->bindAttr($relationModel, $result); + } else { + // 设置关联属性 + $result->setRelation(Loader::parseName($relation), $relationModel); + } + } + + /** + * 添加关联数据 + * @access public + * @param Model $model 关联模型对象 + * @return Model + */ + public function associate($model) + { + $foreignKey = $this->foreignKey; + $pk = $model->getPk(); + + $this->parent->setAttr($foreignKey, $model->$pk); + $this->parent->save(); + + return $this->parent->setRelation($this->relation, $model); + } + + /** + * 注销关联数据 + * @access public + * @return Model + */ + public function dissociate() + { + $foreignKey = $this->foreignKey; + + $this->parent->setAttr($foreignKey, null); + $this->parent->save(); + + return $this->parent->setRelation($this->relation, null); + } + + /** + * 执行基础查询(仅执行一次) + * @access protected + * @return void + */ + protected function baseQuery() + { + if (empty($this->baseQuery)) { + if (isset($this->parent->{$this->foreignKey})) { + // 关联查询带入关联条件 + $this->query->where($this->localKey, '=', $this->parent->{$this->foreignKey}); + } + + $this->baseQuery = true; + } + } +} diff --git a/library/think/model/relation/BelongsToMany.php b/library/think/model/relation/BelongsToMany.php new file mode 100644 index 0000000000000000000000000000000000000000..02e666695c19a856414ccc54dfdddf81196249b2 --- /dev/null +++ b/library/think/model/relation/BelongsToMany.php @@ -0,0 +1,648 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use think\Collection; +use think\db\Query; +use think\Exception; +use think\Loader; +use think\Model; +use think\model\Pivot; +use think\model\Relation; + +class BelongsToMany extends Relation +{ + // 中间表表名 + protected $middle; + // 中间表模型名称 + protected $pivotName; + // 中间表模型对象 + protected $pivot; + + /** + * 架构函数 + * @access public + * @param Model $parent 上级模型对象 + * @param string $model 模型名 + * @param string $table 中间表名 + * @param string $foreignKey 关联模型外键 + * @param string $localKey 当前模型关联键 + */ + public function __construct(Model $parent, $model, $table, $foreignKey, $localKey) + { + $this->parent = $parent; + $this->model = $model; + $this->foreignKey = $foreignKey; + $this->localKey = $localKey; + + if (false !== strpos($table, '\\')) { + $this->pivotName = $table; + $this->middle = basename(str_replace('\\', '/', $table)); + } else { + $this->middle = $table; + } + + $this->query = (new $model)->db(); + $this->pivot = $this->newPivot(); + } + + /** + * 设置中间表模型 + * @access public + * @param $pivot + * @return $this + */ + public function pivot($pivot) + { + $this->pivotName = $pivot; + return $this; + } + + /** + * 获取中间表更新条件 + * @param $data + * @return array + */ + protected function getUpdateWhere($data) + { + return [ + $this->localKey => $data[$this->localKey], + $this->foreignKey => $data[$this->foreignKey], + ]; + } + + /** + * 实例化中间表模型 + * @access public + * @param array $data + * @param bool $isUpdate + * @return Pivot + * @throws Exception + */ + protected function newPivot($data = [], $isUpdate = false) + { + $class = $this->pivotName ?: '\\think\\model\\Pivot'; + $pivot = new $class($data, $this->parent, $this->middle); + + if ($pivot instanceof Pivot) { + return $isUpdate ? $pivot->isUpdate(true, $this->getUpdateWhere($data)) : $pivot; + } + + throw new Exception('pivot model must extends: \think\model\Pivot'); + } + + /** + * 合成中间表模型 + * @access protected + * @param array|Collection|Paginator $models + */ + protected function hydratePivot($models) + { + foreach ($models as $model) { + $pivot = []; + + foreach ($model->getData() as $key => $val) { + if (strpos($key, '__')) { + list($name, $attr) = explode('__', $key, 2); + + if ('pivot' == $name) { + $pivot[$attr] = $val; + unset($model->$key); + } + } + } + + $model->setRelation('pivot', $this->newPivot($pivot, true)); + } + } + + /** + * 创建关联查询Query对象 + * @access protected + * @return Query + */ + protected function buildQuery() + { + $foreignKey = $this->foreignKey; + $localKey = $this->localKey; + + // 关联查询 + $pk = $this->parent->getPk(); + + $condition[] = ['pivot.' . $localKey, '=', $this->parent->$pk]; + + return $this->belongsToManyQuery($foreignKey, $localKey, $condition); + } + + /** + * 延迟获取关联数据 + * @access public + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包查询条件 + * @return Collection + */ + public function getRelation($subRelation = '', $closure = null) + { + if ($closure) { + $closure($this->query); + } + + $result = $this->buildQuery()->relation($subRelation)->select(); + $this->hydratePivot($result); + + return $result; + } + + /** + * 重载select方法 + * @access public + * @param mixed $data + * @return Collection + */ + public function select($data = null) + { + $result = $this->buildQuery()->select($data); + $this->hydratePivot($result); + + return $result; + } + + /** + * 重载paginate方法 + * @access public + * @param null $listRows + * @param bool $simple + * @param array $config + * @return Paginator + */ + public function paginate($listRows = null, $simple = false, $config = []) + { + $result = $this->buildQuery()->paginate($listRows, $simple, $config); + $this->hydratePivot($result); + + return $result; + } + + /** + * 重载find方法 + * @access public + * @param mixed $data + * @return Model + */ + public function find($data = null) + { + $result = $this->buildQuery()->find($data); + if ($result) { + $this->hydratePivot([$result]); + } + + return $result; + } + + /** + * 查找多条记录 如果不存在则抛出异常 + * @access public + * @param array|string|Query|\Closure $data + * @return Collection + */ + public function selectOrFail($data = null) + { + return $this->failException(true)->select($data); + } + + /** + * 查找单条记录 如果不存在则抛出异常 + * @access public + * @param array|string|Query|\Closure $data + * @return Model + */ + public function findOrFail($data = null) + { + return $this->failException(true)->find($data); + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @param string $joinType JOIN类型 + * @return Query + */ + public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER') + { + return $this->parent; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $fields 字段 + * @return Query + * @throws Exception + */ + public function hasWhere($where = [], $fields = null) + { + throw new Exception('relation not support: hasWhere'); + } + + /** + * 设置中间表的查询条件 + * @access public + * @param string $field + * @param string $op + * @param mixed $condition + * @return $this + */ + public function wherePivot($field, $op = null, $condition = null) + { + $this->query->where('pivot.' . $field, $op, $condition); + return $this; + } + + /** + * 预载入关联查询(数据集) + * @access public + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure) + { + $localKey = $this->localKey; + $foreignKey = $this->foreignKey; + + $pk = $resultSet[0]->getPk(); + $range = []; + foreach ($resultSet as $result) { + // 获取关联外键列表 + if (isset($result->$pk)) { + $range[] = $result->$pk; + } + } + + if (!empty($range)) { + // 查询关联数据 + $data = $this->eagerlyManyToMany([ + ['pivot.' . $localKey, 'in', $range], + ], $relation, $subRelation); + + // 关联属性名 + $attr = Loader::parseName($relation); + + // 关联数据封装 + foreach ($resultSet as $result) { + if (!isset($data[$result->$pk])) { + $data[$result->$pk] = []; + } + + $result->setRelation($attr, $this->resultSetBuild($data[$result->$pk])); + } + } + } + + /** + * 预载入关联查询(单个数据) + * @access public + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResult(&$result, $relation, $subRelation, $closure) + { + $pk = $result->getPk(); + + if (isset($result->$pk)) { + $pk = $result->$pk; + // 查询管理数据 + $data = $this->eagerlyManyToMany([ + ['pivot.' . $this->localKey, '=', $pk], + ], $relation, $subRelation); + + // 关联数据封装 + if (!isset($data[$pk])) { + $data[$pk] = []; + } + + $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$pk])); + } + } + + /** + * 关联统计 + * @access public + * @param Model $result 数据对象 + * @param \Closure $closure 闭包 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return integer + */ + public function relationCount($result, $closure, $aggregate = 'count', $field = '*') + { + $pk = $result->getPk(); + $count = 0; + + if (isset($result->$pk)) { + $pk = $result->$pk; + $count = $this->belongsToManyQuery($this->foreignKey, $this->localKey, [ + ['pivot.' . $this->localKey, '=', $pk], + ])->$aggregate($field); + } + + return $count; + } + + /** + * 获取关联统计子查询 + * @access public + * @param \Closure $closure 闭包 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return string + */ + public function getRelationCountQuery($closure, $aggregate = 'count', $field = '*') + { + return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [ + [ + 'pivot.' . $this->localKey, 'exp', $this->query->raw('=' . $this->parent->getTable() . '.' . $this->parent->getPk()), + ], + ])->fetchSql()->$aggregate($field); + } + + /** + * 多对多 关联模型预查询 + * @access protected + * @param array $where 关联预查询条件 + * @param string $relation 关联名 + * @param string $subRelation 子关联 + * @return array + */ + protected function eagerlyManyToMany($where, $relation, $subRelation = '') + { + // 预载入关联查询 支持嵌套预载入 + $list = $this->belongsToManyQuery($this->foreignKey, $this->localKey, $where) + ->with($subRelation) + ->select(); + + // 组装模型数据 + $data = []; + foreach ($list as $set) { + $pivot = []; + foreach ($set->getData() as $key => $val) { + if (strpos($key, '__')) { + list($name, $attr) = explode('__', $key, 2); + if ('pivot' == $name) { + $pivot[$attr] = $val; + unset($set->$key); + } + } + } + + $set->setRelation('pivot', $this->newPivot($pivot, true)); + + $data[$pivot[$this->localKey]][] = $set; + } + + return $data; + } + + /** + * BELONGS TO MANY 关联查询 + * @access protected + * @param string $foreignKey 关联模型关联键 + * @param string $localKey 当前模型关联键 + * @param array $condition 关联查询条件 + * @return Query + */ + protected function belongsToManyQuery($foreignKey, $localKey, $condition = []) + { + // 关联查询封装 + $tableName = $this->query->getTable(); + $table = $this->pivot->getTable(); + $fields = $this->getQueryFields($tableName); + + $query = $this->query + ->field($fields) + ->field(true, false, $table, 'pivot', 'pivot__'); + + if (empty($this->baseQuery)) { + $relationFk = $this->query->getPk(); + $query->join([$table => 'pivot'], 'pivot.' . $foreignKey . '=' . $tableName . '.' . $relationFk) + ->where($condition); + } + + return $query; + } + + /** + * 保存(新增)当前关联数据对象 + * @access public + * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键 + * @param array $pivot 中间表额外数据 + * @return array|Pivot + */ + public function save($data, array $pivot = []) + { + // 保存关联表/中间表数据 + return $this->attach($data, $pivot); + } + + /** + * 批量保存当前关联数据对象 + * @access public + * @param array $dataSet 数据集 + * @param array $pivot 中间表额外数据 + * @param bool $samePivot 额外数据是否相同 + * @return array|false + */ + public function saveAll(array $dataSet, array $pivot = [], $samePivot = false) + { + $result = []; + + foreach ($dataSet as $key => $data) { + if (!$samePivot) { + $pivotData = isset($pivot[$key]) ? $pivot[$key] : []; + } else { + $pivotData = $pivot; + } + + $result[] = $this->attach($data, $pivotData); + } + + return empty($result) ? false : $result; + } + + /** + * 附加关联的一个中间表数据 + * @access public + * @param mixed $data 数据 可以使用数组、关联模型对象 或者 关联对象的主键 + * @param array $pivot 中间表额外数据 + * @return array|Pivot + * @throws Exception + */ + public function attach($data, $pivot = []) + { + if (is_array($data)) { + if (key($data) === 0) { + $id = $data; + } else { + // 保存关联表数据 + $model = new $this->model; + $model->save($data); + $id = $model->getLastInsID(); + } + } elseif (is_numeric($data) || is_string($data)) { + // 根据关联表主键直接写入中间表 + $id = $data; + } elseif ($data instanceof Model) { + // 根据关联表主键直接写入中间表 + $relationFk = $data->getPk(); + $id = $data->$relationFk; + } + + if ($id) { + // 保存中间表数据 + $pk = $this->parent->getPk(); + $pivot[$this->localKey] = $this->parent->$pk; + $ids = (array) $id; + + foreach ($ids as $id) { + $pivot[$this->foreignKey] = $id; + $this->pivot->insert($pivot, true); + $result[] = $this->newPivot($pivot, true); + } + + if (count($result) == 1) { + // 返回中间表模型对象 + $result = $result[0]; + } + + return $result; + } else { + throw new Exception('miss relation data'); + } + } + + /** + * 解除关联的一个中间表数据 + * @access public + * @param integer|array $data 数据 可以使用关联对象的主键 + * @param bool $relationDel 是否同时删除关联表数据 + * @return integer + */ + public function detach($data = null, $relationDel = false) + { + if (is_array($data)) { + $id = $data; + } elseif (is_numeric($data) || is_string($data)) { + // 根据关联表主键直接写入中间表 + $id = $data; + } elseif ($data instanceof Model) { + // 根据关联表主键直接写入中间表 + $relationFk = $data->getPk(); + $id = $data->$relationFk; + } + + // 删除中间表数据 + $pk = $this->parent->getPk(); + $pivot[] = [$this->localKey, '=', $this->parent->$pk]; + + if (isset($id)) { + $pivot[] = [$this->foreignKey, is_array($id) ? 'in' : '=', $id]; + } + + $result = $this->pivot->where($pivot)->delete(); + + // 删除关联表数据 + if (isset($id) && $relationDel) { + $model = $this->model; + $model::destroy($id); + } + + return $result; + } + + /** + * 数据同步 + * @access public + * @param array $ids + * @param bool $detaching + * @return array + */ + public function sync($ids, $detaching = true) + { + $changes = [ + 'attached' => [], + 'detached' => [], + 'updated' => [], + ]; + + $pk = $this->parent->getPk(); + + $current = $this->pivot + ->where($this->localKey, $this->parent->$pk) + ->column($this->foreignKey); + + $records = []; + + foreach ($ids as $key => $value) { + if (!is_array($value)) { + $records[$value] = []; + } else { + $records[$key] = $value; + } + } + + $detach = array_diff($current, array_keys($records)); + + if ($detaching && count($detach) > 0) { + $this->detach($detach); + $changes['detached'] = $detach; + } + + foreach ($records as $id => $attributes) { + if (!in_array($id, $current)) { + $this->attach($id, $attributes); + $changes['attached'][] = $id; + } elseif (count($attributes) > 0 && $this->attach($id, $attributes)) { + $changes['updated'][] = $id; + } + } + + return $changes; + } + + /** + * 执行基础查询(仅执行一次) + * @access protected + * @return void + */ + protected function baseQuery() + { + if (empty($this->baseQuery) && $this->parent->getData()) { + $pk = $this->parent->getPk(); + $table = $this->pivot->getTable(); + + $this->query + ->join([$table => 'pivot'], 'pivot.' . $this->foreignKey . '=' . $this->query->getTable() . '.' . $this->query->getPk()) + ->where('pivot.' . $this->localKey, $this->parent->$pk); + $this->baseQuery = true; + } + } + +} diff --git a/library/think/model/relation/HasMany.php b/library/think/model/relation/HasMany.php new file mode 100644 index 0000000000000000000000000000000000000000..46082d0aeaf87f7670dc44a2cc57882e8ae8961d --- /dev/null +++ b/library/think/model/relation/HasMany.php @@ -0,0 +1,327 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use think\db\Query; +use think\Loader; +use think\Model; +use think\model\Relation; + +class HasMany extends Relation +{ + /** + * 架构函数 + * @access public + * @param Model $parent 上级模型对象 + * @param string $model 模型名 + * @param string $foreignKey 关联外键 + * @param string $localKey 当前模型主键 + */ + public function __construct(Model $parent, $model, $foreignKey, $localKey) + { + $this->parent = $parent; + $this->model = $model; + $this->foreignKey = $foreignKey; + $this->localKey = $localKey; + $this->query = (new $model)->db(); + } + + /** + * 延迟获取关联数据 + * @access public + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包查询条件 + * @return \think\Collection + */ + public function getRelation($subRelation = '', $closure = null) + { + if ($closure) { + $closure($this->query); + } + + $list = $this->query + ->where($this->foreignKey, $this->parent->{$this->localKey}) + ->relation($subRelation) + ->select(); + + $parent = clone $this->parent; + + foreach ($list as &$model) { + $model->setParent($parent); + } + + return $list; + } + + /** + * 预载入关联查询 + * @access public + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure) + { + $localKey = $this->localKey; + $range = []; + + foreach ($resultSet as $result) { + // 获取关联外键列表 + if (isset($result->$localKey)) { + $range[] = $result->$localKey; + } + } + + if (!empty($range)) { + $where = [ + [$this->foreignKey, 'in', $range], + ]; + $data = $this->eagerlyOneToMany($where, $relation, $subRelation, $closure); + + // 关联属性名 + $attr = Loader::parseName($relation); + + // 关联数据封装 + foreach ($resultSet as $result) { + $pk = $result->$localKey; + if (!isset($data[$pk])) { + $data[$pk] = []; + } + + foreach ($data[$pk] as &$relationModel) { + $relationModel->setParent(clone $result); + } + + $result->setRelation($attr, $this->resultSetBuild($data[$pk])); + } + } + } + + /** + * 预载入关联查询 + * @access public + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResult(&$result, $relation, $subRelation, $closure) + { + $localKey = $this->localKey; + + if (isset($result->$localKey)) { + $pk = $result->$localKey; + $where = [ + [$this->foreignKey, '=', $pk], + ]; + $data = $this->eagerlyOneToMany($where, $relation, $subRelation, $closure); + + // 关联数据封装 + if (!isset($data[$pk])) { + $data[$pk] = []; + } + + foreach ($data[$pk] as &$relationModel) { + $relationModel->setParent(clone $result); + } + + $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$pk])); + } + } + + /** + * 关联统计 + * @access public + * @param Model $result 数据对象 + * @param \Closure $closure 闭包 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return integer + */ + public function relationCount($result, $closure, $aggregate = 'count', $field = '*') + { + $localKey = $this->localKey; + $count = 0; + + if (isset($result->$localKey)) { + if ($closure) { + $closure($this->query); + } + + $count = $this->query->where($this->foreignKey, '=', $result->$localKey)->$aggregate($field); + } + + return $count; + } + + /** + * 创建关联统计子查询 + * @access public + * @param \Closure $closure 闭包 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return string + */ + public function getRelationCountQuery($closure, $aggregate = 'count', $field = '*') + { + if ($closure) { + $closure($this->query); + } + + return $this->query + ->whereExp($this->foreignKey, '=' . $this->parent->getTable() . '.' . $this->parent->getPk()) + ->fetchSql() + ->$aggregate($field); + } + + /** + * 一对多 关联模型预查询 + * @access public + * @param array $where 关联预查询条件 + * @param string $relation 关联名 + * @param string $subRelation 子关联 + * @param \Closure $closure + * @return array + */ + protected function eagerlyOneToMany($where, $relation, $subRelation = '', $closure = null) + { + $foreignKey = $this->foreignKey; + + $this->query->removeWhereField($this->foreignKey); + + // 预载入关联查询 支持嵌套预载入 + if ($closure) { + $closure($this->query); + } + + $list = $this->query->where($where)->with($subRelation)->select(); + + // 组装模型数据 + $data = []; + + foreach ($list as $set) { + $data[$set->$foreignKey][] = $set; + } + + return $data; + } + + /** + * 保存(新增)当前关联数据对象 + * @access public + * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键 + * @param boolean $replace 是否自动识别更新和写入 + * @return Model|false + */ + public function save($data, $replace = true) + { + if ($data instanceof Model) { + $data = $data->getData(); + } + + // 保存关联表数据 + $data[$this->foreignKey] = $this->parent->{$this->localKey}; + + $model = new $this->model; + + return $model->replace($replace)->save($data) ? $model : false; + } + + /** + * 批量保存当前关联数据对象 + * @access public + * @param array $dataSet 数据集 + * @param boolean $replace 是否自动识别更新和写入 + * @return array|false + */ + public function saveAll(array $dataSet, $replace = true) + { + $result = []; + + foreach ($dataSet as $key => $data) { + $result[] = $this->save($data, $replace); + } + + return empty($result) ? false : $result; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @param string $joinType JOIN类型 + * @return Query + */ + public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER') + { + $table = $this->query->getTable(); + $model = basename(str_replace('\\', '/', get_class($this->parent))); + $relation = basename(str_replace('\\', '/', $this->model)); + + return $this->parent->db() + ->alias($model) + ->field($model . '.*') + ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $joinType) + ->group($relation . '.' . $this->foreignKey) + ->having('count(' . $id . ')' . $operator . $count); + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $fields 字段 + * @return Query + */ + public function hasWhere($where = [], $fields = null) + { + $table = $this->query->getTable(); + $model = basename(str_replace('\\', '/', get_class($this->parent))); + $relation = basename(str_replace('\\', '/', $this->model)); + + if (is_array($where)) { + $this->getQueryWhere($where, $relation); + } + + $fields = $this->getRelationQueryFields($fields, $model); + + return $this->parent->db() + ->alias($model) + ->group($model . '.' . $this->localKey) + ->field($fields) + ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey) + ->where($where); + } + + /** + * 执行基础查询(仅执行一次) + * @access protected + * @return void + */ + protected function baseQuery() + { + if (empty($this->baseQuery)) { + if (isset($this->parent->{$this->localKey})) { + // 关联查询带入关联条件 + $this->query->where($this->foreignKey, '=', $this->parent->{$this->localKey}); + } + + $this->baseQuery = true; + } + } + +} diff --git a/library/think/model/relation/HasManyThrough.php b/library/think/model/relation/HasManyThrough.php new file mode 100644 index 0000000000000000000000000000000000000000..411f3fccf36598b20f13c901ba60eef1e603ac2f --- /dev/null +++ b/library/think/model/relation/HasManyThrough.php @@ -0,0 +1,155 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use think\db\Query; +use think\Exception; +use think\Loader; +use think\Model; +use think\model\Relation; + +class HasManyThrough extends Relation +{ + // 中间关联表外键 + protected $throughKey; + // 中间表模型 + protected $through; + + /** + * 架构函数 + * @access public + * @param Model $parent 上级模型对象 + * @param string $model 模型名 + * @param string $through 中间模型名 + * @param string $foreignKey 关联外键 + * @param string $throughKey 关联外键 + * @param string $localKey 当前主键 + */ + public function __construct(Model $parent, $model, $through, $foreignKey, $throughKey, $localKey) + { + $this->parent = $parent; + $this->model = $model; + $this->through = $through; + $this->foreignKey = $foreignKey; + $this->throughKey = $throughKey; + $this->localKey = $localKey; + $this->query = (new $model)->db(); + } + + /** + * 延迟获取关联数据 + * @access public + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包查询条件 + * @return \think\Collection + */ + public function getRelation($subRelation = '', $closure = null) + { + if ($closure) { + $closure($this->query); + } + + $this->baseQuery(); + + return $this->query->relation($subRelation)->select(); + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @param string $joinType JOIN类型 + * @return Query + */ + public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER') + { + return $this->parent; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $fields 字段 + * @return Query + */ + public function hasWhere($where = [], $fields = null) + { + throw new Exception('relation not support: hasWhere'); + } + + /** + * 预载入关联查询 + * @access public + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure) + {} + + /** + * 预载入关联查询 返回模型对象 + * @access public + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResult(&$result, $relation, $subRelation, $closure) + {} + + /** + * 关联统计 + * @access public + * @param Model $result 数据对象 + * @param \Closure $closure 闭包 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return integer + */ + public function relationCount($result, $closure, $aggregate = 'count', $field = '*') + {} + + /** + * 执行基础查询(仅执行一次) + * @access protected + * @return void + */ + protected function baseQuery() + { + if (empty($this->baseQuery) && $this->parent->getData()) { + $through = $this->through; + $alias = Loader::parseName(basename(str_replace('\\', '/', $this->model))); + $throughTable = $through::getTable(); + $pk = (new $through)->getPk(); + $throughKey = $this->throughKey; + $modelTable = $this->parent->getTable(); + $fields = $this->getQueryFields($alias); + + $this->query + ->field($fields) + ->alias($alias) + ->join($throughTable, $throughTable . '.' . $pk . '=' . $alias . '.' . $throughKey) + ->join($modelTable, $modelTable . '.' . $this->localKey . '=' . $throughTable . '.' . $this->foreignKey) + ->where($throughTable . '.' . $this->foreignKey, $this->parent->{$this->localKey}); + + $this->baseQuery = true; + } + } + +} diff --git a/library/think/model/relation/HasOne.php b/library/think/model/relation/HasOne.php new file mode 100644 index 0000000000000000000000000000000000000000..02c743c5992ff233185a57e999ef2358a67db9d5 --- /dev/null +++ b/library/think/model/relation/HasOne.php @@ -0,0 +1,226 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use think\db\Query; +use think\Loader; +use think\Model; + +class HasOne extends OneToOne +{ + /** + * 架构函数 + * @access public + * @param Model $parent 上级模型对象 + * @param string $model 模型名 + * @param string $foreignKey 关联外键 + * @param string $localKey 当前模型主键 + */ + public function __construct(Model $parent, $model, $foreignKey, $localKey) + { + $this->parent = $parent; + $this->model = $model; + $this->foreignKey = $foreignKey; + $this->localKey = $localKey; + $this->joinType = 'INNER'; + $this->query = (new $model)->db(); + } + + /** + * 延迟获取关联数据 + * @access public + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包查询条件 + * @return Model + */ + public function getRelation($subRelation = '', $closure = null) + { + $localKey = $this->localKey; + + if ($closure) { + $closure($this->query); + } + + // 判断关联类型执行查询 + $relationModel = $this->query + ->removeWhereField($this->foreignKey) + ->where($this->foreignKey, $this->parent->$localKey) + ->relation($subRelation) + ->find(); + + if ($relationModel) { + $relationModel->setParent(clone $this->parent); + } + + return $relationModel; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @param string $joinType JOIN类型 + * @return Query + */ + public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER') + { + $table = $this->query->getTable(); + $model = basename(str_replace('\\', '/', get_class($this->parent))); + $relation = basename(str_replace('\\', '/', $this->model)); + $localKey = $this->localKey; + $foreignKey = $this->foreignKey; + + return $this->parent->db() + ->alias($model) + ->whereExists(function ($query) use ($table, $model, $relation, $localKey, $foreignKey) { + $query->table([$table => $relation]) + ->field($relation . '.' . $foreignKey) + ->whereExp($model . '.' . $localKey, '=' . $relation . '.' . $foreignKey); + }); + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $fields 字段 + * @return Query + */ + public function hasWhere($where = [], $fields = null) + { + $table = $this->query->getTable(); + $model = basename(str_replace('\\', '/', get_class($this->parent))); + $relation = basename(str_replace('\\', '/', $this->model)); + + if (is_array($where)) { + $this->getQueryWhere($where, $relation); + } + + $fields = $this->getRelationQueryFields($fields, $model); + + return $this->parent->db() + ->alias($model) + ->field($fields) + ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $this->joinType) + ->where($where); + } + + /** + * 预载入关联查询(数据集) + * @access protected + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + protected function eagerlySet(&$resultSet, $relation, $subRelation, $closure) + { + $localKey = $this->localKey; + $foreignKey = $this->foreignKey; + + $range = []; + foreach ($resultSet as $result) { + // 获取关联外键列表 + if (isset($result->$localKey)) { + $range[] = $result->$localKey; + } + } + + if (!empty($range)) { + $this->query->removeWhereField($foreignKey); + + $data = $this->eagerlyWhere([ + [$foreignKey, 'in', $range], + ], $foreignKey, $relation, $subRelation, $closure); + + // 关联属性名 + $attr = Loader::parseName($relation); + + // 关联数据封装 + foreach ($resultSet as $result) { + // 关联模型 + if (!isset($data[$result->$localKey])) { + $relationModel = null; + } else { + $relationModel = $data[$result->$localKey]; + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + } + + if (!empty($this->bindAttr)) { + // 绑定关联属性 + $this->bindAttr($relationModel, $result, $this->bindAttr); + } else { + // 设置关联属性 + $result->setRelation($attr, $relationModel); + } + } + } + } + + /** + * 预载入关联查询(数据) + * @access protected + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + protected function eagerlyOne(&$result, $relation, $subRelation, $closure) + { + $localKey = $this->localKey; + $foreignKey = $this->foreignKey; + + $this->query->removeWhereField($foreignKey); + + $data = $this->eagerlyWhere([ + [$foreignKey, '=', $result->$localKey], + ], $foreignKey, $relation, $subRelation, $closure); + + // 关联模型 + if (!isset($data[$result->$localKey])) { + $relationModel = null; + } else { + $relationModel = $data[$result->$localKey]; + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + } + + if (!empty($this->bindAttr)) { + // 绑定关联属性 + $this->bindAttr($relationModel, $result, $this->bindAttr); + } else { + $result->setRelation(Loader::parseName($relation), $relationModel); + } + } + + /** + * 执行基础查询(仅执行一次) + * @access protected + * @return void + */ + protected function baseQuery() + { + if (empty($this->baseQuery)) { + if (isset($this->parent->{$this->localKey})) { + // 关联查询带入关联条件 + $this->query->where($this->foreignKey, '=', $this->parent->{$this->localKey}); + } + + $this->baseQuery = true; + } + } +} diff --git a/library/think/model/relation/MorphMany.php b/library/think/model/relation/MorphMany.php new file mode 100644 index 0000000000000000000000000000000000000000..3e913ccd06f6fb69d01f46a6c7be30e73ac9d528 --- /dev/null +++ b/library/think/model/relation/MorphMany.php @@ -0,0 +1,322 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use think\db\Query; +use think\Exception; +use think\Loader; +use think\Model; +use think\model\Relation; + +class MorphMany extends Relation +{ + // 多态字段 + protected $morphKey; + protected $morphType; + // 多态类型 + protected $type; + + /** + * 架构函数 + * @access public + * @param Model $parent 上级模型对象 + * @param string $model 模型名 + * @param string $morphKey 关联外键 + * @param string $morphType 多态字段名 + * @param string $type 多态类型 + */ + public function __construct(Model $parent, $model, $morphKey, $morphType, $type) + { + $this->parent = $parent; + $this->model = $model; + $this->type = $type; + $this->morphKey = $morphKey; + $this->morphType = $morphType; + $this->query = (new $model)->db(); + } + + /** + * 延迟获取关联数据 + * @access public + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包查询条件 + * @return \think\Collection + */ + public function getRelation($subRelation = '', $closure = null) + { + if ($closure) { + $closure($this->query); + } + + $this->baseQuery(); + + $list = $this->query->relation($subRelation)->select(); + $parent = clone $this->parent; + + foreach ($list as &$model) { + $model->setParent($parent); + } + + return $list; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @param string $joinType JOIN类型 + * @return Query + */ + public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER') + { + throw new Exception('relation not support: has'); + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $fields 字段 + * @return Query + */ + public function hasWhere($where = [], $fields = null) + { + throw new Exception('relation not support: hasWhere'); + } + + /** + * 预载入关联查询 + * @access public + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure) + { + $morphType = $this->morphType; + $morphKey = $this->morphKey; + $type = $this->type; + $range = []; + + foreach ($resultSet as $result) { + $pk = $result->getPk(); + // 获取关联外键列表 + if (isset($result->$pk)) { + $range[] = $result->$pk; + } + } + + if (!empty($range)) { + $where = [ + [$morphKey, 'in', $range], + [$morphType, '=', $type], + ]; + $data = $this->eagerlyMorphToMany($where, $relation, $subRelation, $closure); + + // 关联属性名 + $attr = Loader::parseName($relation); + + // 关联数据封装 + foreach ($resultSet as $result) { + if (!isset($data[$result->$pk])) { + $data[$result->$pk] = []; + } + + foreach ($data[$result->$pk] as &$relationModel) { + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + } + + $result->setRelation($attr, $this->resultSetBuild($data[$result->$pk])); + } + } + } + + /** + * 预载入关联查询 + * @access public + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResult(&$result, $relation, $subRelation, $closure) + { + $pk = $result->getPk(); + + if (isset($result->$pk)) { + $key = $result->$pk; + $where = [ + [$this->morphKey, '=', $key], + [$this->morphType, '=', $this->type], + ]; + $data = $this->eagerlyMorphToMany($where, $relation, $subRelation, $closure); + + if (!isset($data[$key])) { + $data[$key] = []; + } + + foreach ($data[$key] as &$relationModel) { + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + } + + $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$key])); + } + } + + /** + * 关联统计 + * @access public + * @param Model $result 数据对象 + * @param \Closure $closure 闭包 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return integer + */ + public function relationCount($result, $closure, $aggregate = 'count', $field = '*') + { + $pk = $result->getPk(); + $count = 0; + + if (isset($result->$pk)) { + if ($closure) { + $closur($this->query); + } + + $count = $this->query + ->where([ + [$this->morphKey, '=', $result->$pk], + [$this->morphType, '=', $this->type], + ]) + ->$aggregate($field); + } + + return $count; + } + + /** + * 获取关联统计子查询 + * @access public + * @param \Closure $closure 闭包 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return string + */ + public function getRelationCountQuery($closure, $aggregate = 'count', $field = '*') + { + if ($closure) { + $closure($this->query); + } + + return $this->query + ->whereExp($this->morphKey, '=' . $this->parent->getTable() . '.' . $this->parent->getPk()) + ->where($this->morphType, '=', $this->type) + ->fetchSql() + ->$aggregate($field); + } + + /** + * 多态一对多 关联模型预查询 + * @access protected + * @param array $where 关联预查询条件 + * @param string $relation 关联名 + * @param string $subRelation 子关联 + * @param \Closure $closure 闭包 + * @return array + */ + protected function eagerlyMorphToMany($where, $relation, $subRelation = '', $closure = null) + { + // 预载入关联查询 支持嵌套预载入 + $this->query->removeOption('where'); + + if ($closure) { + $closure($this->query); + } + + $list = $this->query->where($where)->with($subRelation)->select(); + $morphKey = $this->morphKey; + + // 组装模型数据 + $data = []; + foreach ($list as $set) { + $data[$set->$morphKey][] = $set; + } + + return $data; + } + + /** + * 保存(新增)当前关联数据对象 + * @access public + * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键 + * @return Model|false + */ + public function save($data) + { + if ($data instanceof Model) { + $data = $data->getData(); + } + + // 保存关联表数据 + $pk = $this->parent->getPk(); + + $model = new $this->model; + + $data[$this->morphKey] = $this->parent->$pk; + $data[$this->morphType] = $this->type; + + return $model->save($data) ? $model : false; + } + + /** + * 批量保存当前关联数据对象 + * @access public + * @param array $dataSet 数据集 + * @return array|false + */ + public function saveAll(array $dataSet) + { + $result = []; + + foreach ($dataSet as $key => $data) { + $result[] = $this->save($data); + } + + return empty($result) ? false : $result; + } + + /** + * 执行基础查询(仅执行一次) + * @access protected + * @return void + */ + protected function baseQuery() + { + if (empty($this->baseQuery) && $this->parent->getData()) { + $pk = $this->parent->getPk(); + + $this->query->where([ + [$this->morphKey, '=', $this->parent->$pk], + [$this->morphType, '=', $this->type], + ]); + + $this->baseQuery = true; + } + } + +} diff --git a/library/think/model/relation/MorphOne.php b/library/think/model/relation/MorphOne.php new file mode 100644 index 0000000000000000000000000000000000000000..ede680c63a3fb5d139cc28b89a3e1af6cf7dc117 --- /dev/null +++ b/library/think/model/relation/MorphOne.php @@ -0,0 +1,245 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use think\db\Query; +use think\Exception; +use think\Loader; +use think\Model; +use think\model\Relation; + +class MorphOne extends Relation +{ + // 多态字段 + protected $morphKey; + protected $morphType; + // 多态类型 + protected $type; + + /** + * 构造函数 + * @access public + * @param Model $parent 上级模型对象 + * @param string $model 模型名 + * @param string $morphKey 关联外键 + * @param string $morphType 多态字段名 + * @param string $type 多态类型 + */ + public function __construct(Model $parent, $model, $morphKey, $morphType, $type) + { + $this->parent = $parent; + $this->model = $model; + $this->type = $type; + $this->morphKey = $morphKey; + $this->morphType = $morphType; + $this->query = (new $model)->db(); + } + + /** + * 延迟获取关联数据 + * @access public + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包查询条件 + * @return Model + */ + public function getRelation($subRelation = '', $closure = null) + { + if ($closure) { + $closure($this->query); + } + + $this->baseQuery(); + + $relationModel = $this->query->relation($subRelation)->find(); + + if ($relationModel) { + $relationModel->setParent(clone $this->parent); + } + + return $relationModel; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @param string $joinType JOIN类型 + * @return Query + */ + public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER') + { + return $this->parent; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $fields 字段 + * @return Query + */ + public function hasWhere($where = [], $fields = null) + { + throw new Exception('relation not support: hasWhere'); + } + + /** + * 预载入关联查询 + * @access public + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure) + { + $morphType = $this->morphType; + $morphKey = $this->morphKey; + $type = $this->type; + $range = []; + + foreach ($resultSet as $result) { + $pk = $result->getPk(); + // 获取关联外键列表 + if (isset($result->$pk)) { + $range[] = $result->$pk; + } + } + + if (!empty($range)) { + $data = $this->eagerlyMorphToOne([ + [$morphKey, 'in', $range], + [$morphType, '=', $type], + ], $relation, $subRelation, $closure); + + // 关联属性名 + $attr = Loader::parseName($relation); + + // 关联数据封装 + foreach ($resultSet as $result) { + if (!isset($data[$result->$pk])) { + $relationModel = null; + } else { + $relationModel = $data[$result->$pk]; + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + } + + $result->setRelation($attr, $relationModel); + } + } + } + + /** + * 预载入关联查询 + * @access public + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResult(&$result, $relation, $subRelation, $closure) + { + $pk = $result->getPk(); + + if (isset($result->$pk)) { + $pk = $result->$pk; + $data = $this->eagerlyMorphToOne([ + [$this->morphKey, '=', $pk], + [$this->morphType, '=', $this->type], + ], $relation, $subRelation, $closure); + + if (isset($data[$pk])) { + $relationModel = $data[$pk]; + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + } else { + $relationModel = null; + } + + $result->setRelation(Loader::parseName($relation), $relationModel); + } + } + + /** + * 多态一对一 关联模型预查询 + * @access protected + * @param array $where 关联预查询条件 + * @param string $relation 关联名 + * @param string $subRelation 子关联 + * @param \Closure $closure 闭包 + * @return array + */ + protected function eagerlyMorphToOne($where, $relation, $subRelation = '', $closure = null) + { + // 预载入关联查询 支持嵌套预载入 + if ($closure) { + $closure($this->query); + } + + $list = $this->query->where($where)->with($subRelation)->find(); + $morphKey = $this->morphKey; + + // 组装模型数据 + $data = []; + + foreach ($list as $set) { + $data[$set->$morphKey] = $set; + } + + return $data; + } + + /** + * 保存(新增)当前关联数据对象 + * @access public + * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键 + * @return Model|false + */ + public function save($data) + { + if ($data instanceof Model) { + $data = $data->getData(); + } + // 保存关联表数据 + $pk = $this->parent->getPk(); + + $model = new $this->model; + + $data[$this->morphKey] = $this->parent->$pk; + $data[$this->morphType] = $this->type; + return $model->save($data) ? $model : false; + } + + /** + * 执行基础查询(进执行一次) + * @access protected + * @return void + */ + protected function baseQuery() + { + if (empty($this->baseQuery) && $this->parent->getData()) { + $pk = $this->parent->getPk(); + + $this->query->where([ + [$this->morphKey, '=', $this->parent->$pk], + [$this->morphType, '=', $this->type], + ]); + $this->baseQuery = true; + } + } + +} diff --git a/library/think/model/relation/MorphTo.php b/library/think/model/relation/MorphTo.php new file mode 100644 index 0000000000000000000000000000000000000000..bb7c4d0b3a83ec9489c28871cf5f14971f8992df --- /dev/null +++ b/library/think/model/relation/MorphTo.php @@ -0,0 +1,306 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use think\Exception; +use think\Loader; +use think\Model; +use think\model\Relation; + +class MorphTo extends Relation +{ + // 多态字段 + protected $morphKey; + protected $morphType; + // 多态别名 + protected $alias; + // 关联名 + protected $relation; + + /** + * 架构函数 + * @access public + * @param Model $parent 上级模型对象 + * @param string $morphType 多态字段名 + * @param string $morphKey 外键名 + * @param array $alias 多态别名定义 + * @param string $relation 关联名 + */ + public function __construct(Model $parent, $morphType, $morphKey, $alias = [], $relation = null) + { + $this->parent = $parent; + $this->morphType = $morphType; + $this->morphKey = $morphKey; + $this->alias = $alias; + $this->relation = $relation; + } + + /** + * 获取当前的关联模型类的实例 + * @access public + * @return Model + */ + public function getModel() + { + $morphType = $this->morphType; + $model = $this->parseModel($this->parent->$morphType); + + return (new $model); + } + + /** + * 延迟获取关联数据 + * @access public + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包查询条件 + * @return Model + */ + public function getRelation($subRelation = '', $closure = null) + { + $morphKey = $this->morphKey; + $morphType = $this->morphType; + + // 多态模型 + $model = $this->parseModel($this->parent->$morphType); + + // 主键数据 + $pk = $this->parent->$morphKey; + + $relationModel = (new $model)->relation($subRelation)->find($pk); + + if ($relationModel) { + $relationModel->setParent(clone $this->parent); + } + + return $relationModel; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @param string $joinType JOIN类型 + * @return Query + */ + public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER') + { + return $this->parent; + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $fields 字段 + * @return Query + */ + public function hasWhere($where = [], $fields = null) + { + throw new Exception('relation not support: hasWhere'); + } + + /** + * 解析模型的完整命名空间 + * @access protected + * @param string $model 模型名(或者完整类名) + * @return string + */ + protected function parseModel($model) + { + if (isset($this->alias[$model])) { + $model = $this->alias[$model]; + } + + if (false === strpos($model, '\\')) { + $path = explode('\\', get_class($this->parent)); + array_pop($path); + array_push($path, Loader::parseName($model, 1)); + $model = implode('\\', $path); + } + + return $model; + } + + /** + * 设置多态别名 + * @access public + * @param array $alias 别名定义 + * @return $this + */ + public function setAlias($alias) + { + $this->alias = $alias; + + return $this; + } + + /** + * 移除关联查询参数 + * @access public + * @return $this + */ + public function removeOption() + { + return $this; + } + + /** + * 预载入关联查询 + * @access public + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + * @throws Exception + */ + public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure) + { + $morphKey = $this->morphKey; + $morphType = $this->morphType; + $range = []; + + foreach ($resultSet as $result) { + // 获取关联外键列表 + if (!empty($result->$morphKey)) { + $range[$result->$morphType][] = $result->$morphKey; + } + } + + if (!empty($range)) { + // 关联属性名 + $attr = Loader::parseName($relation); + + foreach ($range as $key => $val) { + // 多态类型映射 + $model = $this->parseModel($key); + $obj = new $model; + $pk = $obj->getPk(); + $list = $obj->all($val, $subRelation); + $data = []; + + foreach ($list as $k => $vo) { + $data[$vo->$pk] = $vo; + } + + foreach ($resultSet as $result) { + if ($key == $result->$morphType) { + // 关联模型 + if (!isset($data[$result->$morphKey])) { + $relationModel = null; + } else { + $relationModel = $data[$result->$morphKey]; + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + } + + $result->setRelation($attr, $relationModel); + } + } + } + } + } + + /** + * 预载入关联查询 + * @access public + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResult(&$result, $relation, $subRelation, $closure) + { + $morphKey = $this->morphKey; + $morphType = $this->morphType; + // 多态类型映射 + $model = $this->parseModel($result->{$this->morphType}); + + $this->eagerlyMorphToOne($model, $relation, $result, $subRelation); + } + + /** + * 关联统计 + * @access public + * @param Model $result 数据对象 + * @param \Closure $closure 闭包 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return integer + */ + public function relationCount($result, $closure, $aggregate = 'count', $field = '*') + {} + + /** + * 多态MorphTo 关联模型预查询 + * @access protected + * @param string $model 关联模型对象 + * @param string $relation 关联名 + * @param Model $result + * @param string $subRelation 子关联 + * @return void + */ + protected function eagerlyMorphToOne($model, $relation, &$result, $subRelation = '') + { + // 预载入关联查询 支持嵌套预载入 + $pk = $this->parent->{$this->morphKey}; + $data = (new $model)->with($subRelation)->find($pk); + + if ($data) { + $data->setParent(clone $result); + $data->isUpdate(true); + } + + $result->setRelation(Loader::parseName($relation), $data ?: null); + } + + /** + * 添加关联数据 + * @access public + * @param Model $model 关联模型对象 + * @param string $type 多态类型 + * @return Model + */ + public function associate($model, $type = '') + { + $morphKey = $this->morphKey; + $morphType = $this->morphType; + $pk = $model->getPk(); + + $this->parent->setAttr($morphKey, $model->$pk); + $this->parent->setAttr($morphType, $type ?: get_class($model)); + $this->parent->save(); + + return $this->parent->setRelation($this->relation, $model); + } + + /** + * 注销关联数据 + * @access public + * @return Model + */ + public function dissociate() + { + $morphKey = $this->morphKey; + $morphType = $this->morphType; + + $this->parent->setAttr($morphKey, null); + $this->parent->setAttr($morphType, null); + $this->parent->save(); + + return $this->parent->setRelation($this->relation, null); + } + +} diff --git a/library/think/model/relation/OneToOne.php b/library/think/model/relation/OneToOne.php new file mode 100644 index 0000000000000000000000000000000000000000..ac5d4e4c43a5668c41d2fcd0907241c654be1a88 --- /dev/null +++ b/library/think/model/relation/OneToOne.php @@ -0,0 +1,342 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use think\db\Query; +use think\Exception; +use think\Loader; +use think\Model; +use think\model\Relation; + +/** + * Class OneToOne + * @package think\model\relation + * + */ +abstract class OneToOne extends Relation +{ + // 预载入方式 0 -JOIN 1 -IN + protected $eagerlyType = 1; + // 当前关联的JOIN类型 + protected $joinType; + // 要绑定的属性 + protected $bindAttr = []; + // 关联名 + protected $relation; + + /** + * 设置join类型 + * @access public + * @param string $type JOIN类型 + * @return $this + */ + public function joinType($type) + { + $this->joinType = $type; + return $this; + } + + /** + * 预载入关联查询(JOIN方式) + * @access public + * @param Query $query 查询对象 + * @param string $relation 关联名 + * @param string $subRelation 子关联 + * @param \Closure $closure 闭包条件 + * @param bool $first + * @return void + */ + public function eagerly(Query $query, $relation, $subRelation, $closure, $first) + { + $name = Loader::parseName(basename(str_replace('\\', '/', get_class($this->parent)))); + + if ($first) { + $table = $query->getTable(); + $query->table([$table => $name]); + + if ($query->getOptions('field')) { + $field = $query->getOptions('field'); + $query->removeOption('field'); + } else { + $field = true; + } + + $query->field($field, false, $table, $name); + } + + // 预载入封装 + $joinTable = $this->query->getTable(); + $joinAlias = $relation; + $query->via($joinAlias); + + if ($this instanceof BelongsTo) { + $query->join([$joinTable => $joinAlias], $name . '.' . $this->foreignKey . '=' . $joinAlias . '.' . $this->localKey, $this->joinType); + } else { + $query->join([$joinTable => $joinAlias], $name . '.' . $this->localKey . '=' . $joinAlias . '.' . $this->foreignKey, $this->joinType); + } + + if ($closure) { + // 执行闭包查询 + $closure($query); + // 使用withField指定获取关联的字段,如 + // $query->where(['id'=>1])->withField('id,name'); + if ($query->getOptions('with_field')) { + $field = $query->getOptions('with_field'); + $query->removeOption('with_field'); + } else { + $field = true; + } + } elseif (isset($this->option['field'])) { + $field = $this->option['field']; + } else { + $field = true; + } + + $query->field($field, false, $joinTable, $joinAlias, $relation . '__'); + } + + /** + * 预载入关联查询(数据集) + * @access protected + * @param array $resultSet + * @param string $relation + * @param string $subRelation + * @param \Closure $closure + * @return mixed + */ + abstract protected function eagerlySet(&$resultSet, $relation, $subRelation, $closure); + + /** + * 预载入关联查询(数据) + * @access protected + * @param Model $result + * @param string $relation + * @param string $subRelation + * @param \Closure $closure + * @return mixed + */ + abstract protected function eagerlyOne(&$result, $relation, $subRelation, $closure); + + /** + * 预载入关联查询(数据集) + * @access public + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure) + { + if (1 == $this->eagerlyType) { + // IN查询 + $this->eagerlySet($resultSet, $relation, $subRelation, $closure); + } else { + // 模型关联组装 + foreach ($resultSet as $result) { + $this->match($this->model, $relation, $result); + } + } + } + + /** + * 预载入关联查询(数据) + * @access public + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param string $subRelation 子关联名 + * @param \Closure $closure 闭包 + * @return void + */ + public function eagerlyResult(&$result, $relation, $subRelation, $closure) + { + if (1 == $this->eagerlyType) { + // IN查询 + $this->eagerlyOne($result, $relation, $subRelation, $closure); + } else { + // 模型关联组装 + $this->match($this->model, $relation, $result); + } + } + + /** + * 保存(新增)当前关联数据对象 + * @access public + * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键 + * @return Model|false + */ + public function save($data) + { + if ($data instanceof Model) { + $data = $data->getData(); + } + + $model = new $this->model; + // 保存关联表数据 + $data[$this->foreignKey] = $this->parent->{$this->localKey}; + + return $model->save($data) ? $model : false; + } + + /** + * 设置预载入方式 + * @access public + * @param integer $type 预载入方式 0 JOIN查询 1 IN查询 + * @return $this + */ + public function setEagerlyType($type) + { + $this->eagerlyType = $type; + + return $this; + } + + /** + * 获取预载入方式 + * @access public + * @return integer + */ + public function getEagerlyType() + { + return $this->eagerlyType; + } + + /** + * 绑定关联表的属性到父模型属性 + * @access public + * @param mixed $attr 要绑定的属性列表 + * @return $this + */ + public function bind($attr) + { + if (is_string($attr)) { + $attr = explode(',', $attr); + } + $this->bindAttr = $attr; + + return $this; + } + + /** + * 获取绑定属性 + * @access public + * @return array + */ + public function getBindAttr() + { + return $this->bindAttr; + } + + /** + * 关联统计 + * @access public + * @param Model $result 数据对象 + * @param \Closure $closure 闭包 + * @param string $aggregate 聚合查询方法 + * @param string $field 字段 + * @return integer + */ + public function relationCount($result, $closure, $aggregate = 'count', $field = '*') + { + throw new Exception('relation not support: ' . $aggregate); + } + + /** + * 一对一 关联模型预查询拼装 + * @access public + * @param string $model 模型名称 + * @param string $relation 关联名 + * @param Model $result 模型对象实例 + * @return void + */ + protected function match($model, $relation, &$result) + { + // 重新组装模型数据 + foreach ($result->getData() as $key => $val) { + if (strpos($key, '__')) { + list($name, $attr) = explode('__', $key, 2); + if ($name == $relation) { + $list[$name][$attr] = $val; + unset($result->$key); + } + } + } + + if (isset($list[$relation])) { + $relationModel = new $model($list[$relation]); + $relationModel->setParent(clone $result); + $relationModel->isUpdate(true); + + if (!empty($this->bindAttr)) { + $this->bindAttr($relationModel, $result, $this->bindAttr); + } + } else { + $relationModel = null; + } + + $result->setRelation(Loader::parseName($relation), $relationModel); + } + + /** + * 绑定关联属性到父模型 + * @access protected + * @param Model $model 关联模型对象 + * @param Model $result 父模型对象 + * @return void + * @throws Exception + */ + protected function bindAttr($model, &$result) + { + foreach ($this->bindAttr as $key => $attr) { + $key = is_numeric($key) ? $attr : $key; + if (isset($result->$key)) { + throw new Exception('bind attr has exists:' . $key); + } else { + $result->setAttr($key, $model ? $model->$attr : null); + } + } + } + + /** + * 一对一 关联模型预查询(IN方式) + * @access public + * @param array $where 关联预查询条件 + * @param string $key 关联键名 + * @param string $relation 关联名 + * @param string $subRelation 子关联 + * @param \Closure $closure + * @return array + */ + protected function eagerlyWhere($where, $key, $relation, $subRelation = '', $closure = null) + { + // 预载入关联查询 支持嵌套预载入 + if ($closure) { + $closure($this->query); + + if ($field = $this->query->getOptions('with_field')) { + $this->query->field($field)->removeOption('with_field'); + } + } + + $list = $this->query->where($where)->with($subRelation)->select(); + + // 组装模型数据 + $data = []; + + foreach ($list as $set) { + $data[$set->$key] = $set; + } + + return $data; + } + +} diff --git a/library/think/paginator/Collection.php b/library/think/paginator/Collection.php deleted file mode 100644 index 82e88272875dea5bfd3435b1e9f81067b7a71a3c..0000000000000000000000000000000000000000 --- a/library/think/paginator/Collection.php +++ /dev/null @@ -1,74 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace think\paginator; - -use Exception; -use think\Paginator; - -/** - * Class Collection - * @package think\paginator - * @method integer total() - * @method integer listRows() - * @method integer currentPage() - * @method string render() - * @method Paginator fragment($fragment) - * @method Paginator appends($key, $value) - * @method integer lastPage() - * @method boolean hasPages() - */ -class Collection extends \think\Collection -{ - - /** @var Paginator */ - protected $paginator; - - public function __construct($items = [], Paginator $paginator = null) - { - $this->paginator = $paginator; - parent::__construct($items); - } - - public static function make($items = [], Paginator $paginator = null) - { - return new static($items, $paginator); - } - - public function toArray() - { - if ($this->paginator) { - try { - $total = $this->total(); - } catch (Exception $e) { - $total = null; - } - - return [ - 'total' => $total, - 'per_page' => $this->listRows(), - 'current_page' => $this->currentPage(), - 'data' => parent::toArray() - ]; - } else { - return parent::toArray(); - } - } - - public function __call($method, $args) - { - if ($this->paginator && method_exists($this->paginator, $method)) { - return call_user_func_array([$this->paginator, $method], $args); - } else { - throw new Exception('method not exists:' . __CLASS__ . '->' . $method); - } - } -} \ No newline at end of file diff --git a/library/think/paginator/driver/Bootstrap.php b/library/think/paginator/driver/Bootstrap.php index 87e1fe489e76dcb24beb5af05574aee0a4ac27b1..ab5315c06608d4d476422bd02df07771372dfce8 100644 --- a/library/think/paginator/driver/Bootstrap.php +++ b/library/think/paginator/driver/Bootstrap.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -57,13 +57,14 @@ class Bootstrap extends Paginator */ protected function getLinks() { - if ($this->simple) + if ($this->simple) { return ''; + } $block = [ 'first' => null, 'slider' => null, - 'last' => null + 'last' => null, ]; $side = 3; @@ -102,7 +103,6 @@ class Bootstrap extends Paginator return $html; } - /** * 渲染分页html * @return mixed @@ -127,7 +127,6 @@ class Bootstrap extends Paginator } } - /** * 生成一个可点击的按钮 * @@ -198,10 +197,10 @@ class Bootstrap extends Paginator */ protected function getPageLinkWrapper($url, $page) { - if ($page == $this->currentPage()) { + if ($this->currentPage() == $page) { return $this->getActivePageWrapper($page); } return $this->getAvailablePageWrapper($url, $page); } -} \ No newline at end of file +} diff --git a/library/think/process/Builder.php b/library/think/process/Builder.php index 826e6745f1be7a1172de30adfac603ba5a0f8abb..da5616397258db3d3862f51016600ce084cdb5e2 100644 --- a/library/think/process/Builder.php +++ b/library/think/process/Builder.php @@ -15,10 +15,9 @@ use think\Process; class Builder { - private $arguments; private $cwd; - private $env = null; + private $env = null; private $input; private $timeout = 60; private $options = []; @@ -155,7 +154,7 @@ class Builder return $this; } - $timeout = (float)$timeout; + $timeout = (float) $timeout; if ($timeout < 0) { throw new \InvalidArgumentException('The timeout value must be a valid positive integer or float number.'); @@ -231,4 +230,4 @@ class Builder return $process; } -} \ No newline at end of file +} diff --git a/library/think/process/Utils.php b/library/think/process/Utils.php index 3ed136a5f4a8943bfcb0495b0dfd2ef622ef0c76..f94c6488e436306a28e1235b6e5003195fd7d7d9 100644 --- a/library/think/process/Utils.php +++ b/library/think/process/Utils.php @@ -60,7 +60,7 @@ class Utils return $input; } if (is_scalar($input)) { - return (string)$input; + return (string) $input; } throw new \InvalidArgumentException(sprintf('%s only accepts strings or stream resources.', $caller)); } @@ -72,4 +72,4 @@ class Utils return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1]; } -} \ No newline at end of file +} diff --git a/library/think/process/exception/Faild.php b/library/think/process/exception/Faild.php index 23df369dee184b301db078d848f1d341f8aec3bb..38647bc11b1f6c82f450e5a7f34f900287ad7f87 100644 --- a/library/think/process/exception/Faild.php +++ b/library/think/process/exception/Faild.php @@ -11,10 +11,9 @@ namespace think\process\exception; - use think\Process; -class Failed extends \RuntimeException +class Faild extends \RuntimeException { private $process; diff --git a/library/traits/think/Instance.php b/library/think/process/exception/Failed.php similarity index 36% rename from library/traits/think/Instance.php rename to library/think/process/exception/Failed.php index 206a941235d8495d20f28cb8422fc5512c34d550..5295082325cf1514440e217130e44aa77ef6b980 100644 --- a/library/traits/think/Instance.php +++ b/library/think/process/exception/Failed.php @@ -2,44 +2,41 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- -// | Author: liu21st +// | Author: yunwuxin <448901948@qq.com> // +---------------------------------------------------------------------- -namespace traits\think; +namespace think\process\exception; -use \think\Exception; +use think\Process; -trait Instance +class Failed extends \RuntimeException { - protected static $instance = null; - /** - * @param array $options - * @return static - */ - public static function instance($options = []) + private $process; + + public function __construct(Process $process) { - if (is_null(self::$instance)) { - self::$instance = new self($options); + if ($process->isSuccessful()) { + throw new \InvalidArgumentException('Expected a failed process, but the given process was successful.'); + } + + $error = sprintf('The command "%s" failed.' . "\nExit Code: %s(%s)", $process->getCommandLine(), $process->getExitCode(), $process->getExitCodeText()); + + if (!$process->isOutputDisabled()) { + $error .= sprintf("\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s", $process->getOutput(), $process->getErrorOutput()); } - return self::$instance; + + parent::__construct($error); + + $this->process = $process; } - // 静态调用 - public static function __callStatic($method, $params) + public function getProcess() { - if (is_null(self::$instance)) { - self::$instance = new self(); - } - $call = substr($method, 1); - if (0 === strpos($method, '_') && is_callable([self::$instance, $call])) { - return call_user_func_array([self::$instance, $call], $params); - } else { - throw new Exception("method not exists:" . $method); - } + return $this->process; } } diff --git a/library/think/process/exception/Timeout.php b/library/think/process/exception/Timeout.php index c085ee8e52724b36318d83612b10c220143d673e..d5f1162f4392ce382d2f4e3f512d6e31db3625a5 100644 --- a/library/think/process/exception/Timeout.php +++ b/library/think/process/exception/Timeout.php @@ -58,4 +58,4 @@ class Timeout extends \RuntimeException throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType)); } } -} \ No newline at end of file +} diff --git a/library/think/process/pipes/Pipes.php b/library/think/process/pipes/Pipes.php index 51da44f31e99805aab4b399d2c82c407b20a9753..82396b8ff8b2318bce56e9f55369780dc053e347 100644 --- a/library/think/process/pipes/Pipes.php +++ b/library/think/process/pipes/Pipes.php @@ -53,7 +53,6 @@ abstract class Pipes */ abstract public function areOpen(); - /** * {@inheritdoc} */ @@ -91,4 +90,4 @@ abstract class Pipes $this->blocked = false; } -} \ No newline at end of file +} diff --git a/library/think/process/pipes/Unix.php b/library/think/process/pipes/Unix.php index abfe61b2be4b64336a8a1fecd87469833bdcea5b..fd99a5d67eba451ea46caef249d613e396fbef66 100644 --- a/library/think/process/pipes/Unix.php +++ b/library/think/process/pipes/Unix.php @@ -25,14 +25,14 @@ class Unix extends Pipes public function __construct($ttyMode, $ptyMode, $input, $disableOutput) { - $this->ttyMode = (bool)$ttyMode; - $this->ptyMode = (bool)$ptyMode; - $this->disableOutput = (bool)$disableOutput; + $this->ttyMode = (bool) $ttyMode; + $this->ptyMode = (bool) $ptyMode; + $this->disableOutput = (bool) $disableOutput; if (is_resource($input)) { $this->input = $input; } else { - $this->inputBuffer = (string)$input; + $this->inputBuffer = (string) $input; } } @@ -134,12 +134,12 @@ class Unix extends Pipes $type = (false !== $found = array_search($pipe, $this->pipes)) ? $found : 'input'; $data = ''; - while ('' !== $dataread = (string)fread($pipe, self::CHUNK_SIZE)) { + while ('' !== $dataread = (string) fread($pipe, self::CHUNK_SIZE)) { $data .= $dataread; } if ('' !== $data) { - if ($type === 'input') { + if ('input' === $type) { $this->inputBuffer .= $data; } else { $read[$type] = $data; @@ -147,7 +147,7 @@ class Unix extends Pipes } if (false === $data || (true === $close && feof($pipe) && '' === $data)) { - if ($type === 'input') { + if ('input' === $type) { $this->input = null; } else { fclose($this->pipes[$type]); @@ -160,7 +160,7 @@ class Unix extends Pipes while (strlen($this->inputBuffer)) { $written = fwrite($w[0], $this->inputBuffer, 2 << 18); // write 512k if ($written > 0) { - $this->inputBuffer = (string)substr($this->inputBuffer, $written); + $this->inputBuffer = (string) substr($this->inputBuffer, $written); } else { break; } @@ -180,7 +180,7 @@ class Unix extends Pipes */ public function areOpen() { - return (bool)$this->pipes; + return (bool) $this->pipes; } /** @@ -193,4 +193,4 @@ class Unix extends Pipes { return new static($process->isTty(), $process->isPty(), $input, $process->isOutputDisabled()); } -} \ No newline at end of file +} diff --git a/library/think/process/pipes/Windows.php b/library/think/process/pipes/Windows.php index 2cc44ca70473b20e5700d1be5335ab6f45a3bbd6..1b8b0d4f2e5c695cf1a778cd6a6b8fb7ec948eb8 100644 --- a/library/think/process/pipes/Windows.php +++ b/library/think/process/pipes/Windows.php @@ -30,7 +30,7 @@ class Windows extends Pipes public function __construct($disableOutput, $input) { - $this->disableOutput = (bool)$disableOutput; + $this->disableOutput = (bool) $disableOutput; if (!$this->disableOutput) { @@ -128,7 +128,7 @@ class Windows extends Pipes */ public function areOpen() { - return (bool)$this->pipes && (bool)$this->fileHandles; + return (bool) $this->pipes && (bool) $this->fileHandles; } /** @@ -196,7 +196,7 @@ class Windows extends Pipes return; } - if (null !== $w && 0 < count($r)) { + if (null !== $r && 0 < count($r)) { $data = ''; while ($dataread = fread($r['input'], self::CHUNK_SIZE)) { $data .= $dataread; @@ -213,7 +213,7 @@ class Windows extends Pipes while (strlen($this->inputBuffer)) { $written = fwrite($w[0], $this->inputBuffer, 2 << 18); if ($written > 0) { - $this->inputBuffer = (string)substr($this->inputBuffer, $written); + $this->inputBuffer = (string) substr($this->inputBuffer, $written); } else { break; } @@ -225,4 +225,4 @@ class Windows extends Pipes unset($this->pipes[0]); } } -} \ No newline at end of file +} diff --git a/library/think/response/Json.php b/library/think/response/Json.php index a137f45397f2c13fc69c2c296b163497e40a7c8f..aa5bbd6fa98e644d47efe5cd94cae3ed40c45d7e 100644 --- a/library/think/response/Json.php +++ b/library/think/response/Json.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -25,19 +25,27 @@ class Json extends Response /** * 处理数据 * @access protected - * @param mixed $data 要处理的数据 + * @param mixed $data 要处理的数据 * @return mixed + * @throws \Exception */ protected function output($data) { - // 返回JSON数据格式到客户端 包含状态信息 - $data = json_encode($data, $this->options['json_encode_param']); - - if ($data === false) { - throw new \InvalidArgumentException(json_last_error_msg()); + try { + // 返回JSON数据格式到客户端 包含状态信息 + $data = json_encode($data, $this->options['json_encode_param']); + + if (false === $data) { + throw new \InvalidArgumentException(json_last_error_msg()); + } + + return $data; + } catch (\Exception $e) { + if ($e->getPrevious()) { + throw $e->getPrevious(); + } + throw $e; } - - return $data; } } diff --git a/library/think/response/Jsonp.php b/library/think/response/Jsonp.php index fda1183a8f9e82d77babbddc1b2961a7c47a28a7..f69e88e1d0f5870b1c5b93b37f0542ea7fc6d8d2 100644 --- a/library/think/response/Jsonp.php +++ b/library/think/response/Jsonp.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,7 +11,6 @@ namespace think\response; -use think\Request; use think\Response; class Jsonp extends Response @@ -28,23 +27,32 @@ class Jsonp extends Response /** * 处理数据 * @access protected - * @param mixed $data 要处理的数据 + * @param mixed $data 要处理的数据 * @return mixed + * @throws \Exception */ protected function output($data) { - // 返回JSON数据格式到客户端 包含状态信息 [当url_common_param为false时是无法获取到$_GET的数据的,故使用Request来获取] - $var_jsonp_handler = Request::instance()->param($this->options['var_jsonp_handler'], ""); - $handler = !empty($var_jsonp_handler) ? $var_jsonp_handler : $this->options['default_jsonp_handler']; + try { + // 返回JSON数据格式到客户端 包含状态信息 [当url_common_param为false时是无法获取到$_GET的数据的,故使用Request来获取] + $var_jsonp_handler = $this->app['request']->param($this->options['var_jsonp_handler'], ""); + $handler = !empty($var_jsonp_handler) ? $var_jsonp_handler : $this->options['default_jsonp_handler']; - $data = json_encode($data, $this->options['json_encode_param']); + $data = json_encode($data, $this->options['json_encode_param']); - if ($data === false) { - throw new \InvalidArgumentException(json_last_error_msg()); - } + if (false === $data) { + throw new \InvalidArgumentException(json_last_error_msg()); + } + + $data = $handler . '(' . $data . ');'; - $data = $handler . '(' . $data . ');'; - return $data; + return $data; + } catch (\Exception $e) { + if ($e->getPrevious()) { + throw $e->getPrevious(); + } + throw $e; + } } } diff --git a/library/think/response/Jump.php b/library/think/response/Jump.php new file mode 100644 index 0000000000000000000000000000000000000000..258448ca4ae5a98a63a942fe8a8cfad69566de13 --- /dev/null +++ b/library/think/response/Jump.php @@ -0,0 +1,32 @@ + +// +---------------------------------------------------------------------- + +namespace think\response; + +use think\Response; + +class Jump extends Response +{ + protected $contentType = 'text/html'; + + /** + * 处理数据 + * @access protected + * @param mixed $data 要处理的数据 + * @return mixed + * @throws \Exception + */ + protected function output($data) + { + $data = $this->app['view']->fetch($this->options['jump_template'], $data); + return $data; + } +} diff --git a/library/think/response/Redirect.php b/library/think/response/Redirect.php index 82a5fe3274fb7cb9f3e8b6d49ecba41460873ebc..62fa83a7aafd42d880ee6302f60417342c13ce03 100644 --- a/library/think/response/Redirect.php +++ b/library/think/response/Redirect.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,10 +11,7 @@ namespace think\response; -use think\Request; use think\Response; -use think\Session; -use think\Url; class Redirect extends Response { @@ -27,71 +24,92 @@ class Redirect extends Response public function __construct($data = '', $code = 302, array $header = [], array $options = []) { parent::__construct($data, $code, $header, $options); + $this->cacheControl('no-cache,must-revalidate'); } /** * 处理数据 * @access protected - * @param mixed $data 要处理的数据 + * @param mixed $data 要处理的数据 * @return mixed */ protected function output($data) { $this->header['Location'] = $this->getTargetUrl(); + return; } /** * 重定向传值(通过Session) * @access protected - * @param string|array $name 变量名或者数组 - * @param mixed $value 值 + * @param string|array $name 变量名或者数组 + * @param mixed $value 值 * @return $this */ public function with($name, $value = null) { + $session = $this->app['session']; + if (is_array($name)) { foreach ($name as $key => $val) { - Session::set($key, $val); + $session->flash($key, $val); } } else { - Session::set($name, $value); + $session->flash($name, $value); } + return $this; } /** * 获取跳转地址 + * @access public * @return string */ public function getTargetUrl() { - return (strpos($this->data, '://') || 0 === strpos($this->data, '/')) ? $this->data : Url::build($this->data, $this->params); + if (strpos($this->data, '://') || (0 === strpos($this->data, '/') && empty($this->params))) { + return $this->data; + } else { + return $this->app['url']->build($this->data, $this->params); + } } public function params($params = []) { $this->params = $params; + return $this; } /** * 记住当前url后跳转 + * @access public + * @return $this */ public function remember() { - Session::set('redirect_url', Request::instance()->url()); + $this->app['session']->set('redirect_url', $this->app['request']->url()); + + return $this; } /** * 跳转到上次记住的url + * @access public + * @return $this */ public function restore() { - if (Session::has('redirect_url')) { - $this->data = Session::get('redirect_url'); - Session::delete('redirect_url'); + $session = $this->app['session']; + + if ($session->has('redirect_url')) { + $this->data = $session->get('redirect_url'); + $session->delete('redirect_url'); } + + return $this; } } diff --git a/library/think/response/View.php b/library/think/response/View.php index 3a5f3660c1791533d1c47183461e9d30a3c2718b..c836ccb5d4cce0cee1f076a159db9bad707a8935 100644 --- a/library/think/response/View.php +++ b/library/think/response/View.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,35 +11,34 @@ namespace think\response; -use think\Config; use think\Response; -use think\View as ViewTemplate; class View extends Response { // 输出参数 - protected $options = []; - protected $vars = []; - protected $replace = []; + protected $options = []; + protected $vars = []; + protected $filter; protected $contentType = 'text/html'; /** * 处理数据 * @access protected - * @param mixed $data 要处理的数据 + * @param mixed $data 要处理的数据 * @return mixed */ protected function output($data) { // 渲染模板输出 - return ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch($data, $this->vars, $this->replace); + return $this->app['view'] + ->filter($this->filter) + ->fetch($data, $this->vars); } /** * 获取视图变量 * @access public - * @param string $name 模板变量 + * @param string $name 模板变量 * @return mixed */ public function getVars($name = null) @@ -54,36 +53,42 @@ class View extends Response /** * 模板变量赋值 * @access public - * @param mixed $name 变量名 - * @param mixed $value 变量值 + * @param mixed $name 变量名 + * @param mixed $value 变量值 * @return $this */ public function assign($name, $value = '') { if (is_array($name)) { $this->vars = array_merge($this->vars, $name); - return $this; } else { $this->vars[$name] = $value; } + return $this; } /** - * 视图内容替换 + * 视图内容过滤 * @access public - * @param string|array $content 被替换内容(支持批量替换) - * @param string $replace 替换内容 + * @param callable $filter * @return $this */ - public function replace($content, $replace = '') + public function filter($filter) { - if (is_array($content)) { - $this->replace = array_merge($this->replace, $content); - } else { - $this->replace[$content] = $replace; - } + $this->filter = $filter; return $this; } + /** + * 检查模板是否存在 + * @access private + * @param string|array $name 参数名 + * @return bool + */ + public function exists($name) + { + return $this->app['view']->exists($name); + } + } diff --git a/library/think/response/Xml.php b/library/think/response/Xml.php index 3a2c59bdc6c67076890728a4966856257f9edbed..9c1681a4a389c29d217b991cc065ee2abccad23f 100644 --- a/library/think/response/Xml.php +++ b/library/think/response/Xml.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,6 +11,8 @@ namespace think\response; +use think\Collection; +use think\Model; use think\Response; class Xml extends Response @@ -34,23 +36,33 @@ class Xml extends Response /** * 处理数据 * @access protected - * @param mixed $data 要处理的数据 + * @param mixed $data 要处理的数据 * @return mixed */ protected function output($data) { + if (is_string($data)) { + if (0 !== strpos($data, 'options['encoding']; + $xml = ""; + $data = $xml . $data; + } + return $data; + } + // XML数据转换 return $this->xmlEncode($data, $this->options['root_node'], $this->options['item_node'], $this->options['root_attr'], $this->options['item_key'], $this->options['encoding']); } /** * XML编码 - * @param mixed $data 数据 - * @param string $root 根节点名 - * @param string $item 数字索引的子节点名 - * @param string $attr 根节点属性 - * @param string $id 数字索引子节点key转换的属性名 - * @param string $encoding 数据编码 + * @access protected + * @param mixed $data 数据 + * @param string $root 根节点名 + * @param string $item 数字索引的子节点名 + * @param string $attr 根节点属性 + * @param string $id 数字索引子节点key转换的属性名 + * @param string $encoding 数据编码 * @return string */ protected function xmlEncode($data, $root, $item, $attr, $id, $encoding) @@ -62,25 +74,33 @@ class Xml extends Response } $attr = implode(' ', $array); } + $attr = trim($attr); $attr = empty($attr) ? '' : " {$attr}"; $xml = ""; $xml .= "<{$root}{$attr}>"; $xml .= $this->dataToXml($data, $item, $id); $xml .= ""; + return $xml; } /** * 数据XML编码 - * @param mixed $data 数据 - * @param string $item 数字索引时的节点名称 - * @param string $id 数字索引key转换为的属性名 + * @access protected + * @param mixed $data 数据 + * @param string $item 数字索引时的节点名称 + * @param string $id 数字索引key转换为的属性名 * @return string */ protected function dataToXml($data, $item, $id) { $xml = $attr = ''; + + if ($data instanceof Collection || $data instanceof Model) { + $data = $data->toArray(); + } + foreach ($data as $key => $val) { if (is_numeric($key)) { $id && $attr = " {$id}=\"{$key}\""; @@ -90,6 +110,7 @@ class Xml extends Response $xml .= (is_array($val) || is_object($val)) ? $this->dataToXml($val, $item, $id) : $val; $xml .= ""; } + return $xml; } } diff --git a/library/think/route/AliasRule.php b/library/think/route/AliasRule.php new file mode 100644 index 0000000000000000000000000000000000000000..daf59fe13ebb9345759d4bf2a67624afeb72b6b5 --- /dev/null +++ b/library/think/route/AliasRule.php @@ -0,0 +1,114 @@ + +// +---------------------------------------------------------------------- + +namespace think\route; + +use think\Route; + +class AliasRule extends Domain +{ + /** + * 架构函数 + * @access public + * @param Route $router 路由实例 + * @param RuleGroup $parent 上级对象 + * @param string $name 路由别名 + * @param string $route 路由绑定 + * @param array $option 路由参数 + */ + public function __construct(Route $router, RuleGroup $parent, $name, $route, $option = []) + { + $this->router = $router; + $this->parent = $parent; + $this->name = $name; + $this->route = $route; + $this->option = $option; + } + + /** + * 检测路由别名 + * @access public + * @param Request $request 请求对象 + * @param string $url 访问地址 + * @param bool $completeMatch 路由是否完全匹配 + * @return Dispatch|false + */ + public function check($request, $url, $completeMatch = false) + { + if ($dispatch = $this->checkCrossDomain($request)) { + // 允许跨域 + return $dispatch; + } + + // 检查参数有效性 + if (!$this->checkOption($this->option, $request)) { + return false; + } + + list($action, $bind) = array_pad(explode('|', $url, 2), 2, ''); + + if (isset($this->option['allow']) && !in_array($action, $this->option['allow'])) { + // 允许操作 + return false; + } elseif (isset($this->option['except']) && in_array($action, $this->option['except'])) { + // 排除操作 + return false; + } + + if (isset($this->option['method'][$action])) { + $this->option['method'] = $this->option['method'][$action]; + } + + // 匹配后执行的行为 + $this->afterMatchGroup($request); + + if ($this->parent) { + // 合并分组参数 + $this->mergeGroupOptions(); + } + + $this->parseBindAppendParam($this->route); + + if (0 === strpos($this->route, '\\')) { + // 路由到类 + return $this->bindToClass($request, $bind, substr($this->route, 1)); + } elseif (0 === strpos($this->route, '@')) { + // 路由到控制器类 + return $this->bindToController($request, $bind, substr($this->route, 1)); + } else { + // 路由到模块/控制器 + return $this->bindToModule($request, $bind, $this->route); + } + } + + /** + * 设置允许的操作方法 + * @access public + * @param array $action 操作方法 + * @return $this + */ + public function allow($action = []) + { + return $this->option('allow', $action); + } + + /** + * 设置排除的操作方法 + * @access public + * @param array $action 操作方法 + * @return $this + */ + public function except($action = []) + { + return $this->option('except', $action); + } + +} diff --git a/library/think/route/Dispatch.php b/library/think/route/Dispatch.php new file mode 100644 index 0000000000000000000000000000000000000000..7f1982cdb69f8f9bb0ccd2f72f59d8355e914f93 --- /dev/null +++ b/library/think/route/Dispatch.php @@ -0,0 +1,353 @@ + +// +---------------------------------------------------------------------- + +namespace think\route; + +use think\Container; +use think\exception\ValidateException; +use think\Request; +use think\Response; + +abstract class Dispatch +{ + /** + * 应用对象 + * @var App + */ + protected $app; + + /** + * 请求对象 + * @var Request + */ + protected $request; + + /** + * 路由规则 + * @var Rule + */ + protected $rule; + + /** + * 调度信息 + * @var mixed + */ + protected $dispatch; + + /** + * 调度参数 + * @var array + */ + protected $param; + + /** + * 状态码 + * @var string + */ + protected $code; + + /** + * 是否进行大小写转换 + * @var bool + */ + protected $convert; + + public function __construct(Request $request, Rule $rule, $dispatch, $param = [], $code = null) + { + $this->request = $request; + $this->rule = $rule; + $this->app = Container::get('app'); + $this->dispatch = $dispatch; + $this->param = $param; + $this->code = $code; + + if (isset($param['convert'])) { + $this->convert = $param['convert']; + } + } + + public function init() + { + // 执行路由后置操作 + if ($this->rule->doAfter()) { + // 设置请求的路由信息 + + // 设置当前请求的参数 + $this->request->setRouteVars($this->rule->getVars()); + $this->request->routeInfo([ + 'rule' => $this->rule->getRule(), + 'route' => $this->rule->getRoute(), + 'option' => $this->rule->getOption(), + 'var' => $this->rule->getVars(), + ]); + + $this->doRouteAfter(); + } + + return $this; + } + + /** + * 检查路由后置操作 + * @access protected + * @return void + */ + protected function doRouteAfter() + { + // 记录匹配的路由信息 + $option = $this->rule->getOption(); + $matches = $this->rule->getVars(); + + // 添加中间件 + if (!empty($option['middleware'])) { + $this->app['middleware']->import($option['middleware']); + } + + // 绑定模型数据 + if (!empty($option['model'])) { + $this->createBindModel($option['model'], $matches); + } + + // 指定Header数据 + if (!empty($option['header'])) { + $header = $option['header']; + $this->app['hook']->add('response_send', function ($response) use ($header) { + $response->header($header); + }); + } + + // 指定Response响应数据 + if (!empty($option['response'])) { + $this->app['hook']->add('response_send', $option['response']); + } + + // 开启请求缓存 + if (isset($option['cache']) && $this->request->isGet()) { + $this->parseRequestCache($option['cache']); + } + + if (!empty($option['append'])) { + $this->request->setRouteVars($option['append']); + } + } + + /** + * 执行路由调度 + * @access public + * @return mixed + */ + public function run() + { + $option = $this->rule->getOption(); + + // 检测路由after行为 + if (!empty($option['after'])) { + $dispatch = $this->checkAfter($option['after']); + + if ($dispatch instanceof Response) { + return $dispatch; + } + } + + // 数据自动验证 + if (isset($option['validate'])) { + $this->autoValidate($option['validate']); + } + + $data = $this->exec(); + + return $this->autoResponse($data); + } + + protected function autoResponse($data) + { + if ($data instanceof Response) { + $response = $data; + } elseif (!is_null($data)) { + // 默认自动识别响应输出类型 + $isAjax = $this->request->isAjax(); + $type = $isAjax ? $this->rule->getConfig('default_ajax_return') : $this->rule->getConfig('default_return_type'); + + $response = Response::create($data, $type); + } else { + $data = ob_get_clean(); + $data = false === $data ? '' : $data; + $status = '' === $data ? 204 : 200; + $response = Response::create($data, '', $status); + } + + return $response; + } + + /** + * 检查路由后置行为 + * @access protected + * @param mixed $after 后置行为 + * @return mixed + */ + protected function checkAfter($after) + { + $this->app['log']->notice('路由后置行为建议使用中间件替代!'); + + $hook = $this->app['hook']; + + $result = null; + + foreach ((array) $after as $behavior) { + $result = $hook->exec($behavior); + + if (!is_null($result)) { + break; + } + } + + // 路由规则重定向 + if ($result instanceof Response) { + return $result; + } + + return false; + } + + /** + * 验证数据 + * @access protected + * @param array $option + * @return void + * @throws ValidateException + */ + protected function autoValidate($option) + { + list($validate, $scene, $message, $batch) = $option; + + if (is_array($validate)) { + // 指定验证规则 + $v = $this->app->validate(); + $v->rule($validate); + } else { + // 调用验证器 + $v = $this->app->validate($validate); + if (!empty($scene)) { + $v->scene($scene); + } + } + + if (!empty($message)) { + $v->message($message); + } + + // 批量验证 + if ($batch) { + $v->batch(true); + } + + if (!$v->check($this->request->param())) { + throw new ValidateException($v->getError()); + } + } + + /** + * 处理路由请求缓存 + * @access protected + * @param Request $request 请求对象 + * @param string|array $cache 路由缓存 + * @return void + */ + protected function parseRequestCache($cache) + { + if (is_array($cache)) { + list($key, $expire, $tag) = array_pad($cache, 3, null); + } else { + $key = str_replace('|', '/', $this->request->url()); + $expire = $cache; + $tag = null; + } + + $this->request->cache($key, $expire, $tag); + } + + /** + * 路由绑定模型实例 + * @access protected + * @param array|\Clousre $bindModel 绑定模型 + * @param array $matches 路由变量 + * @return void + */ + protected function createBindModel($bindModel, $matches) + { + foreach ($bindModel as $key => $val) { + if ($val instanceof \Closure) { + $result = $this->app->invokeFunction($val, $matches); + } else { + $fields = explode('&', $key); + + if (is_array($val)) { + list($model, $exception) = $val; + } else { + $model = $val; + $exception = true; + } + + $where = []; + $match = true; + + foreach ($fields as $field) { + if (!isset($matches[$field])) { + $match = false; + break; + } else { + $where[] = [$field, '=', $matches[$field]]; + } + } + + if ($match) { + $query = strpos($model, '\\') ? $model::where($where) : $this->app->model($model)->where($where); + $result = $query->failException($exception)->find(); + } + } + + if (!empty($result)) { + // 注入容器 + $this->app->instance(get_class($result), $result); + } + } + } + + public function convert($convert) + { + $this->convert = $convert; + + return $this; + } + + public function getDispatch() + { + return $this->dispatch; + } + + public function getParam() + { + return $this->param; + } + + abstract public function exec(); + + public function __sleep() + { + return ['rule', 'dispatch', 'convert', 'param', 'code', 'controller', 'actionName']; + } + + public function __wakeup() + { + $this->app = Container::get('app'); + $this->request = $this->app['request']; + } +} diff --git a/library/think/route/Domain.php b/library/think/route/Domain.php new file mode 100644 index 0000000000000000000000000000000000000000..260ca500ad67c10b0bf1e3ab02c4e78fdc0a3ef0 --- /dev/null +++ b/library/think/route/Domain.php @@ -0,0 +1,235 @@ + +// +---------------------------------------------------------------------- + +namespace think\route; + +use think\Container; +use think\Loader; +use think\Route; +use think\route\dispatch\Callback as CallbackDispatch; +use think\route\dispatch\Controller as ControllerDispatch; +use think\route\dispatch\Module as ModuleDispatch; + +class Domain extends RuleGroup +{ + protected $bind; + + /** + * 架构函数 + * @access public + * @param Route $router 路由对象 + * @param string $name 路由域名 + * @param mixed $rule 域名路由 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + */ + public function __construct(Route $router, $name = '', $rule = null, $option = [], $pattern = []) + { + $this->router = $router; + $this->domain = $name; + $this->option = $option; + $this->rule = $rule; + $this->pattern = $pattern; + } + + /** + * 检测域名路由 + * @access public + * @param Request $request 请求对象 + * @param string $url 访问地址 + * @param bool $completeMatch 路由是否完全匹配 + * @return Dispatch|false + */ + public function check($request, $url, $completeMatch = false) + { + // 检测别名路由 + $result = $this->checkRouteAlias($request, $url); + + if (false !== $result) { + return $result; + } + + // 检测URL绑定 + $result = $this->checkUrlBind($request, $url); + + if (!empty($this->option['append'])) { + $request->setRouteVars($this->option['append']); + unset($this->option['append']); + } + + if (false !== $result) { + return $result; + } + + // 添加域名中间件 + if (!empty($this->option['middleware'])) { + Container::get('middleware')->import($this->option['middleware']); + unset($this->option['middleware']); + } + + return parent::check($request, $url, $completeMatch); + } + + /** + * 设置路由绑定 + * @access public + * @param string $bind 绑定信息 + * @return $this + */ + public function bind($bind) + { + $this->bind = $bind; + $this->router->bind($bind, $this->domain); + + return $this; + } + + /** + * 检测路由别名 + * @access private + * @param Request $request + * @param string $url URL地址 + * @return Dispatch|false + */ + private function checkRouteAlias($request, $url) + { + $alias = strpos($url, '|') ? strstr($url, '|', true) : $url; + + $item = $this->router->getAlias($alias); + + return $item ? $item->check($request, $url) : false; + } + + /** + * 检测URL绑定 + * @access private + * @param Request $request + * @param string $url URL地址 + * @return Dispatch|false + */ + private function checkUrlBind($request, $url) + { + if (!empty($this->bind)) { + $bind = $this->bind; + $this->parseBindAppendParam($bind); + + // 记录绑定信息 + Container::get('app')->log('[ BIND ] ' . var_export($bind, true)); + + // 如果有URL绑定 则进行绑定检测 + $type = substr($bind, 0, 1); + $bind = substr($bind, 1); + + $bindTo = [ + '\\' => 'bindToClass', + '@' => 'bindToController', + ':' => 'bindToNamespace', + ]; + + if (isset($bindTo[$type])) { + return $this->{$bindTo[$type]}($request, $url, $bind); + } + } + + return false; + } + + protected function parseBindAppendParam(&$bind) + { + if (false !== strpos($bind, '?')) { + list($bind, $query) = explode('?', $bind); + parse_str($query, $vars); + $this->append($vars); + } + } + + /** + * 绑定到类 + * @access protected + * @param Request $request + * @param string $url URL地址 + * @param string $class 类名(带命名空间) + * @return CallbackDispatch + */ + protected function bindToClass($request, $url, $class) + { + $array = explode('|', $url, 2); + $action = !empty($array[0]) ? $array[0] : $this->router->config('default_action'); + + if (!empty($array[1])) { + $this->parseUrlParams($request, $array[1]); + } + + return new CallbackDispatch($request, $this, [$class, $action]); + } + + /** + * 绑定到命名空间 + * @access protected + * @param Request $request + * @param string $url URL地址 + * @param string $namespace 命名空间 + * @return CallbackDispatch + */ + protected function bindToNamespace($request, $url, $namespace) + { + $array = explode('|', $url, 3); + $class = !empty($array[0]) ? $array[0] : $this->router->config('default_controller'); + $method = !empty($array[1]) ? $array[1] : $this->router->config('default_action'); + + if (!empty($array[2])) { + $this->parseUrlParams($request, $array[2]); + } + + return new CallbackDispatch($request, $this, [$namespace . '\\' . Loader::parseName($class, 1), $method]); + } + + /** + * 绑定到控制器类 + * @access protected + * @param Request $request + * @param string $url URL地址 + * @param string $controller 控制器名 (支持带模块名 index/user ) + * @return ControllerDispatch + */ + protected function bindToController($request, $url, $controller) + { + $array = explode('|', $url, 2); + $action = !empty($array[0]) ? $array[0] : $this->router->config('default_action'); + + if (!empty($array[1])) { + $this->parseUrlParams($request, $array[1]); + } + + return new ControllerDispatch($request, $this, $controller . '/' . $action); + } + + /** + * 绑定到模块/控制器 + * @access protected + * @param Request $request + * @param string $url URL地址 + * @param string $controller 控制器类名(带命名空间) + * @return ModuleDispatch + */ + protected function bindToModule($request, $url, $controller) + { + $array = explode('|', $url, 2); + $action = !empty($array[0]) ? $array[0] : $this->router->config('default_action'); + + if (!empty($array[1])) { + $this->parseUrlParams($request, $array[1]); + } + + return new ModuleDispatch($request, $this, $controller . '/' . $action); + } + +} diff --git a/library/think/route/Resource.php b/library/think/route/Resource.php new file mode 100644 index 0000000000000000000000000000000000000000..5d0d34a082e2dc2a252759252b58c6f86590c372 --- /dev/null +++ b/library/think/route/Resource.php @@ -0,0 +1,155 @@ + +// +---------------------------------------------------------------------- + +namespace think\route; + +use think\Route; + +class Resource extends RuleGroup +{ + // 资源路由名称 + protected $resource; + + // REST路由方法定义 + protected $rest = []; + + /** + * 架构函数 + * @access public + * @param Route $router 路由对象 + * @param RuleGroup $parent 上级对象 + * @param string $name 资源名称 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @param array $rest 资源定义 + */ + public function __construct(Route $router, RuleGroup $parent = null, $name = '', $route = '', $option = [], $pattern = [], $rest = []) + { + $this->router = $router; + $this->parent = $parent; + $this->resource = $name; + $this->route = $route; + $this->name = strpos($name, '.') ? strstr($name, '.', true) : $name; + + $this->setFullName(); + + // 资源路由默认为完整匹配 + $option['complete_match'] = true; + + $this->pattern = $pattern; + $this->option = $option; + $this->rest = $rest; + + if ($this->parent) { + $this->domain = $this->parent->getDomain(); + $this->parent->addRuleItem($this); + } + } + + /** + * 生成资源路由规则 + * @access protected + * @param string $rule 路由规则 + * @param array $option 路由参数 + * @return void + */ + protected function buildResourceRule($rule, $option = []) + { + $origin = $this->router->getGroup(); + $this->router->setGroup($this); + + if (strpos($rule, '.')) { + // 注册嵌套资源路由 + $array = explode('.', $rule); + $last = array_pop($array); + $item = []; + + foreach ($array as $val) { + $item[] = $val . '/<' . (isset($option['var'][$val]) ? $option['var'][$val] : $val . '_id') . '>'; + } + + $rule = implode('/', $item) . '/' . $last; + } + + $prefix = substr($rule, strlen($this->name) + 1); + + // 注册资源路由 + foreach ($this->rest as $key => $val) { + if ((isset($option['only']) && !in_array($key, $option['only'])) + || (isset($option['except']) && in_array($key, $option['except']))) { + continue; + } + + if (isset($last) && strpos($val[1], '') && isset($option['var'][$last])) { + $val[1] = str_replace('', '<' . $option['var'][$last] . '>', $val[1]); + } elseif (strpos($val[1], '') && isset($option['var'][$rule])) { + $val[1] = str_replace('', '<' . $option['var'][$rule] . '>', $val[1]); + } + + $this->addRule(trim($prefix . $val[1], '/'), $this->route . '/' . $val[2], $val[0]); + } + + $this->router->setGroup($origin); + } + + /** + * rest方法定义和修改 + * @access public + * @param string $name 方法名称 + * @param array|bool $resource 资源 + * @return $this + */ + public function rest($name, $resource = []) + { + if (is_array($name)) { + $this->rest = $resource ? $name : array_merge($this->rest, $name); + } else { + $this->rest[$name] = $resource; + } + + return $this; + } + + /** + * 设置资源允许 + * @access public + * @param array $only + * @return $this + */ + public function only($only) + { + return $this->option('only', $only); + } + + /** + * 设置资源排除 + * @access public + * @param array $except + * @return $this + */ + public function except($except) + { + return $this->option('except', $except); + } + + /** + * 设置资源路由的变量 + * @access public + * @param array $vars + * @return $this + */ + public function vars($vars) + { + return $this->option('var', $vars); + } + +} diff --git a/library/think/route/Rule.php b/library/think/route/Rule.php new file mode 100644 index 0000000000000000000000000000000000000000..bdb7f1f261c1b2d6e0b9aaf1db579fd4fa733ec5 --- /dev/null +++ b/library/think/route/Rule.php @@ -0,0 +1,1090 @@ + +// +---------------------------------------------------------------------- + +namespace think\route; + +use think\Container; +use think\Request; +use think\Response; +use think\route\dispatch\Callback as CallbackDispatch; +use think\route\dispatch\Controller as ControllerDispatch; +use think\route\dispatch\Module as ModuleDispatch; +use think\route\dispatch\Redirect as RedirectDispatch; +use think\route\dispatch\Response as ResponseDispatch; +use think\route\dispatch\View as ViewDispatch; + +abstract class Rule +{ + /** + * 路由标识 + * @var string + */ + protected $name; + + /** + * 路由对象 + * @var Route + */ + protected $router; + + /** + * 路由所属分组 + * @var RuleGroup + */ + protected $parent; + + /** + * 路由规则 + * @var mixed + */ + protected $rule; + + /** + * 路由地址 + * @var string|\Closure + */ + protected $route; + + /** + * 请求类型 + * @var string + */ + protected $method; + + /** + * 路由变量 + * @var array + */ + protected $vars = []; + + /** + * 路由参数 + * @var array + */ + protected $option = []; + + /** + * 路由变量规则 + * @var array + */ + protected $pattern = []; + + /** + * 需要和分组合并的路由参数 + * @var array + */ + protected $mergeOptions = ['after', 'before', 'model', 'header', 'response', 'append', 'middleware']; + + /** + * 是否需要后置操作 + * @var bool + */ + protected $doAfter; + + abstract public function check($request, $url, $completeMatch = false); + + /** + * 获取Name + * @access public + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * 获取当前路由规则 + * @access public + * @return string + */ + public function getRule() + { + return $this->rule; + } + + /** + * 获取当前路由地址 + * @access public + * @return mixed + */ + public function getRoute() + { + return $this->route; + } + + /** + * 获取当前路由的请求类型 + * @access public + * @return string + */ + public function getMethod() + { + return strtolower($this->method); + } + + /** + * 获取当前路由的变量 + * @access public + * @return array + */ + public function getVars() + { + return $this->vars; + } + + /** + * 获取路由对象 + * @access public + * @return Route + */ + public function getRouter() + { + return $this->router; + } + + /** + * 路由是否有后置操作 + * @access public + * @return bool + */ + public function doAfter() + { + return $this->doAfter; + } + + /** + * 获取路由分组 + * @access public + * @return RuleGroup|null + */ + public function getParent() + { + return $this->parent; + } + + /** + * 获取变量规则定义 + * @access public + * @param string $name 变量名 + * @return mixed + */ + public function getPattern($name = '') + { + if ('' === $name) { + return $this->pattern; + } + + return isset($this->pattern[$name]) ? $this->pattern[$name] : null; + } + + /** + * 获取路由参数 + * @access public + * @param string $name 变量名 + * @return mixed + */ + public function getConfig($name = '') + { + return $this->router->config($name); + } + + /** + * 获取路由参数定义 + * @access public + * @param string $name 参数名 + * @return mixed + */ + public function getOption($name = '') + { + if ('' === $name) { + return $this->option; + } + + return isset($this->option[$name]) ? $this->option[$name] : null; + } + + /** + * 注册路由参数 + * @access public + * @param string|array $name 参数名 + * @param mixed $value 值 + * @return $this + */ + public function option($name, $value = '') + { + if (is_array($name)) { + $this->option = array_merge($this->option, $name); + } else { + $this->option[$name] = $value; + } + + return $this; + } + + /** + * 注册变量规则 + * @access public + * @param string|array $name 变量名 + * @param string $rule 变量规则 + * @return $this + */ + public function pattern($name, $rule = '') + { + if (is_array($name)) { + $this->pattern = array_merge($this->pattern, $name); + } else { + $this->pattern[$name] = $rule; + } + + return $this; + } + + /** + * 设置标识 + * @access public + * @param string $name 标识名 + * @return $this + */ + public function name($name) + { + $this->name = $name; + + return $this; + } + + /** + * 设置变量 + * @access public + * @param array $vars 变量 + * @return $this + */ + public function vars($vars) + { + $this->vars = $vars; + + return $this; + } + + /** + * 设置路由请求类型 + * @access public + * @param string $method + * @return $this + */ + public function method($method) + { + return $this->option('method', strtolower($method)); + } + + /** + * 设置路由前置行为 + * @access public + * @param array|\Closure $before + * @return $this + */ + public function before($before) + { + return $this->option('before', $before); + } + + /** + * 设置路由后置行为 + * @access public + * @param array|\Closure $after + * @return $this + */ + public function after($after) + { + return $this->option('after', $after); + } + + /** + * 检查后缀 + * @access public + * @param string $ext + * @return $this + */ + public function ext($ext = '') + { + return $this->option('ext', $ext); + } + + /** + * 检查禁止后缀 + * @access public + * @param string $ext + * @return $this + */ + public function denyExt($ext = '') + { + return $this->option('deny_ext', $ext); + } + + /** + * 检查域名 + * @access public + * @param string $domain + * @return $this + */ + public function domain($domain) + { + return $this->option('domain', $domain); + } + + /** + * 设置参数过滤检查 + * @access public + * @param string|array $name + * @param mixed $value + * @return $this + */ + public function filter($name, $value = null) + { + if (is_array($name)) { + $this->option['filter'] = $name; + } else { + $this->option['filter'][$name] = $value; + } + + return $this; + } + + /** + * 绑定模型 + * @access public + * @param array|string $var 路由变量名 多个使用 & 分割 + * @param string|\Closure $model 绑定模型类 + * @param bool $exception 是否抛出异常 + * @return $this + */ + public function model($var, $model = null, $exception = true) + { + if ($var instanceof \Closure) { + $this->option['model'][] = $var; + } elseif (is_array($var)) { + $this->option['model'] = $var; + } elseif (is_null($model)) { + $this->option['model']['id'] = [$var, true]; + } else { + $this->option['model'][$var] = [$model, $exception]; + } + + return $this; + } + + /** + * 附加路由隐式参数 + * @access public + * @param array $append + * @return $this + */ + public function append(array $append = []) + { + if (isset($this->option['append'])) { + $this->option['append'] = array_merge($this->option['append'], $append); + } else { + $this->option['append'] = $append; + } + + return $this; + } + + /** + * 绑定验证 + * @access public + * @param mixed $validate 验证器类 + * @param string $scene 验证场景 + * @param array $message 验证提示 + * @param bool $batch 批量验证 + * @return $this + */ + public function validate($validate, $scene = null, $message = [], $batch = false) + { + $this->option['validate'] = [$validate, $scene, $message, $batch]; + + return $this; + } + + /** + * 绑定Response对象 + * @access public + * @param mixed $response + * @return $this + */ + public function response($response) + { + $this->option['response'][] = $response; + return $this; + } + + /** + * 设置Response Header信息 + * @access public + * @param string|array $name 参数名 + * @param string $value 参数值 + * @return $this + */ + public function header($header, $value = null) + { + if (is_array($header)) { + $this->option['header'] = $header; + } else { + $this->option['header'][$header] = $value; + } + + return $this; + } + + /** + * 指定路由中间件 + * @access public + * @param string|array|\Closure $middleware + * @param mixed $param + * @return $this + */ + public function middleware($middleware, $param = null) + { + if (is_null($param) && is_array($middleware)) { + $this->option['middleware'] = $middleware; + } else { + foreach ((array) $middleware as $item) { + $this->option['middleware'][] = [$item, $param]; + } + } + + return $this; + } + + /** + * 设置路由缓存 + * @access public + * @param array|string $cache + * @return $this + */ + public function cache($cache) + { + return $this->option('cache', $cache); + } + + /** + * 检查URL分隔符 + * @access public + * @param bool $depr + * @return $this + */ + public function depr($depr) + { + return $this->option('param_depr', $depr); + } + + /** + * 是否合并额外参数 + * @access public + * @param bool $merge + * @return $this + */ + public function mergeExtraVars($merge = true) + { + return $this->option('merge_extra_vars', $merge); + } + + /** + * 设置需要合并的路由参数 + * @access public + * @param array $option + * @return $this + */ + public function mergeOptions($option = []) + { + $this->mergeOptions = array_merge($this->mergeOptions, $option); + return $this; + } + + /** + * 检查是否为HTTPS请求 + * @access public + * @param bool $https + * @return $this + */ + public function https($https = true) + { + return $this->option('https', $https); + } + + /** + * 检查是否为AJAX请求 + * @access public + * @param bool $ajax + * @return $this + */ + public function ajax($ajax = true) + { + return $this->option('ajax', $ajax); + } + + /** + * 检查是否为PJAX请求 + * @access public + * @param bool $pjax + * @return $this + */ + public function pjax($pjax = true) + { + return $this->option('pjax', $pjax); + } + + /** + * 检查是否为手机访问 + * @access public + * @param bool $mobile + * @return $this + */ + public function mobile($mobile = true) + { + return $this->option('mobile', $mobile); + } + + /** + * 当前路由到一个模板地址 当使用数组的时候可以传入模板变量 + * @access public + * @param bool|array $view + * @return $this + */ + public function view($view = true) + { + return $this->option('view', $view); + } + + /** + * 当前路由为重定向 + * @access public + * @param bool $redirect 是否为重定向 + * @return $this + */ + public function redirect($redirect = true) + { + return $this->option('redirect', $redirect); + } + + /** + * 设置路由完整匹配 + * @access public + * @param bool $match + * @return $this + */ + public function completeMatch($match = true) + { + return $this->option('complete_match', $match); + } + + /** + * 是否去除URL最后的斜线 + * @access public + * @param bool $remove + * @return $this + */ + public function removeSlash($remove = true) + { + return $this->option('remove_slash', $remove); + } + + /** + * 设置是否允许跨域 + * @access public + * @param bool $allow + * @param array $header + * @return $this + */ + public function allowCrossDomain($allow = true, $header = []) + { + if (!empty($header)) { + $this->header($header); + } + + if ($allow && $this->parent) { + $this->parent->addRuleItem($this, 'options'); + } + + return $this->option('cross_domain', $allow); + } + + /** + * 检查OPTIONS请求 + * @access public + * @param Request $request + * @return Dispatch|void + */ + protected function checkCrossDomain($request) + { + if (!empty($this->option['cross_domain'])) { + + $header = [ + 'Access-Control-Allow-Origin' => '*', + 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE', + 'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With', + ]; + + if (!empty($this->option['header'])) { + $header = array_merge($header, $this->option['header']); + } + + $this->option['header'] = $header; + + if ($request->method(true) == 'OPTIONS') { + return new ResponseDispatch($request, $this, Response::create()->code(204)->header($header)); + } + } + } + + /** + * 设置路由规则全局有效 + * @access public + * @return $this + */ + public function crossDomainRule() + { + if ($this instanceof RuleGroup) { + $method = '*'; + } else { + $method = $this->method; + } + + $this->router->setCrossDomainRule($this, $method); + + return $this; + } + + /** + * 合并分组参数 + * @access protected + * @return void + */ + protected function mergeGroupOptions() + { + $parentOption = $this->parent->getOption(); + // 合并分组参数 + foreach ($this->mergeOptions as $item) { + if (isset($parentOption[$item]) && isset($this->option[$item])) { + $this->option[$item] = array_merge($parentOption[$item], $this->option[$item]); + } + } + + $this->option = array_merge($parentOption, $this->option); + + return $this->option; + } + + /** + * 解析匹配到的规则路由 + * @access public + * @param Request $request 请求对象 + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param string $url URL地址 + * @param array $option 路由参数 + * @param array $matches 匹配的变量 + * @return Dispatch + */ + public function parseRule($request, $rule, $route, $url, $option = [], $matches = []) + { + if (is_string($route) && isset($option['prefix'])) { + // 路由地址前缀 + $route = $option['prefix'] . $route; + } + + // 替换路由地址中的变量 + if (is_string($route) && !empty($matches)) { + foreach ($matches as $key => $val) { + if (false !== strpos($route, '<' . $key . '>')) { + $route = str_replace('<' . $key . '>', $val, $route); + } elseif (false !== strpos($route, ':' . $key)) { + $route = str_replace(':' . $key, $val, $route); + } + } + } + + // 解析额外参数 + $count = substr_count($rule, '/'); + $url = array_slice(explode('|', $url), $count + 1); + $this->parseUrlParams($request, implode('|', $url), $matches); + + $this->route = $route; + $this->vars = $matches; + $this->option = $option; + $this->doAfter = true; + + // 发起路由调度 + return $this->dispatch($request, $route, $option); + } + + /** + * 检查路由前置行为 + * @access protected + * @param mixed $before 前置行为 + * @return mixed + */ + protected function checkBefore($before) + { + $hook = Container::get('hook'); + + foreach ((array) $before as $behavior) { + $result = $hook->exec($behavior); + + if (false === $result) { + return false; + } + } + } + + /** + * 发起路由调度 + * @access protected + * @param Request $request Request对象 + * @param mixed $route 路由地址 + * @param array $option 路由参数 + * @return Dispatch + */ + protected function dispatch($request, $route, $option) + { + if ($route instanceof \Closure) { + // 执行闭包 + $result = new CallbackDispatch($request, $this, $route); + } elseif ($route instanceof Response) { + $result = new ResponseDispatch($request, $this, $route); + } elseif (isset($option['view']) && false !== $option['view']) { + $result = new ViewDispatch($request, $this, $route, is_array($option['view']) ? $option['view'] : []); + } elseif (!empty($option['redirect']) || 0 === strpos($route, '/') || strpos($route, '://')) { + // 路由到重定向地址 + $result = new RedirectDispatch($request, $this, $route, [], isset($option['status']) ? $option['status'] : 301); + } elseif (false !== strpos($route, '\\')) { + // 路由到方法 + $result = $this->dispatchMethod($request, $route); + } elseif (0 === strpos($route, '@')) { + // 路由到控制器 + $result = $this->dispatchController($request, substr($route, 1)); + } else { + // 路由到模块/控制器/操作 + $result = $this->dispatchModule($request, $route); + } + + return $result; + } + + /** + * 解析URL地址为 模块/控制器/操作 + * @access protected + * @param Request $request Request对象 + * @param string $route 路由地址 + * @return CallbackDispatch + */ + protected function dispatchMethod($request, $route) + { + list($path, $var) = $this->parseUrlPath($route); + + $route = str_replace('/', '@', implode('/', $path)); + $method = strpos($route, '@') ? explode('@', $route) : $route; + + return new CallbackDispatch($request, $this, $method, $var); + } + + /** + * 解析URL地址为 模块/控制器/操作 + * @access protected + * @param Request $request Request对象 + * @param string $route 路由地址 + * @return ControllerDispatch + */ + protected function dispatchController($request, $route) + { + list($route, $var) = $this->parseUrlPath($route); + + $result = new ControllerDispatch($request, $this, implode('/', $route), $var); + + $request->setAction(array_pop($route)); + $request->setController($route ? array_pop($route) : $this->getConfig('default_controller')); + $request->setModule($route ? array_pop($route) : $this->getConfig('default_module')); + + return $result; + } + + /** + * 解析URL地址为 模块/控制器/操作 + * @access protected + * @param Request $request Request对象 + * @param string $route 路由地址 + * @return ModuleDispatch + */ + protected function dispatchModule($request, $route) + { + list($path, $var) = $this->parseUrlPath($route); + + $action = array_pop($path); + $controller = !empty($path) ? array_pop($path) : null; + $module = $this->getConfig('app_multi_module') && !empty($path) ? array_pop($path) : null; + $method = $request->method(); + + if ($this->getConfig('use_action_prefix') && $this->router->getMethodPrefix($method)) { + $prefix = $this->router->getMethodPrefix($method); + // 操作方法前缀支持 + $action = 0 !== strpos($action, $prefix) ? $prefix . $action : $action; + } + + // 设置当前请求的路由变量 + $request->setRouteVars($var); + + // 路由到模块/控制器/操作 + return new ModuleDispatch($request, $this, [$module, $controller, $action], ['convert' => false]); + } + + /** + * 路由检查 + * @access protected + * @param array $option 路由参数 + * @param Request $request Request对象 + * @return bool + */ + protected function checkOption($option, Request $request) + { + // 请求类型检测 + if (!empty($option['method'])) { + if (is_string($option['method']) && false === stripos($option['method'], $request->method())) { + return false; + } + } + + // AJAX PJAX 请求检查 + foreach (['ajax', 'pjax', 'mobile'] as $item) { + if (isset($option[$item])) { + $call = 'is' . $item; + if ($option[$item] && !$request->$call() || !$option[$item] && $request->$call()) { + return false; + } + } + } + + // 伪静态后缀检测 + if ($request->url() != '/' && ((isset($option['ext']) && false === stripos('|' . $option['ext'] . '|', '|' . $request->ext() . '|')) + || (isset($option['deny_ext']) && false !== stripos('|' . $option['deny_ext'] . '|', '|' . $request->ext() . '|')))) { + return false; + } + + // 域名检查 + if ((isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()]))) { + return false; + } + + // HTTPS检查 + if ((isset($option['https']) && $option['https'] && !$request->isSsl()) + || (isset($option['https']) && !$option['https'] && $request->isSsl())) { + return false; + } + + // 请求参数检查 + if (isset($option['filter'])) { + foreach ($option['filter'] as $name => $value) { + if ($request->param($name, '', null) != $value) { + return false; + } + } + } + return true; + } + + /** + * 解析URL地址中的参数Request对象 + * @access protected + * @param Request $request + * @param string $rule 路由规则 + * @param array $var 变量 + * @return void + */ + protected function parseUrlParams($request, $url, &$var = []) + { + if ($url) { + if ($this->getConfig('url_param_type')) { + $var += explode('|', $url); + } else { + preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) { + $var[$match[1]] = strip_tags($match[2]); + }, $url); + } + } + } + + /** + * 解析URL的pathinfo参数和变量 + * @access protected + * @param string $url URL地址 + * @return array + */ + protected function parseUrlPath($url) + { + // 分隔符替换 确保路由定义使用统一的分隔符 + $url = str_replace('|', '/', $url); + $url = trim($url, '/'); + $var = []; + + if (false !== strpos($url, '?')) { + // [模块/控制器/操作?]参数1=值1&参数2=值2... + $info = parse_url($url); + $path = explode('/', $info['path']); + parse_str($info['query'], $var); + } elseif (strpos($url, '/')) { + // [模块/控制器/操作] + $path = explode('/', $url); + } elseif (false !== strpos($url, '=')) { + // 参数1=值1&参数2=值2... + parse_str($url, $var); + } else { + $path = [$url]; + } + + return [$path, $var]; + } + + /** + * 生成路由的正则规则 + * @access protected + * @param string $rule 路由规则 + * @param array $match 匹配的变量 + * @param array $pattern 路由变量规则 + * @param array $option 路由参数 + * @param bool $completeMatch 路由是否完全匹配 + * @param string $suffix 路由正则变量后缀 + * @return string + */ + protected function buildRuleRegex($rule, $match, $pattern = [], $option = [], $completeMatch = false, $suffix = '') + { + foreach ($match as $name) { + $replace[] = $this->buildNameRegex($name, $pattern, $suffix); + } + + // 是否区分 / 地址访问 + if ('/' != $rule) { + if (!empty($option['remove_slash'])) { + $rule = rtrim($rule, '/'); + } elseif (substr($rule, -1) == '/') { + $rule = rtrim($rule, '/'); + $hasSlash = true; + } + } + + $regex = str_replace($match, $replace, $rule); + $regex = str_replace([')?/', ')/', ')?-', ')-', '\\\\/'], [')\/', ')\/', ')\-', ')\-', '\/'], $regex); + + if (isset($hasSlash)) { + $regex .= '\/'; + } + + return $regex . ($completeMatch ? '$' : ''); + } + + /** + * 生成路由变量的正则规则 + * @access protected + * @param string $name 路由变量 + * @param string $pattern 变量规则 + * @param string $suffix 路由正则变量后缀 + * @return string + */ + protected function buildNameRegex($name, $pattern, $suffix) + { + $optional = ''; + $slash = substr($name, 0, 1); + + if (in_array($slash, ['/', '-'])) { + $prefix = '\\' . $slash; + $name = substr($name, 1); + $slash = substr($name, 0, 1); + } else { + $prefix = ''; + } + + if ('<' != $slash) { + return $prefix . preg_quote($name, '/'); + } + + if (strpos($name, '?')) { + $name = substr($name, 1, -2); + $optional = '?'; + } elseif (strpos($name, '>')) { + $name = substr($name, 1, -1); + } + + if (isset($pattern[$name])) { + $nameRule = $pattern[$name]; + if (0 === strpos($nameRule, '/') && '/' == substr($nameRule, -1)) { + $nameRule = substr($nameRule, 1, -1); + } + } else { + $nameRule = $this->getConfig('default_route_pattern'); + } + + return '(' . $prefix . '(?<' . $name . $suffix . '>' . $nameRule . '))' . $optional; + } + + /** + * 分析路由规则中的变量 + * @access protected + * @param string $rule 路由规则 + * @return array + */ + protected function parseVar($rule) + { + // 提取路由规则中的变量 + $var = []; + + if (preg_match_all('/<\w+\??>/', $rule, $matches)) { + foreach ($matches[0] as $name) { + $optional = false; + + if (strpos($name, '?')) { + $name = substr($name, 1, -2); + $optional = true; + } else { + $name = substr($name, 1, -1); + } + + $var[$name] = $optional ? 2 : 1; + } + } + + return $var; + } + + /** + * 设置路由参数 + * @access public + * @param string $method 方法名 + * @param array $args 调用参数 + * @return $this + */ + public function __call($method, $args) + { + if (count($args) > 1) { + $args[0] = $args; + } + array_unshift($args, $method); + + return call_user_func_array([$this, 'option'], $args); + } + + public function __sleep() + { + return ['name', 'rule', 'route', 'method', 'vars', 'option', 'pattern', 'doAfter']; + } + + public function __wakeup() + { + $this->router = Container::get('route'); + } +} diff --git a/library/think/route/RuleGroup.php b/library/think/route/RuleGroup.php new file mode 100644 index 0000000000000000000000000000000000000000..19d077db57e8829e28789b8225e79213189586fe --- /dev/null +++ b/library/think/route/RuleGroup.php @@ -0,0 +1,525 @@ + +// +---------------------------------------------------------------------- + +namespace think\route; + +use think\Container; +use think\Exception; +use think\Request; +use think\Response; +use think\Route; +use think\route\dispatch\Response as ResponseDispatch; +use think\route\dispatch\Url as UrlDispatch; + +class RuleGroup extends Rule +{ + // 分组路由(包括子分组) + protected $rules = [ + '*' => [], + 'get' => [], + 'post' => [], + 'put' => [], + 'patch' => [], + 'delete' => [], + 'head' => [], + 'options' => [], + ]; + + // MISS路由 + protected $miss; + + // 自动路由 + protected $auto; + + // 完整名称 + protected $fullName; + + // 所在域名 + protected $domain; + + /** + * 架构函数 + * @access public + * @param Route $router 路由对象 + * @param RuleGroup $parent 上级对象 + * @param string $name 分组名称 + * @param mixed $rule 分组路由 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + */ + public function __construct(Route $router, RuleGroup $parent = null, $name = '', $rule = [], $option = [], $pattern = []) + { + $this->router = $router; + $this->parent = $parent; + $this->rule = $rule; + $this->name = trim($name, '/'); + $this->option = $option; + $this->pattern = $pattern; + + $this->setFullName(); + + if ($this->parent) { + $this->domain = $this->parent->getDomain(); + $this->parent->addRuleItem($this); + } + + if (!empty($option['cross_domain'])) { + $this->router->setCrossDomainRule($this); + } + } + + /** + * 设置分组的路由规则 + * @access public + * @return void + */ + protected function setFullName() + { + if (false !== strpos($this->name, ':')) { + $this->name = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $this->name); + } + + if ($this->parent && $this->parent->getFullName()) { + $this->fullName = $this->parent->getFullName() . ($this->name ? '/' . $this->name : ''); + } else { + $this->fullName = $this->name; + } + } + + /** + * 获取所属域名 + * @access public + * @return string + */ + public function getDomain() + { + return $this->domain; + } + + /** + * 检测分组路由 + * @access public + * @param Request $request 请求对象 + * @param string $url 访问地址 + * @param bool $completeMatch 路由是否完全匹配 + * @return Dispatch|false + */ + public function check($request, $url, $completeMatch = false) + { + if ($dispatch = $this->checkCrossDomain($request)) { + // 跨域OPTIONS请求 + return $dispatch; + } + + // 检查分组有效性 + if (!$this->checkOption($this->option, $request) || !$this->checkUrl($url)) { + return false; + } + + // 解析分组路由 + if ($this instanceof Resource) { + $this->buildResourceRule($this->resource, $this->option); + } elseif ($this->rule) { + if ($this->rule instanceof Response) { + return new ResponseDispatch($request, $this, $this->rule); + } + + $this->parseGroupRule($this->rule); + } + + // 获取当前路由规则 + $method = strtolower($request->method()); + $rules = $this->getMethodRules($method); + + if (count($rules) == 0) { + return false; + } + + if ($this->parent) { + // 合并分组参数 + $this->mergeGroupOptions(); + // 合并分组变量规则 + $this->pattern = array_merge($this->parent->getPattern(), $this->pattern); + } + + if (isset($this->option['complete_match'])) { + $completeMatch = $this->option['complete_match']; + } + + if (!empty($this->option['merge_rule_regex'])) { + // 合并路由正则规则进行路由匹配检查 + $result = $this->checkMergeRuleRegex($request, $rules, $url, $completeMatch); + + if (false !== $result) { + return $result; + } + } + + // 检查分组路由 + foreach ($rules as $key => $item) { + $result = $item->check($request, $url, $completeMatch); + + if (false !== $result) { + return $result; + } + } + + if ($this->auto) { + // 自动解析URL地址 + $result = new UrlDispatch($request, $this, $this->auto . '/' . $url, ['auto_search' => false]); + } elseif ($this->miss && in_array($this->miss->getMethod(), ['*', $method])) { + // 未匹配所有路由的路由规则处理 + $result = $this->miss->parseRule($request, '', $this->miss->getRoute(), $url, $this->miss->getOption()); + } else { + $result = false; + } + + return $result; + } + + /** + * 获取当前请求的路由规则(包括子分组、资源路由) + * @access protected + * @param string $method + * @return array + */ + protected function getMethodRules($method) + { + return array_merge($this->rules[$method], $this->rules['*']); + } + + /** + * 分组URL匹配检查 + * @access protected + * @param string $url + * @return bool + */ + protected function checkUrl($url) + { + if ($this->fullName) { + $pos = strpos($this->fullName, '<'); + + if (false !== $pos) { + $str = substr($this->fullName, 0, $pos); + } else { + $str = $this->fullName; + } + + if ($str && 0 !== stripos(str_replace('|', '/', $url), $str)) { + return false; + } + } + + return true; + } + + /** + * 延迟解析分组的路由规则 + * @access public + * @param bool $lazy 路由是否延迟解析 + * @return $this + */ + public function lazy($lazy = true) + { + if (!$lazy) { + $this->parseGroupRule($this->rule); + $this->rule = null; + } + + return $this; + } + + /** + * 解析分组和域名的路由规则及绑定 + * @access public + * @param mixed $rule 路由规则 + * @return void + */ + public function parseGroupRule($rule) + { + $origin = $this->router->getGroup(); + $this->router->setGroup($this); + + if ($rule instanceof \Closure) { + Container::getInstance()->invokeFunction($rule); + } elseif (is_array($rule)) { + $this->addRules($rule); + } elseif (is_string($rule) && $rule) { + $this->router->bind($rule, $this->domain); + } + + $this->router->setGroup($origin); + } + + /** + * 检测分组路由 + * @access public + * @param Request $request 请求对象 + * @param array $rules 路由规则 + * @param string $url 访问地址 + * @param bool $completeMatch 路由是否完全匹配 + * @return Dispatch|false + */ + protected function checkMergeRuleRegex($request, &$rules, $url, $completeMatch) + { + $depr = $this->router->config('pathinfo_depr'); + $url = $depr . str_replace('|', $depr, $url); + + foreach ($rules as $key => $item) { + if ($item instanceof RuleItem) { + $rule = $depr . str_replace('/', $depr, $item->getRule()); + if ($depr == $rule && $depr != $url) { + unset($rules[$key]); + continue; + } + + $complete = null !== $item->getOption('complete_match') ? $item->getOption('complete_match') : $completeMatch; + + if (false === strpos($rule, '<')) { + if (0 === strcasecmp($rule, $url) || (!$complete && 0 === strncasecmp($rule, $url, strlen($rule)))) { + return $item->checkRule($request, $url, []); + } + + unset($rules[$key]); + continue; + } + + $slash = preg_quote('/-' . $depr, '/'); + + if ($matchRule = preg_split('/[' . $slash . ']<\w+\??>/', $rule, 2)) { + if ($matchRule[0] && 0 !== strncasecmp($rule, $url, strlen($matchRule[0]))) { + unset($rules[$key]); + continue; + } + } + + if (preg_match_all('/[' . $slash . ']??/', $rule, $matches)) { + unset($rules[$key]); + $pattern = array_merge($this->getPattern(), $item->getPattern()); + $option = array_merge($this->getOption(), $item->getOption()); + + $regex[$key] = $this->buildRuleRegex($rule, $matches[0], $pattern, $option, $complete, '_THINK_' . $key); + $items[$key] = $item; + } + } + } + + try { + if (!empty($regex) && preg_match('/^(?:' . implode('|', $regex) . ')/u', $url, $match)) { + $var = []; + foreach ($match as $key => $val) { + if (is_string($key) && '' !== $val) { + list($name, $pos) = explode('_THINK_', $key); + + $var[$name] = $val; + } + } + + if (!isset($pos)) { + foreach ($regex as $key => $item) { + if (0 === strpos(str_replace(['\/', '\-', '\\' . $depr], ['/', '-', $depr], $item), $match[0])) { + $pos = $key; + break; + } + } + } + + return $items[$pos]->checkRule($request, $url, $var); + } + + return false; + } catch (\Exception $e) { + throw new Exception('route pattern error'); + } + } + + /** + * 获取分组的MISS路由 + * @access public + * @return RuleItem|null + */ + public function getMissRule() + { + return $this->miss; + } + + /** + * 获取分组的自动路由 + * @access public + * @return string + */ + public function getAutoRule() + { + return $this->auto; + } + + /** + * 注册自动路由 + * @access public + * @param string $route 路由规则 + * @return void + */ + public function addAutoRule($route) + { + $this->auto = $route; + } + + /** + * 注册MISS路由 + * @access public + * @param string $route 路由地址 + * @param string $method 请求类型 + * @param array $option 路由参数 + * @return RuleItem + */ + public function addMissRule($route, $method = '*', $option = []) + { + // 创建路由规则实例 + $ruleItem = new RuleItem($this->router, $this, null, '', $route, strtolower($method), $option); + + $this->miss = $ruleItem; + + return $ruleItem; + } + + /** + * 添加分组下的路由规则或者子分组 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param string $method 请求类型 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return $this + */ + public function addRule($rule, $route, $method = '*', $option = [], $pattern = []) + { + // 读取路由标识 + if (is_array($rule)) { + $name = $rule[0]; + $rule = $rule[1]; + } elseif (is_string($route)) { + $name = $route; + } else { + $name = null; + } + + $method = strtolower($method); + + if ('/' === $rule || '' === $rule) { + // 首页自动完整匹配 + $rule .= '$'; + } + + // 创建路由规则实例 + $ruleItem = new RuleItem($this->router, $this, $name, $rule, $route, $method, $option, $pattern); + + if (!empty($option['cross_domain'])) { + $this->router->setCrossDomainRule($ruleItem, $method); + } + + $this->addRuleItem($ruleItem, $method); + + return $ruleItem; + } + + /** + * 批量注册路由规则 + * @access public + * @param array $rules 路由规则 + * @param string $method 请求类型 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return void + */ + public function addRules($rules, $method = '*', $option = [], $pattern = []) + { + foreach ($rules as $key => $val) { + if (is_numeric($key)) { + $key = array_shift($val); + } + + if (is_array($val)) { + $route = array_shift($val); + $option = $val ? array_shift($val) : []; + $pattern = $val ? array_shift($val) : []; + } else { + $route = $val; + } + + $this->addRule($key, $route, $method, $option, $pattern); + } + } + + public function addRuleItem($rule, $method = '*') + { + if (strpos($method, '|')) { + $rule->method($method); + $method = '*'; + } + + $this->rules[$method][] = $rule; + + return $this; + } + + /** + * 设置分组的路由前缀 + * @access public + * @param string $prefix + * @return $this + */ + public function prefix($prefix) + { + if ($this->parent && $this->parent->getOption('prefix')) { + $prefix = $this->parent->getOption('prefix') . $prefix; + } + + return $this->option('prefix', $prefix); + } + + /** + * 合并分组的路由规则正则 + * @access public + * @param bool $merge + * @return $this + */ + public function mergeRuleRegex($merge = true) + { + return $this->option('merge_rule_regex', $merge); + } + + /** + * 获取完整分组Name + * @access public + * @return string + */ + public function getFullName() + { + return $this->fullName; + } + + /** + * 获取分组的路由规则 + * @access public + * @param string $method + * @return array + */ + public function getRules($method = '') + { + if ('' === $method) { + return $this->rules; + } + + return isset($this->rules[strtolower($method)]) ? $this->rules[strtolower($method)] : []; + } + +} diff --git a/library/think/route/RuleItem.php b/library/think/route/RuleItem.php new file mode 100644 index 0000000000000000000000000000000000000000..1fd98783c31610eb7ad0dc4a1d8f628180cae686 --- /dev/null +++ b/library/think/route/RuleItem.php @@ -0,0 +1,281 @@ + +// +---------------------------------------------------------------------- + +namespace think\route; + +use think\Container; +use think\Exception; +use think\Route; + +class RuleItem extends Rule +{ + /** + * 架构函数 + * @access public + * @param Route $router 路由实例 + * @param RuleGroup $parent 上级对象 + * @param string $name 路由标识 + * @param string|array $rule 路由规则 + * @param string|\Closure $route 路由地址 + * @param string $method 请求类型 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + */ + public function __construct(Route $router, RuleGroup $parent, $name, $rule, $route, $method = '*', $option = [], $pattern = []) + { + $this->router = $router; + $this->parent = $parent; + $this->name = $name; + $this->route = $route; + $this->method = $method; + $this->option = $option; + $this->pattern = $pattern; + + $this->setRule($rule); + + if (!empty($option['cross_domain'])) { + $this->router->setCrossDomainRule($this, $method); + } + } + + /** + * 路由规则预处理 + * @access public + * @param string $rule 路由规则 + * @return void + */ + public function setRule($rule) + { + if ('$' == substr($rule, -1, 1)) { + // 是否完整匹配 + $rule = substr($rule, 0, -1); + + $this->option['complete_match'] = true; + } + + $rule = '/' != $rule ? ltrim($rule, '/') : ''; + + if ($this->parent && $prefix = $this->parent->getFullName()) { + $rule = $prefix . ($rule ? '/' . ltrim($rule, '/') : ''); + } + + if (false !== strpos($rule, ':')) { + $this->rule = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $rule); + } else { + $this->rule = $rule; + } + + // 生成路由标识的快捷访问 + $this->setRuleName(); + } + + /** + * 检查后缀 + * @access public + * @param string $ext + * @return $this + */ + public function ext($ext = '') + { + $this->option('ext', $ext); + $this->setRuleName(true); + + return $this; + } + + /** + * 设置别名 + * @access public + * @param string $name + * @return $this + */ + public function name($name) + { + $this->name = $name; + $this->setRuleName(true); + + return $this; + } + + /** + * 设置路由标识 用于URL反解生成 + * @access protected + * @param bool $first 是否插入开头 + * @return void + */ + protected function setRuleName($first = false) + { + if ($this->name) { + $vars = $this->parseVar($this->rule); + $name = strtolower($this->name); + + if (isset($this->option['ext'])) { + $suffix = $this->option['ext']; + } elseif ($this->parent->getOption('ext')) { + $suffix = $this->parent->getOption('ext'); + } else { + $suffix = null; + } + + $value = [$this->rule, $vars, $this->parent->getDomain(), $suffix, $this->method]; + + Container::get('rule_name')->set($name, $value, $first); + } + } + + /** + * 检测路由 + * @access public + * @param Request $request 请求对象 + * @param string $url 访问地址 + * @param array $match 匹配路由变量 + * @param bool $completeMatch 路由是否完全匹配 + * @return Dispatch|false + */ + public function checkRule($request, $url, $match = null, $completeMatch = false) + { + if ($dispatch = $this->checkCrossDomain($request)) { + // 允许跨域 + return $dispatch; + } + + // 检查参数有效性 + if (!$this->checkOption($this->option, $request)) { + return false; + } + + // 合并分组参数 + $option = $this->mergeGroupOptions(); + + // 检查前置行为 + if (isset($option['before']) && false === $this->checkBefore($option['before'])) { + return false; + } + + $url = $this->urlSuffixCheck($request, $url, $option); + + if (is_null($match)) { + $match = $this->match($url, $option, $completeMatch); + } + + if (false !== $match) { + return $this->parseRule($request, $this->rule, $this->route, $url, $option, $match); + } + + return false; + } + + /** + * 检测路由(含路由匹配) + * @access public + * @param Request $request 请求对象 + * @param string $url 访问地址 + * @param string $depr 路径分隔符 + * @param bool $completeMatch 路由是否完全匹配 + * @return Dispatch|false + */ + public function check($request, $url, $completeMatch = false) + { + return $this->checkRule($request, $url, null, $completeMatch); + } + + /** + * URL后缀及Slash检查 + * @access protected + * @param Request $request 请求对象 + * @param string $url 访问地址 + * @param array $option 路由参数 + * @return string + */ + protected function urlSuffixCheck($request, $url, $option = []) + { + // 是否区分 / 地址访问 + if (!empty($option['remove_slash']) && '/' != $this->rule) { + $this->rule = rtrim($this->rule, '/'); + $url = rtrim($url, '|'); + } + + if (isset($option['ext'])) { + // 路由ext参数 优先于系统配置的URL伪静态后缀参数 + $url = preg_replace('/\.(' . $request->ext() . ')$/i', '', $url); + } + + return $url; + } + + /** + * 检测URL和规则路由是否匹配 + * @access private + * @param string $url URL地址 + * @param array $option 路由参数 + * @param bool $completeMatch 路由是否完全匹配 + * @return array|false + */ + private function match($url, $option, $completeMatch) + { + if (isset($option['complete_match'])) { + $completeMatch = $option['complete_match']; + } + + $pattern = array_merge($this->parent->getPattern(), $this->pattern); + $depr = $this->router->config('pathinfo_depr'); + + // 检查完整规则定义 + if (isset($pattern['__url__']) && !preg_match(0 === strpos($pattern['__url__'], '/') ? $pattern['__url__'] : '/^' . $pattern['__url__'] . '/', str_replace('|', $depr, $url))) { + return false; + } + + $var = []; + $url = $depr . str_replace('|', $depr, $url); + $rule = $depr . str_replace('/', $depr, $this->rule); + + if ($depr == $rule && $depr != $url) { + return false; + } + + if (false === strpos($rule, '<')) { + if (0 === strcasecmp($rule, $url) || (!$completeMatch && 0 === strncasecmp($rule . $depr, $url . $depr, strlen($rule . $depr)))) { + return $var; + } + return false; + } + + $slash = preg_quote('/-' . $depr, '/'); + + if ($matchRule = preg_split('/[' . $slash . ']?<\w+\??>/', $rule, 2)) { + if ($matchRule[0] && 0 !== strncasecmp($rule, $url, strlen($matchRule[0]))) { + return false; + } + } + + if (preg_match_all('/[' . $slash . ']??/', $rule, $matches)) { + $regex = $this->buildRuleRegex($rule, $matches[0], $pattern, $option, $completeMatch); + + try { + if (!preg_match('/^' . $regex . ($completeMatch ? '$' : '') . '/u', $url, $match)) { + return false; + } + } catch (\Exception $e) { + throw new Exception('route pattern error'); + } + + foreach ($match as $key => $val) { + if (is_string($key)) { + $var[$key] = $val; + } + } + } + + // 成功匹配后返回URL中的动态变量数组 + return $var; + } + +} diff --git a/tests/thinkphp/library/think/cache/driver/memcachedTest.php b/library/think/route/RuleName.php similarity index 32% rename from tests/thinkphp/library/think/cache/driver/memcachedTest.php rename to library/think/route/RuleName.php index 58bcbd88d5586e8aff5899d793a3323a2807e56c..11fc194291a2d008621790ed924f91b7600f91eb 100644 --- a/tests/thinkphp/library/think/cache/driver/memcachedTest.php +++ b/library/think/route/RuleName.php @@ -1,72 +1,79 @@ - -// +---------------------------------------------------------------------- - -/** - * Memcached缓存驱动测试 - * @author 7IN0SAN9 - */ - -namespace tests\thinkphp\library\think\cache\driver; - -class memcachedTest extends cacheTestCase -{ - private $_cacheInstance = null; - /** - * 基境缓存类型 - */ - protected function setUp() - { - if (!extension_loaded("memcached") && !extension_loaded('memcache')) { - $this->markTestSkipped("Memcached或Memcache没有安装,已跳过测试!"); - } - \think\Cache::connect(array('type' => 'memcached', 'expire' => 2)); - } - /** - * @return ApcCache - */ - protected function getCacheInstance() - { - if (null === $this->_cacheInstance) { - $this->_cacheInstance = new \think\cache\driver\Memcached(['length' => 3]); - } - return $this->_cacheInstance; - } - /** - * 缓存过期测试《提出来测试,因为目前看通不过缓存过期测试,所以还需研究》 - * @return mixed - * @access public - */ - public function testExpire() - { - } - - public function testStaticCall() - { - } - - /** - * 测试缓存自增 - * @return mixed - * @access public - */ - public function testInc() - { - } - - /** - * 测试缓存自减 - * @return mixed - * @access public - */ - public function testDec() - { - } -} + +// +---------------------------------------------------------------------- + +namespace think\route; + +class RuleName +{ + protected $item = []; + + /** + * 注册路由标识 + * @access public + * @param string $name 路由标识 + * @param array $value 路由规则 + * @param bool $first 是否置顶 + * @return void + */ + public function set($name, $value, $first = false) + { + if ($first && isset($this->item[$name])) { + array_unshift($this->item[$name], $value); + } else { + $this->item[$name][] = $value; + } + } + + /** + * 导入路由标识 + * @access public + * @param array $name 路由标识 + * @return void + */ + public function import($item) + { + $this->item = $item; + } + + /** + * 根据路由标识获取路由信息(用于URL生成) + * @access public + * @param string $name 路由标识 + * @param string $domain 域名 + * @return array|null + */ + public function get($name = null, $domain = null) + { + if (is_null($name)) { + return $this->item; + } + + $name = strtolower($name); + + if (isset($this->item[$name])) { + if (is_null($domain)) { + $result = $this->item[$name]; + } else { + $result = []; + foreach ($this->item[$name] as $item) { + if ($item[2] == $domain) { + $result[] = $item; + } + } + } + } else { + $result = null; + } + + return $result; + } + +} diff --git a/tests/thinkphp/library/think/dbTest.php b/library/think/route/dispatch/Callback.php similarity index 61% rename from tests/thinkphp/library/think/dbTest.php rename to library/think/route/dispatch/Callback.php index 9019917e7d92d4e7d14e90aa3f7549d3ce9e06b5..ca76fc99363e0c4594f59df486b92259551b0277 100644 --- a/tests/thinkphp/library/think/dbTest.php +++ b/library/think/route/dispatch/Callback.php @@ -2,26 +2,25 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st // +---------------------------------------------------------------------- -/** - * Db类测试 - */ +namespace think\route\dispatch; -namespace tests\thinkphp\library\think; +use think\route\Dispatch; -use \think\Db; - -class dbTest extends \PHPUnit_Framework_TestCase +class Callback extends Dispatch { - public function testConnect() + public function exec() { - Db::connect('mysql://root@127.0.0.1/test#utf8')->execute('show databases'); + // 执行回调方法 + $vars = array_merge($this->request->param(), $this->param); + + return $this->app->invoke($this->dispatch, $vars); } } diff --git a/library/think/route/dispatch/Controller.php b/library/think/route/dispatch/Controller.php new file mode 100644 index 0000000000000000000000000000000000000000..1de82992630ab81d2243429e52f2190a4a7046af --- /dev/null +++ b/library/think/route/dispatch/Controller.php @@ -0,0 +1,30 @@ + +// +---------------------------------------------------------------------- + +namespace think\route\dispatch; + +use think\route\Dispatch; + +class Controller extends Dispatch +{ + public function exec() + { + // 执行控制器的操作方法 + $vars = array_merge($this->request->param(), $this->param); + + return $this->app->action( + $this->dispatch, $vars, + $this->rule->getConfig('url_controller_layer'), + $this->rule->getConfig('controller_suffix') + ); + } + +} diff --git a/library/think/route/dispatch/Module.php b/library/think/route/dispatch/Module.php new file mode 100644 index 0000000000000000000000000000000000000000..4224b362f58f84616de7438cbea9f5d884341716 --- /dev/null +++ b/library/think/route/dispatch/Module.php @@ -0,0 +1,136 @@ + +// +---------------------------------------------------------------------- + +namespace think\route\dispatch; + +use ReflectionMethod; +use think\exception\ClassNotFoundException; +use think\exception\HttpException; +use think\Loader; +use think\Request; +use think\route\Dispatch; + +class Module extends Dispatch +{ + protected $controller; + protected $actionName; + + public function init() + { + parent::init(); + + $result = $this->dispatch; + + if (is_string($result)) { + $result = explode('/', $result); + } + + if ($this->rule->getConfig('app_multi_module')) { + // 多模块部署 + $module = strip_tags(strtolower($result[0] ?: $this->rule->getConfig('default_module'))); + $bind = $this->rule->getRouter()->getBind(); + $available = false; + + if ($bind && preg_match('/^[a-z]/is', $bind)) { + // 绑定模块 + list($bindModule) = explode('/', $bind); + if (empty($result[0])) { + $module = $bindModule; + } + $available = true; + } elseif (!in_array($module, $this->rule->getConfig('deny_module_list')) && is_dir($this->app->getAppPath() . $module)) { + $available = true; + } elseif ($this->rule->getConfig('empty_module')) { + $module = $this->rule->getConfig('empty_module'); + $available = true; + } + + // 模块初始化 + if ($module && $available) { + // 初始化模块 + $this->request->setModule($module); + $this->app->init($module); + } else { + throw new HttpException(404, 'module not exists:' . $module); + } + } + + // 是否自动转换控制器和操作名 + $convert = is_bool($this->convert) ? $this->convert : $this->rule->getConfig('url_convert'); + // 获取控制器名 + $controller = strip_tags($result[1] ?: $this->rule->getConfig('default_controller')); + $this->controller = $convert ? strtolower($controller) : $controller; + + // 获取操作名 + $this->actionName = strip_tags($result[2] ?: $this->rule->getConfig('default_action')); + + // 设置当前请求的控制器、操作 + $this->request + ->setController(Loader::parseName($this->controller, 1)) + ->setAction($this->actionName); + + return $this; + } + + public function exec() + { + // 监听module_init + $this->app['hook']->listen('module_init'); + + try { + // 实例化控制器 + $instance = $this->app->controller($this->controller, + $this->rule->getConfig('url_controller_layer'), + $this->rule->getConfig('controller_suffix'), + $this->rule->getConfig('empty_controller')); + } catch (ClassNotFoundException $e) { + throw new HttpException(404, 'controller not exists:' . $e->getClass()); + } + + $this->app['middleware']->controller(function (Request $request, $next) use ($instance) { + // 获取当前操作名 + $action = $this->actionName . $this->rule->getConfig('action_suffix'); + + if (is_callable([$instance, $action])) { + // 执行操作方法 + $call = [$instance, $action]; + + // 严格获取当前操作方法名 + $reflect = new ReflectionMethod($instance, $action); + $methodName = $reflect->getName(); + $suffix = $this->rule->getConfig('action_suffix'); + $actionName = $suffix ? substr($methodName, 0, -strlen($suffix)) : $methodName; + $this->request->setAction($actionName); + + // 自动获取请求变量 + $vars = $this->rule->getConfig('url_param_type') + ? $this->request->route() + : $this->request->param(); + } elseif (is_callable([$instance, '_empty'])) { + // 空操作 + $call = [$instance, '_empty']; + $vars = [$this->actionName]; + $reflect = new ReflectionMethod($instance, '_empty'); + } else { + // 操作不存在 + throw new HttpException(404, 'method not exists:' . get_class($instance) . '->' . $action . '()'); + } + + $this->app['hook']->listen('action_begin', $call); + + $data = $this->app->invokeReflectMethod($instance, $reflect, $vars); + + return $this->autoResponse($data); + }); + + return $this->app['middleware']->dispatch($this->request, 'controller'); + } +} diff --git a/tests/application/route.php b/library/think/route/dispatch/Redirect.php similarity index 63% rename from tests/application/route.php rename to library/think/route/dispatch/Redirect.php index 45bcf79d6a1bba871becd2c2170ec01c8bc0f000..fae2c9a65f3414c8f568caf74f385f3fbdb72f4c 100644 --- a/tests/application/route.php +++ b/library/think/route/dispatch/Redirect.php @@ -2,21 +2,22 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st // +---------------------------------------------------------------------- -// $Id$ -return [ - '__pattern__' => [ - 'name' => '\w+', - ], - '[hello]' => [ - ':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']], - ':name' => ['index/hello', ['method' => 'post']], - ], +namespace think\route\dispatch; -]; +use think\Response; +use think\route\Dispatch; + +class Redirect extends Dispatch +{ + public function exec() + { + return Response::create($this->dispatch, 'redirect')->code($this->code); + } +} diff --git a/start.php b/library/think/route/dispatch/Response.php similarity index 69% rename from start.php rename to library/think/route/dispatch/Response.php index 2d5179149ae1105d06a712e6a22e0c4161362935..66f4e5abb9ba18b10c467e5176213c3f464aaf9a 100644 --- a/start.php +++ b/library/think/route/dispatch/Response.php @@ -2,17 +2,22 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st // +---------------------------------------------------------------------- -namespace think; +namespace think\route\dispatch; -// ThinkPHP 引导文件 -// 加载基础文件 -require __DIR__ . '/base.php'; -// 执行应用 -App::run()->send(); +use think\route\Dispatch; + +class Response extends Dispatch +{ + public function exec() + { + return $this->dispatch; + } + +} diff --git a/library/think/route/dispatch/Url.php b/library/think/route/dispatch/Url.php new file mode 100644 index 0000000000000000000000000000000000000000..90a865b49e904d76f2f1ae38a575a827ff908ac0 --- /dev/null +++ b/library/think/route/dispatch/Url.php @@ -0,0 +1,193 @@ + +// +---------------------------------------------------------------------- + +namespace think\route\dispatch; + +use think\exception\HttpException; +use think\Loader; +use think\route\Dispatch; + +class Url extends Dispatch +{ + public function init() + { + // 解析默认的URL规则 + $result = $this->parseUrl($this->dispatch); + + return (new Module($this->request, $this->rule, $result))->init(); + } + + public function exec() + {} + + /** + * 解析URL地址 + * @access protected + * @param string $url URL + * @return array + */ + protected function parseUrl($url) + { + $depr = $this->rule->getConfig('pathinfo_depr'); + $bind = $this->rule->getRouter()->getBind(); + + if (!empty($bind) && preg_match('/^[a-z]/is', $bind)) { + $bind = str_replace('/', $depr, $bind); + // 如果有模块/控制器绑定 + $url = $bind . ('.' != substr($bind, -1) ? $depr : '') . ltrim($url, $depr); + } + + list($path, $var) = $this->parseUrlPath($url); + if (empty($path)) { + return [null, null, null]; + } + + // 解析模块 + $module = $this->rule->getConfig('app_multi_module') ? array_shift($path) : null; + + if ($this->param['auto_search']) { + $controller = $this->autoFindController($module, $path); + } else { + // 解析控制器 + $controller = !empty($path) ? array_shift($path) : null; + } + + // 解析操作 + $action = !empty($path) ? array_shift($path) : null; + + // 解析额外参数 + if ($path) { + if ($this->rule->getConfig('url_param_type')) { + $var += $path; + } else { + preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) { + $var[$match[1]] = strip_tags($match[2]); + }, implode('|', $path)); + } + } + + $panDomain = $this->request->panDomain(); + + if ($panDomain && $key = array_search('*', $var)) { + // 泛域名赋值 + $var[$key] = $panDomain; + } + + // 设置当前请求的参数 + $this->request->setRouteVars($var); + + // 封装路由 + $route = [$module, $controller, $action]; + + if ($this->hasDefinedRoute($route, $bind)) { + throw new HttpException(404, 'invalid request:' . str_replace('|', $depr, $url)); + } + + return $route; + } + + /** + * 检查URL是否已经定义过路由 + * @access protected + * @param string $route 路由信息 + * @param string $bind 绑定信息 + * @return bool + */ + protected function hasDefinedRoute($route, $bind) + { + list($module, $controller, $action) = $route; + + // 检查地址是否被定义过路由 + $name = strtolower($module . '/' . Loader::parseName($controller, 1) . '/' . $action); + + $name2 = ''; + + if (empty($module) || $module == $bind) { + $name2 = strtolower(Loader::parseName($controller, 1) . '/' . $action); + } + + $host = $this->request->host(true); + + if ($this->rule->getRouter()->getName($name, $host) || $this->rule->getRouter()->getName($name2, $host)) { + return true; + } + + return false; + } + + /** + * 自动定位控制器类 + * @access protected + * @param string $module 模块名 + * @param array $path URL + * @return string + */ + protected function autoFindController($module, &$path) + { + $dir = $this->app->getAppPath() . ($module ? $module . '/' : '') . $this->rule->getConfig('url_controller_layer'); + $suffix = $this->app->getSuffix() || $this->rule->getConfig('controller_suffix') ? ucfirst($this->rule->getConfig('url_controller_layer')) : ''; + + $item = []; + $find = false; + + foreach ($path as $val) { + $item[] = $val; + $file = $dir . '/' . str_replace('.', '/', $val) . $suffix . '.php'; + $file = pathinfo($file, PATHINFO_DIRNAME) . '/' . Loader::parseName(pathinfo($file, PATHINFO_FILENAME), 1) . '.php'; + if (is_file($file)) { + $find = true; + break; + } else { + $dir .= '/' . Loader::parseName($val); + } + } + + if ($find) { + $controller = implode('.', $item); + $path = array_slice($path, count($item)); + } else { + $controller = array_shift($path); + } + + return $controller; + } + + /** + * 解析URL的pathinfo参数和变量 + * @access private + * @param string $url URL地址 + * @return array + */ + private function parseUrlPath($url) + { + // 分隔符替换 确保路由定义使用统一的分隔符 + $url = str_replace('|', '/', $url); + $url = trim($url, '/'); + $var = []; + + if (false !== strpos($url, '?')) { + // [模块/控制器/操作?]参数1=值1&参数2=值2... + $info = parse_url($url); + $path = explode('/', $info['path']); + parse_str($info['query'], $var); + } elseif (strpos($url, '/')) { + // [模块/控制器/操作] + $path = explode('/', $url); + } elseif (false !== strpos($url, '=')) { + // 参数1=值1&参数2=值2... + parse_str($url, $var); + } else { + $path = [$url]; + } + + return [$path, $var]; + } +} diff --git a/tests/mock.php b/library/think/route/dispatch/View.php similarity index 57% rename from tests/mock.php rename to library/think/route/dispatch/View.php index 28471ee28bdd845d77c0b626bc95c1aba3d0fbaa..ea3ef11b024d6a46fc797638b73d53e75f4835c1 100644 --- a/tests/mock.php +++ b/library/think/route/dispatch/View.php @@ -1,20 +1,26 @@ - -// +---------------------------------------------------------------------- - -// 测试入口文件 -$_SERVER['REQUEST_METHOD'] = 'GET'; -// 定义项目测试基础路径 -define('TEST_PATH', __DIR__ . '/'); -// 定义项目路径 -define('APP_PATH', __DIR__ . '/application/'); -// 加载框架基础文件 -require __DIR__ . '/../base.php'; -\think\Loader::addNamespace('tests', TEST_PATH); + +// +---------------------------------------------------------------------- + +namespace think\route\dispatch; + +use think\Response; +use think\route\Dispatch; + +class View extends Dispatch +{ + public function exec() + { + // 渲染模板输出 + $vars = array_merge($this->request->param(), $this->param); + + return Response::create($this->dispatch, 'view')->assign($vars); + } +} diff --git a/library/think/session/driver/Memcache.php b/library/think/session/driver/Memcache.php index 2c040271bcad5bb5b86faa3fa2588f1326076be7..40d7bb8251359ea7c93118ab595e2a413555851b 100644 --- a/library/think/session/driver/Memcache.php +++ b/library/think/session/driver/Memcache.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,10 +11,10 @@ namespace think\session\driver; -use SessionHandler; +use SessionHandlerInterface; use think\Exception; -class Memcache extends SessionHandler +class Memcache implements SessionHandlerInterface { protected $handler = null; protected $config = [ @@ -34,8 +34,8 @@ class Memcache extends SessionHandler /** * 打开Session * @access public - * @param string $savePath - * @param mixed $sessName + * @param string $savePath + * @param mixed $sessName */ public function open($savePath, $sessName) { @@ -43,13 +43,17 @@ class Memcache extends SessionHandler if (!extension_loaded('memcache')) { throw new Exception('not support:memcache'); } + $this->handler = new \Memcache; + // 支持集群 $hosts = explode(',', $this->config['host']); $ports = explode(',', $this->config['port']); + if (empty($ports[0])) { $ports[0] = 11211; } + // 建立连接 foreach ((array) $hosts as $i => $host) { $port = isset($ports[$i]) ? $ports[$i] : $ports[0]; @@ -57,6 +61,7 @@ class Memcache extends SessionHandler $this->handler->addServer($host, $port, $this->config['persistent'], 1, $this->config['timeout']) : $this->handler->addServer($host, $port, $this->config['persistent'], 1); } + return true; } @@ -69,24 +74,26 @@ class Memcache extends SessionHandler $this->gc(ini_get('session.gc_maxlifetime')); $this->handler->close(); $this->handler = null; + return true; } /** * 读取Session * @access public - * @param string $sessID + * @param string $sessID */ public function read($sessID) { - return $this->handler->get($this->config['session_name'] . $sessID); + return (string) $this->handler->get($this->config['session_name'] . $sessID); } /** * 写入Session * @access public - * @param string $sessID - * @param String $sessData + * @param string $sessID + * @param string $sessData + * @return bool */ public function write($sessID, $sessData) { @@ -96,7 +103,8 @@ class Memcache extends SessionHandler /** * 删除Session * @access public - * @param string $sessID + * @param string $sessID + * @return bool */ public function destroy($sessID) { @@ -106,7 +114,8 @@ class Memcache extends SessionHandler /** * Session 垃圾回收 * @access public - * @param string $sessMaxLifeTime + * @param string $sessMaxLifeTime + * @return true */ public function gc($sessMaxLifeTime) { diff --git a/library/think/session/driver/Memcached.php b/library/think/session/driver/Memcached.php index 4187204a5ed6b7401ef8e8bf00224ec40816f26e..074b2ff73658cd7fcfe84921572a013a2b5a401c 100644 --- a/library/think/session/driver/Memcached.php +++ b/library/think/session/driver/Memcached.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,10 +11,10 @@ namespace think\session\driver; -use SessionHandler; +use SessionHandlerInterface; use think\Exception; -class Memcached extends SessionHandler +class Memcached implements SessionHandlerInterface { protected $handler = null; protected $config = [ @@ -35,8 +35,8 @@ class Memcached extends SessionHandler /** * 打开Session * @access public - * @param string $savePath - * @param mixed $sessName + * @param string $savePath + * @param mixed $sessName */ public function open($savePath, $sessName) { @@ -44,27 +44,35 @@ class Memcached extends SessionHandler if (!extension_loaded('memcached')) { throw new Exception('not support:memcached'); } + $this->handler = new \Memcached; + // 设置连接超时时间(单位:毫秒) if ($this->config['timeout'] > 0) { $this->handler->setOption(\Memcached::OPT_CONNECT_TIMEOUT, $this->config['timeout']); } + // 支持集群 $hosts = explode(',', $this->config['host']); $ports = explode(',', $this->config['port']); + if (empty($ports[0])) { $ports[0] = 11211; } + // 建立连接 $servers = []; foreach ((array) $hosts as $i => $host) { $servers[] = [$host, (isset($ports[$i]) ? $ports[$i] : $ports[0]), 1]; } + $this->handler->addServers($servers); + if ('' != $this->config['username']) { $this->handler->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); $this->handler->setSaslAuthData($this->config['username'], $this->config['password']); } + return true; } @@ -77,24 +85,26 @@ class Memcached extends SessionHandler $this->gc(ini_get('session.gc_maxlifetime')); $this->handler->quit(); $this->handler = null; + return true; } /** * 读取Session * @access public - * @param string $sessID + * @param string $sessID */ public function read($sessID) { - return $this->handler->get($this->config['session_name'] . $sessID); + return (string) $this->handler->get($this->config['session_name'] . $sessID); } /** * 写入Session * @access public - * @param string $sessID - * @param String $sessData + * @param string $sessID + * @param string $sessData + * @return bool */ public function write($sessID, $sessData) { @@ -104,7 +114,8 @@ class Memcached extends SessionHandler /** * 删除Session * @access public - * @param string $sessID + * @param string $sessID + * @return bool */ public function destroy($sessID) { @@ -114,7 +125,8 @@ class Memcached extends SessionHandler /** * Session 垃圾回收 * @access public - * @param string $sessMaxLifeTime + * @param string $sessMaxLifeTime + * @return true */ public function gc($sessMaxLifeTime) { diff --git a/library/think/session/driver/Redis.php b/library/think/session/driver/Redis.php index e3dc998312fd972a6a3b3242f71119b3d109efab..a521ca0f716cffe82196b5215425ab34b5a3b722 100644 --- a/library/think/session/driver/Redis.php +++ b/library/think/session/driver/Redis.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -11,10 +11,10 @@ namespace think\session\driver; -use SessionHandler; +use SessionHandlerInterface; use think\Exception; -class Redis extends SessionHandler +class Redis implements SessionHandlerInterface { /** @var \Redis */ protected $handler = null; @@ -37,29 +37,38 @@ class Redis extends SessionHandler /** * 打开Session * @access public - * @param string $savePath - * @param mixed $sessName + * @param string $savePath + * @param mixed $sessName * @return bool * @throws Exception */ public function open($savePath, $sessName) { - // 检测php环境 - if (!extension_loaded('redis')) { - throw new Exception('not support:redis'); - } - $this->handler = new \Redis; + if (extension_loaded('redis')) { + $this->handler = new \Redis; - // 建立连接 - $func = $this->config['persistent'] ? 'pconnect' : 'connect'; - $this->handler->$func($this->config['host'], $this->config['port'], $this->config['timeout']); + // 建立连接 + $func = $this->config['persistent'] ? 'pconnect' : 'connect'; + $this->handler->$func($this->config['host'], $this->config['port'], $this->config['timeout']); - if ('' != $this->config['password']) { - $this->handler->auth($this->config['password']); - } + if ('' != $this->config['password']) { + $this->handler->auth($this->config['password']); + } - if (0 != $this->config['select']) { - $this->handler->select($this->config['select']); + if (0 != $this->config['select']) { + $this->handler->select($this->config['select']); + } + } elseif (class_exists('\Predis\Client')) { + $params = []; + foreach ($this->config as $key => $val) { + if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication'])) { + $params[$key] = $val; + unset($this->config[$key]); + } + } + $this->handler = new \Predis\Client($this->config, $params); + } else { + throw new \BadFunctionCallException('not support: redis'); } return true; @@ -74,25 +83,26 @@ class Redis extends SessionHandler $this->gc(ini_get('session.gc_maxlifetime')); $this->handler->close(); $this->handler = null; + return true; } /** * 读取Session * @access public - * @param string $sessID - * @return bool|string + * @param string $sessID + * @return string */ public function read($sessID) { - return $this->handler->get($this->config['session_name'] . $sessID); + return (string) $this->handler->get($this->config['session_name'] . $sessID); } /** * 写入Session * @access public - * @param string $sessID - * @param String $sessData + * @param string $sessID + * @param string $sessData * @return bool */ public function write($sessID, $sessData) @@ -107,22 +117,61 @@ class Redis extends SessionHandler /** * 删除Session * @access public - * @param string $sessID - * @return bool|void + * @param string $sessID + * @return bool */ public function destroy($sessID) { - $this->handler->delete($this->config['session_name'] . $sessID); + return $this->handler->delete($this->config['session_name'] . $sessID) > 0; } /** * Session 垃圾回收 * @access public - * @param string $sessMaxLifeTime + * @param string $sessMaxLifeTime * @return bool */ public function gc($sessMaxLifeTime) { return true; } + + /** + * Redis Session 驱动的加锁机制 + * @access public + * @param string $sessID 用于加锁的sessID + * @param integer $timeout 默认过期时间 + * @return bool + */ + public function lock($sessID, $timeout = 10) + { + if (null == $this->handler) { + $this->open('', ''); + } + + $lockKey = 'LOCK_PREFIX_' . $sessID; + // 使用setnx操作加锁 + $isLock = $this->handler->setnx($lockKey, 1); + if ($isLock) { + // 设置过期时间,防止死任务的出现 + $this->handler->expire($lockKey, $timeout); + return true; + } + + return false; + } + + /** + * Redis Session 驱动的解锁机制 + * @access public + * @param string $sessID 用于解锁的sessID + */ + public function unlock($sessID) + { + if (null == $this->handler) { + $this->open('', ''); + } + + $this->handler->del('LOCK_PREFIX_' . $sessID); + } } diff --git a/library/think/template/TagLib.php b/library/think/template/TagLib.php index 101593bfa02270417177bbeb731b7f7c5e862da4..3653b7d2f322882d5743bdc8be92088ab50bf884 100644 --- a/library/think/template/TagLib.php +++ b/library/think/template/TagLib.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -70,7 +70,7 @@ class TagLib /** * 架构函数 * @access public - * @param \stdClass $template 模板引擎对象 + * @param \stdClass $template 模板引擎对象 */ public function __construct($template) { @@ -88,6 +88,7 @@ class TagLib { $tags = []; $lib = $lib ? strtolower($lib) . ':' : ''; + foreach ($this->tags as $name => $val) { $close = !isset($val['close']) || $val['close'] ? 1 : 0; $tags[$close][$lib . $name] = $name; @@ -136,11 +137,14 @@ class TagLib // 对应的标签名 $name = $tags[1][$node['name']]; $alias = $lib . $name != $node['name'] ? ($lib ? strstr($node['name'], $lib) : $node['name']) : ''; + // 解析标签属性 $attrs = $this->parseAttr($node['begin'][0], $name, $alias); $method = 'tag' . $name; + // 读取标签库中对应的标签内容 replace[0]用来替换标签头,replace[1]用来替换标签尾 $replace = explode($break, $this->$method($attrs, $break)); + if (count($replace) > 1) { while ($beginArray) { $begin = end($beginArray); @@ -160,6 +164,7 @@ class TagLib $beginArray[] = ['pos' => $node['begin'][1], 'len' => strlen($node['begin'][0]), 'str' => $replace[0]]; } } + while ($beginArray) { $begin = array_pop($beginArray); // 替换标签头部 @@ -180,22 +185,24 @@ class TagLib return $this->$method($attrs, ''); }, $content); } + return; } /** * 按标签生成正则 - * @access private + * @access public * @param array|string $tags 标签名 * @param boolean $close 是否为闭合标签 * @return string */ - private function getRegex($tags, $close) + public function getRegex($tags, $close) { $begin = $this->tpl->config('taglib_begin'); $end = $this->tpl->config('taglib_end'); $single = strlen(ltrim($begin, '\\')) == 1 && strlen(ltrim($end, '\\')) == 1 ? true : false; $tagName = is_array($tags) ? implode('|', $tags) : $tags; + if ($single) { if ($close) { // 如果是闭合标签 @@ -211,25 +218,28 @@ class TagLib $regex = $begin . '(' . $tagName . ')\b(?>(?:(?!' . $end . ').)*)' . $end; } } + return '/' . $regex . '/is'; } /** * 分析标签属性 正则方式 * @access public - * @param string $str 标签属性字符串 - * @param string $name 标签名 - * @param string $alias 别名 + * @param string $str 标签属性字符串 + * @param string $name 标签名 + * @param string $alias 别名 * @return array */ public function parseAttr($str, $name, $alias = '') { $regex = '/\s+(?>(?P[\w-]+)\s*)=(?>\s*)([\"\'])(?P(?:(?!\\2).)*)\\2/is'; $result = []; + if (preg_match_all($regex, $str, $matches)) { foreach ($matches['name'] as $key => $val) { $result[$val] = $matches['value'][$key]; } + if (!isset($this->tags[$name])) { // 检测是否存在别名定义 foreach ($this->tags as $key => $val) { @@ -251,6 +261,7 @@ class TagLib $result[$type] = $alias; } } + if (!empty($tag['must'])) { $must = explode(',', $tag['must']); foreach ($must as $name) { @@ -264,8 +275,8 @@ class TagLib if (!empty($this->tags[$name]['expression'])) { static $_taglibs; if (!isset($_taglibs[$name])) { - $_taglibs[$name][0] = strlen(ltrim($this->tpl->config('taglib_begin'), '\\') . $name); - $_taglibs[$name][1] = strlen(ltrim($this->tpl->config('taglib_end'), '\\')); + $_taglibs[$name][0] = strlen($this->tpl->config('taglib_begin_origin') . $name); + $_taglibs[$name][1] = strlen($this->tpl->config('taglib_end_origin')); } $result['expression'] = substr($str, $_taglibs[$name][0], -$_taglibs[$name][1]); // 清除自闭合标签尾部/ @@ -275,6 +286,7 @@ class TagLib throw new Exception('tag error:' . $name); } } + return $result; } @@ -289,8 +301,10 @@ class TagLib if (strpos($condition, ':')) { $condition = ' ' . substr(strstr($condition, ':'), 1); } + $condition = str_ireplace(array_keys($this->comparison), array_values($this->comparison), $condition); $this->tpl->parseVar($condition); + // $this->tpl->parseVarFunction($condition); // XXX: 此句能解析表达式中用|分隔的函数,但表达式中如果有|、||这样的逻辑运算就产生了歧异 return $condition; } @@ -298,12 +312,13 @@ class TagLib /** * 自动识别构建变量 * @access public - * @param string $name 变量描述 + * @param string $name 变量描述 * @return string */ public function autoBuildVar(&$name) { $flag = substr($name, 0, 1); + if (':' == $flag) { // 以:开头为函数调用,解析前去掉: $name = substr($name, 1); @@ -313,11 +328,14 @@ class TagLib if (defined($name)) { return $name; } + // 不以$开头并且也不是常量,自动补上$前缀 $name = '$' . $name; } + $this->tpl->parseVar($name); - $this->tpl->parseVarFunction($name); + $this->tpl->parseVarFunction($name, false); + return $name; } @@ -326,7 +344,6 @@ class TagLib * @access public * @return array */ - // 获取标签定义 public function getTags() { return $this->tags; diff --git a/library/think/template/driver/File.php b/library/think/template/driver/File.php index 1cd041afd33befffb575320f5ff1bc150057cb1c..3b96a0f3ba927d910532b632e7c07e30389cb73e 100644 --- a/library/think/template/driver/File.php +++ b/library/think/template/driver/File.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -15,19 +15,24 @@ use think\Exception; class File { + protected $cacheFile; + /** * 写入编译缓存 - * @param string $cacheFile 缓存的文件名 - * @param string $content 缓存的内容 + * @access public + * @param string $cacheFile 缓存的文件名 + * @param string $content 缓存的内容 * @return void|array */ public function write($cacheFile, $content) { // 检测模板目录 $dir = dirname($cacheFile); + if (!is_dir($dir)) { mkdir($dir, 0755, true); } + // 生成模板缓存文件 if (false === file_put_contents($cacheFile, $content)) { throw new Exception('cache write error:' . $cacheFile, 11602); @@ -36,24 +41,29 @@ class File /** * 读取编译编译 - * @param string $cacheFile 缓存的文件名 - * @param array $vars 变量数组 + * @access public + * @param string $cacheFile 缓存的文件名 + * @param array $vars 变量数组 * @return void */ public function read($cacheFile, $vars = []) { + $this->cacheFile = $cacheFile; + if (!empty($vars) && is_array($vars)) { // 模板阵列变量分解成为独立变量 extract($vars, EXTR_OVERWRITE); } + //载入模版缓存文件 - include $cacheFile; + include $this->cacheFile; } /** * 检查编译缓存是否有效 - * @param string $cacheFile 缓存的文件名 - * @param int $cacheTime 缓存时间 + * @access public + * @param string $cacheFile 缓存的文件名 + * @param int $cacheTime 缓存时间 * @return boolean */ public function check($cacheFile, $cacheTime) @@ -62,10 +72,12 @@ class File if (!file_exists($cacheFile)) { return false; } - if (0 != $cacheTime && $_SERVER['REQUEST_TIME'] > filemtime($cacheFile) + $cacheTime) { + + if (0 != $cacheTime && time() > filemtime($cacheFile) + $cacheTime) { // 缓存是否在有效期 return false; } + return true; } } diff --git a/library/think/template/taglib/Cx.php b/library/think/template/taglib/Cx.php index b15c7bba0e05b6e74dda3275f318c407b4027e65..ad741f289ab3a3809442ef6863b97a223b8168f3 100644 --- a/library/think/template/taglib/Cx.php +++ b/library/think/template/taglib/Cx.php @@ -56,8 +56,8 @@ class Cx extends Taglib * 格式: * {php}echo $name{/php} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagPhp($tag, $content) @@ -74,8 +74,8 @@ class Cx extends Taglib * {user.email} * {/volist} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string|void */ public function tagVolist($tag, $content) @@ -90,6 +90,7 @@ class Cx extends Taglib // 允许使用函数设定数据集 {$vo.name} $parseStr = 'autoBuildVar($name); $parseStr .= '$_result=' . $name . ';'; @@ -98,13 +99,15 @@ class Cx extends Taglib $name = $this->autoBuildVar($name); } - $parseStr .= 'if(is_array(' . $name . ') || ' . $name . ' instanceof \think\Collection): $' . $key . ' = 0;'; + $parseStr .= 'if(is_array(' . $name . ') || ' . $name . ' instanceof \think\Collection || ' . $name . ' instanceof \think\Paginator): $' . $key . ' = 0;'; + // 设置了输出数组长度 if (0 != $offset || 'null' != $length) { $parseStr .= '$__LIST__ = is_array(' . $name . ') ? array_slice(' . $name . ',' . $offset . ',' . $length . ', true) : ' . $name . '->slice(' . $offset . ',' . $length . ', true); '; } else { $parseStr .= ' $__LIST__ = ' . $name . ';'; } + $parseStr .= 'if( count($__LIST__)==0 ) : echo "' . $empty . '" ;'; $parseStr .= 'else: '; $parseStr .= 'foreach($__LIST__ as $key=>$' . $id . '): '; @@ -116,6 +119,7 @@ class Cx extends Taglib if (!empty($parseStr)) { return $parseStr; } + return; } @@ -126,8 +130,8 @@ class Cx extends Taglib * {user.username} * {/foreach} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string|void */ public function tagForeach($tag, $content) @@ -141,6 +145,7 @@ class Cx extends Taglib $parseStr .= ''; return $parseStr; } + $name = $tag['name']; $key = !empty($tag['key']) ? $tag['key'] : 'key'; $item = !empty($tag['id']) ? $tag['id'] : $tag['item']; @@ -149,6 +154,7 @@ class Cx extends Taglib $length = !empty($tag['length']) && is_numeric($tag['length']) ? intval($tag['length']) : 'null'; $parseStr = 'autoBuildVar($name); } - $parseStr .= 'if(is_array(' . $name . ') || ' . $name . ' instanceof \think\Collection): '; + + $parseStr .= 'if(is_array(' . $name . ') || ' . $name . ' instanceof \think\Collection || ' . $name . ' instanceof \think\Paginator): '; + // 设置了输出数组长度 if (0 != $offset || 'null' != $length) { if (!isset($var)) { @@ -177,7 +185,9 @@ class Cx extends Taglib $index = $tag['index']; $parseStr .= '$' . $index . '=0; '; } + $parseStr .= 'foreach(' . $var . ' as $' . $key . '=>$' . $item . '): '; + // 设置了索引项 if (isset($tag['index'])) { $index = $tag['index']; @@ -187,6 +197,7 @@ class Cx extends Taglib } $parseStr .= '++$' . $index . '; '; } + $parseStr .= '?>'; // 循环体中的内容 $parseStr .= $content; @@ -195,6 +206,7 @@ class Cx extends Taglib if (!empty($parseStr)) { return $parseStr; } + return; } @@ -207,8 +219,8 @@ class Cx extends Taglib * {/if} * 表达式支持 eq neq gt egt lt elt == > >= < <= or and || && * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagIf($tag, $content) @@ -216,6 +228,7 @@ class Cx extends Taglib $condition = !empty($tag['expression']) ? $tag['expression'] : $tag['condition']; $condition = $this->parseCondition($condition); $parseStr = '' . $content . ''; + return $parseStr; } @@ -223,8 +236,8 @@ class Cx extends Taglib * elseif标签解析 * 格式:见if标签 * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagElseif($tag, $content) @@ -232,6 +245,7 @@ class Cx extends Taglib $condition = !empty($tag['expression']) ? $tag['expression'] : $tag['condition']; $condition = $this->parseCondition($condition); $parseStr = ''; + return $parseStr; } @@ -239,12 +253,13 @@ class Cx extends Taglib * else标签解析 * 格式:见if标签 * @access public - * @param array $tag 标签属性 + * @param array $tag 标签属性 * @return string */ public function tagElse($tag) { $parseStr = ''; + return $parseStr; } @@ -257,8 +272,8 @@ class Cx extends Taglib * {default /}other * {/switch} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagSwitch($tag, $content) @@ -266,20 +281,22 @@ class Cx extends Taglib $name = !empty($tag['expression']) ? $tag['expression'] : $tag['name']; $name = $this->autoBuildVar($name); $parseStr = '' . $content . ''; + return $parseStr; } /** * case标签解析 需要配合switch才有效 * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagCase($tag, $content) { - $value = !empty($tag['expression']) ? $tag['expression'] : $tag['value']; + $value = isset($tag['expression']) ? $tag['expression'] : $tag['value']; $flag = substr($value, 0, 1); + if ('$' == $flag || ':' == $flag) { $value = $this->autoBuildVar($value); $value = 'case ' . $value . ':'; @@ -292,11 +309,14 @@ class Cx extends Taglib } else { $value = 'case "' . $value . '":'; } + $parseStr = '' . $content; $isBreak = isset($tag['break']) ? $tag['break'] : ''; + if ('' == $isBreak || $isBreak) { $parseStr .= ''; } + return $parseStr; } @@ -304,13 +324,14 @@ class Cx extends Taglib * default标签解析 需要配合switch才有效 * 使用: {default /}ddfdf * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagDefault($tag) { $parseStr = ''; + return $parseStr; } @@ -319,8 +340,8 @@ class Cx extends Taglib * 用于值的比较 支持 eq neq gt lt egt elt heq nheq 默认是eq * 格式: {compare name="" type="eq" value="" }content{/compare} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagCompare($tag, $content) @@ -330,11 +351,13 @@ class Cx extends Taglib $type = isset($tag['type']) ? $tag['type'] : 'eq'; // 比较类型 $name = $this->autoBuildVar($name); $flag = substr($value, 0, 1); + if ('$' == $flag || ':' == $flag) { $value = $this->autoBuildVar($value); } else { $value = '\'' . $value . '\''; } + switch ($type) { case 'equal': $type = 'eq'; @@ -345,6 +368,7 @@ class Cx extends Taglib } $type = $this->parseCondition(' ' . $type . ' '); $parseStr = '' . $content . ''; + return $parseStr; } @@ -354,8 +378,8 @@ class Cx extends Taglib * 格式: {range name="var|function" value="val" type='in|notin' }content{/range} * example: {range name="a" value="1,2,3" type='in' }content{/range} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagRange($tag, $content) @@ -366,6 +390,7 @@ class Cx extends Taglib $name = $this->autoBuildVar($name); $flag = substr($value, 0, 1); + if ('$' == $flag || ':' == $flag) { $value = $this->autoBuildVar($value); $str = 'is_array(' . $value . ')?' . $value . ':explode(\',\',' . $value . ')'; @@ -373,6 +398,7 @@ class Cx extends Taglib $value = '"' . $value . '"'; $str = 'explode(\',\',' . $value . ')'; } + if ('between' == $type) { $parseStr = '= $_RANGE_VAR_[0] && ' . $name . '<= $_RANGE_VAR_[1]):?>' . $content . ''; } elseif ('notbetween' == $type) { @@ -381,6 +407,7 @@ class Cx extends Taglib $fun = ('in' == $type) ? 'in_array' : '!in_array'; $parseStr = '' . $content . ''; } + return $parseStr; } @@ -389,8 +416,8 @@ class Cx extends Taglib * 如果某个变量已经设置 则输出内容 * 格式: {present name="" }content{/present} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagPresent($tag, $content) @@ -398,6 +425,7 @@ class Cx extends Taglib $name = $tag['name']; $name = $this->autoBuildVar($name); $parseStr = '' . $content . ''; + return $parseStr; } @@ -406,8 +434,8 @@ class Cx extends Taglib * 如果某个变量没有设置,则输出内容 * 格式: {notpresent name="" }content{/notpresent} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagNotpresent($tag, $content) @@ -415,6 +443,7 @@ class Cx extends Taglib $name = $tag['name']; $name = $this->autoBuildVar($name); $parseStr = '' . $content . ''; + return $parseStr; } @@ -423,15 +452,16 @@ class Cx extends Taglib * 如果某个变量为empty 则输出内容 * 格式: {empty name="" }content{/empty} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagEmpty($tag, $content) { $name = $tag['name']; $name = $this->autoBuildVar($name); - $parseStr = 'isEmpty())): ?>' . $content . ''; + $parseStr = 'isEmpty())): ?>' . $content . ''; + return $parseStr; } @@ -440,43 +470,48 @@ class Cx extends Taglib * 如果某个变量不为empty 则输出内容 * 格式: {notempty name="" }content{/notempty} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagNotempty($tag, $content) { $name = $tag['name']; $name = $this->autoBuildVar($name); - $parseStr = 'isEmpty()))): ?>' . $content . ''; + $parseStr = 'isEmpty()))): ?>' . $content . ''; + return $parseStr; } /** * 判断是否已经定义了该常量 * {defined name='TXT'}已定义{/defined} - * @param array $tag - * @param string $content + * @access public + * @param array $tag + * @param string $content * @return string */ public function tagDefined($tag, $content) { $name = $tag['name']; $parseStr = '' . $content . ''; + return $parseStr; } /** * 判断是否没有定义了该常量 * {notdefined name='TXT'}已定义{/notdefined} - * @param array $tag - * @param string $content + * @access public + * @param array $tag + * @param string $content * @return string */ public function tagNotdefined($tag, $content) { $name = $tag['name']; $parseStr = '' . $content . ''; + return $parseStr; } @@ -484,16 +519,18 @@ class Cx extends Taglib * load 标签解析 {load file="/static/js/base.js" /} * 格式:{load file="/static/css/base.css" /} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagLoad($tag, $content) { - $file = isset($tag['file']) ? $tag['file'] : $tag['href']; - $type = isset($tag['type']) ? strtolower($tag['type']) : ''; + $file = isset($tag['file']) ? $tag['file'] : $tag['href']; + $type = isset($tag['type']) ? strtolower($tag['type']) : ''; + $parseStr = ''; $endStr = ''; + // 判断是否存在加载条件 允许使用函数判断(默认为isset) if (isset($tag['value'])) { $name = $tag['value']; @@ -505,6 +542,7 @@ class Cx extends Taglib // 文件方式导入 $array = explode(',', $file); + foreach ($array as $val) { $type = strtolower(substr(strrchr($val, '.'), 1)); switch ($type) { @@ -519,6 +557,7 @@ class Cx extends Taglib break; } } + return $parseStr . $endStr; } @@ -527,20 +566,23 @@ class Cx extends Taglib * 在模板中给某个变量赋值 支持变量赋值 * 格式: {assign name="" value="" /} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagAssign($tag, $content) { $name = $this->autoBuildVar($tag['name']); $flag = substr($tag['value'], 0, 1); + if ('$' == $flag || ':' == $flag) { $value = $this->autoBuildVar($tag['value']); } else { $value = '\'' . $tag['value'] . '\''; } + $parseStr = ''; + return $parseStr; } @@ -549,20 +591,23 @@ class Cx extends Taglib * 在模板中定义常量 支持变量赋值 * 格式: {define name="" value="" /} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagDefine($tag, $content) { $name = '\'' . $tag['name'] . '\''; $flag = substr($tag['value'], 0, 1); + if ('$' == $flag || ':' == $flag) { $value = $this->autoBuildVar($tag['value']); } else { $value = '\'' . $tag['value'] . '\''; } + $parseStr = ''; + return $parseStr; } @@ -573,8 +618,8 @@ class Cx extends Taglib * content * {/for} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagFor($tag, $content) @@ -586,6 +631,7 @@ class Cx extends Taglib $comparison = 'lt'; $name = 'i'; $rand = rand(); //添加随机数,防止嵌套变量冲突 + //获取属性 foreach ($tag as $key => $value) { $value = trim($value); @@ -617,15 +663,16 @@ class Cx extends Taglib $parseStr .= 'for($' . $name . '=$__FOR_START_' . $rand . '__;' . $this->parseCondition('$' . $name . ' ' . $comparison . ' $__FOR_END_' . $rand . '__') . ';$' . $name . '+=' . $step . '){ ?>'; $parseStr .= $content; $parseStr .= ''; + return $parseStr; } - /** - * U函数的tag标签 + /** + * url函数的tag标签 * 格式:{url link="模块/控制器/方法" vars="参数" suffix="true或者false 是否带有后缀" domain="true或者false 是否携带域名" /} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagUrl($tag, $content) @@ -634,6 +681,7 @@ class Cx extends Taglib $vars = isset($tag['vars']) ? $tag['vars'] : ''; $suffix = isset($tag['suffix']) ? $tag['suffix'] : 'true'; $domain = isset($tag['domain']) ? $tag['domain'] : 'false'; + return ''; } @@ -650,8 +698,8 @@ class Cx extends Taglib * {/if} * {/function} * @access public - * @param array $tag 标签属性 - * @param string $content 标签内容 + * @param array $tag 标签属性 + * @param string $content 标签内容 * @return string */ public function tagFunction($tag, $content) @@ -660,14 +708,17 @@ class Cx extends Taglib $vars = !empty($tag['vars']) ? $tag['vars'] : ''; $call = !empty($tag['call']) ? $tag['call'] : ''; $use = ['&$' . $name]; + if (!empty($tag['use'])) { foreach (explode(',', $tag['use']) as $val) { $use[] = '&' . ltrim(trim($val), '&'); } } + $parseStr = '' . $content . '' : '?>'; + return $parseStr; } } diff --git a/library/think/validate/ValidateRule.php b/library/think/validate/ValidateRule.php new file mode 100644 index 0000000000000000000000000000000000000000..5253465fad5aad309bbffcbd5fe9ad374ce46431 --- /dev/null +++ b/library/think/validate/ValidateRule.php @@ -0,0 +1,171 @@ + +// +---------------------------------------------------------------------- + +namespace think\validate; + +/** + * Class ValidateRule + * @package think\validate + * @method ValidateRule confirm(mixed $rule, string $msg = '') static 验证是否和某个字段的值一致 + * @method ValidateRule different(mixed $rule, string $msg = '') static 验证是否和某个字段的值是否不同 + * @method ValidateRule egt(mixed $rule, string $msg = '') static 验证是否大于等于某个值 + * @method ValidateRule gt(mixed $rule, string $msg = '') static 验证是否大于某个值 + * @method ValidateRule elt(mixed $rule, string $msg = '') static 验证是否小于等于某个值 + * @method ValidateRule lt(mixed $rule, string $msg = '') static 验证是否小于某个值 + * @method ValidateRule eg(mixed $rule, string $msg = '') static 验证是否等于某个值 + * @method ValidateRule in(mixed $rule, string $msg = '') static 验证是否在范围内 + * @method ValidateRule notIn(mixed $rule, string $msg = '') static 验证是否不在某个范围 + * @method ValidateRule between(mixed $rule, string $msg = '') static 验证是否在某个区间 + * @method ValidateRule notBetween(mixed $rule, string $msg = '') static 验证是否不在某个区间 + * @method ValidateRule length(mixed $rule, string $msg = '') static 验证数据长度 + * @method ValidateRule max(mixed $rule, string $msg = '') static 验证数据最大长度 + * @method ValidateRule min(mixed $rule, string $msg = '') static 验证数据最小长度 + * @method ValidateRule after(mixed $rule, string $msg = '') static 验证日期 + * @method ValidateRule before(mixed $rule, string $msg = '') static 验证日期 + * @method ValidateRule expire(mixed $rule, string $msg = '') static 验证有效期 + * @method ValidateRule allowIp(mixed $rule, string $msg = '') static 验证IP许可 + * @method ValidateRule denyIp(mixed $rule, string $msg = '') static 验证IP禁用 + * @method ValidateRule regex(mixed $rule, string $msg = '') static 使用正则验证数据 + * @method ValidateRule token(mixed $rule='__token__', string $msg = '') static 验证表单令牌 + * @method ValidateRule is(mixed $rule, string $msg = '') static 验证字段值是否为有效格式 + * @method ValidateRule isRequire(mixed $rule, string $msg = '') static 验证字段必须 + * @method ValidateRule isNumber(mixed $rule, string $msg = '') static 验证字段值是否为数字 + * @method ValidateRule isArray(mixed $rule, string $msg = '') static 验证字段值是否为数组 + * @method ValidateRule isInteger(mixed $rule, string $msg = '') static 验证字段值是否为整形 + * @method ValidateRule isFloat(mixed $rule, string $msg = '') static 验证字段值是否为浮点数 + * @method ValidateRule isMobile(mixed $rule, string $msg = '') static 验证字段值是否为手机 + * @method ValidateRule isIdCard(mixed $rule, string $msg = '') static 验证字段值是否为身份证号码 + * @method ValidateRule isChs(mixed $rule, string $msg = '') static 验证字段值是否为中文 + * @method ValidateRule isChsDash(mixed $rule, string $msg = '') static 验证字段值是否为中文字母及下划线 + * @method ValidateRule isChsAlpha(mixed $rule, string $msg = '') static 验证字段值是否为中文和字母 + * @method ValidateRule isChsAlphaNum(mixed $rule, string $msg = '') static 验证字段值是否为中文字母和数字 + * @method ValidateRule isDate(mixed $rule, string $msg = '') static 验证字段值是否为有效格式 + * @method ValidateRule isBool(mixed $rule, string $msg = '') static 验证字段值是否为布尔值 + * @method ValidateRule isAlpha(mixed $rule, string $msg = '') static 验证字段值是否为字母 + * @method ValidateRule isAlphaDash(mixed $rule, string $msg = '') static 验证字段值是否为字母和下划线 + * @method ValidateRule isAlphaNum(mixed $rule, string $msg = '') static 验证字段值是否为字母和数字 + * @method ValidateRule isAccepted(mixed $rule, string $msg = '') static 验证字段值是否为yes, on, 或是 1 + * @method ValidateRule isEmail(mixed $rule, string $msg = '') static 验证字段值是否为有效邮箱格式 + * @method ValidateRule isUrl(mixed $rule, string $msg = '') static 验证字段值是否为有效URL地址 + * @method ValidateRule activeUrl(mixed $rule, string $msg = '') static 验证是否为合格的域名或者IP + * @method ValidateRule ip(mixed $rule, string $msg = '') static 验证是否有效IP + * @method ValidateRule fileExt(mixed $rule, string $msg = '') static 验证文件后缀 + * @method ValidateRule fileMime(mixed $rule, string $msg = '') static 验证文件类型 + * @method ValidateRule fileSize(mixed $rule, string $msg = '') static 验证文件大小 + * @method ValidateRule image(mixed $rule, string $msg = '') static 验证图像文件 + * @method ValidateRule method(mixed $rule, string $msg = '') static 验证请求类型 + * @method ValidateRule dateFormat(mixed $rule, string $msg = '') static 验证时间和日期是否符合指定格式 + * @method ValidateRule unique(mixed $rule, string $msg = '') static 验证是否唯一 + * @method ValidateRule behavior(mixed $rule, string $msg = '') static 使用行为类验证 + * @method ValidateRule filter(mixed $rule, string $msg = '') static 使用filter_var方式验证 + * @method ValidateRule requireIf(mixed $rule, string $msg = '') static 验证某个字段等于某个值的时候必须 + * @method ValidateRule requireCallback(mixed $rule, string $msg = '') static 通过回调方法验证某个字段是否必须 + * @method ValidateRule requireWith(mixed $rule, string $msg = '') static 验证某个字段有值的情况下必须 + * @method ValidateRule must(mixed $rule=null, string $msg = '') static 必须验证 + */ +class ValidateRule +{ + // 验证字段的名称 + protected $title; + + // 当前验证规则 + protected $rule = []; + + // 验证提示信息 + protected $message = []; + + /** + * 添加验证因子 + * @access protected + * @param string $name 验证名称 + * @param mixed $rule 验证规则 + * @param string $msg 提示信息 + * @return $this + */ + protected function addItem($name, $rule = null, $msg = '') + { + if ($rule || 0 === $rule) { + $this->rule[$name] = $rule; + } else { + $this->rule[] = $name; + } + + $this->message[] = $msg; + + return $this; + } + + /** + * 获取验证规则 + * @access public + * @return array + */ + public function getRule() + { + return $this->rule; + } + + /** + * 获取验证字段名称 + * @access public + * @return string + */ + public function getTitle() + { + return $this->title; + } + + /** + * 获取验证提示 + * @access public + * @return array + */ + public function getMsg() + { + return $this->message; + } + + /** + * 设置验证字段名称 + * @access public + * @return $this + */ + public function title($title) + { + $this->title = $title; + + return $this; + } + + public function __call($method, $args) + { + if ('is' == strtolower(substr($method, 0, 2))) { + $method = substr($method, 2); + } + + array_unshift($args, lcfirst($method)); + + return call_user_func_array([$this, 'addItem'], $args); + } + + public static function __callStatic($method, $args) + { + $rule = new static(); + + if ('is' == strtolower(substr($method, 0, 2))) { + $method = substr($method, 2); + } + + array_unshift($args, lcfirst($method)); + + return call_user_func_array([$rule, 'addItem'], $args); + } +} diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index 31fe78076c27357cfd94e1dba68c78e47e0e97dd..b6f6a3d074d944584a9d9d44578d60da16c10b55 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -14,30 +14,37 @@ namespace think\view\driver; use think\App; use think\exception\TemplateNotFoundException; use think\Loader; -use think\Log; -use think\Request; class Php { // 模板引擎参数 protected $config = [ + // 默认模板渲染规则 1 解析为小写+下划线 2 全部转换小写 + 'auto_rule' => 1, + // 视图基础目录(集中式) + 'view_base' => '', // 模板起始路径 'view_path' => '', // 模板文件后缀 'view_suffix' => 'php', // 模板文件名分隔符 - 'view_depr' => DS, + 'view_depr' => DIRECTORY_SEPARATOR, ]; - public function __construct($config = []) + protected $template; + protected $app; + protected $content; + + public function __construct(App $app, $config = []) { - $this->config = array_merge($this->config, $config); + $this->app = $app; + $this->config = array_merge($this->config, (array) $config); } /** * 检测是否存在模板文件 * @access public - * @param string $template 模板文件或者模板规则 + * @param string $template 模板文件或者模板规则 * @return bool */ public function exists($template) @@ -46,14 +53,15 @@ class Php // 获取模板文件名 $template = $this->parseTemplate($template); } + return is_file($template); } /** * 渲染模板文件 * @access public - * @param string $template 模板文件 - * @param array $data 模板变量 + * @param string $template 模板文件 + * @param array $data 模板变量 * @return void */ public function fetch($template, $data = []) @@ -62,81 +70,99 @@ class Php // 获取模板文件名 $template = $this->parseTemplate($template); } + // 模板不存在 抛出异常 if (!is_file($template)) { throw new TemplateNotFoundException('template not exists:' . $template, $template); } + + $this->template = $template; + // 记录视图信息 - App::$debug && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); - if (isset($data['template'])) { - $__template__ = $template; - extract($data, EXTR_OVERWRITE); - include $__template__; - } else { - extract($data, EXTR_OVERWRITE); - include $template; - } + $this->app + ->log('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]'); + + extract($data, EXTR_OVERWRITE); + include $this->template; } /** * 渲染模板内容 * @access public - * @param string $content 模板内容 - * @param array $data 模板变量 + * @param string $content 模板内容 + * @param array $data 模板变量 * @return void */ public function display($content, $data = []) { - if (isset($data['content'])) { - $__content__ = $content; - extract($data, EXTR_OVERWRITE); - eval('?>' . $__content__); - } else { - extract($data, EXTR_OVERWRITE); - eval('?>' . $content); - } + $this->content = $content; + + extract($data, EXTR_OVERWRITE); + eval('?>' . $this->content); } /** * 自动定位模板文件 * @access private - * @param string $template 模板文件规则 + * @param string $template 模板文件规则 * @return string */ private function parseTemplate($template) { if (empty($this->config['view_path'])) { - $this->config['view_path'] = App::$modulePath . 'view' . DS; + $this->config['view_path'] = $this->app->getModulePath() . 'view' . DIRECTORY_SEPARATOR; } + $request = $this->app['request']; + + // 获取视图根目录 if (strpos($template, '@')) { + // 跨模块调用 list($module, $template) = explode('@', $template); - $path = APP_PATH . $module . DS . 'view' . DS; + } + + if ($this->config['view_base']) { + // 基础视图目录 + $module = isset($module) ? $module : $request->module(); + $path = $this->config['view_base'] . ($module ? $module . DIRECTORY_SEPARATOR : ''); } else { - $path = $this->config['view_path']; + $path = isset($module) ? $this->app->getAppPath() . $module . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR : $this->config['view_path']; } - // 分析模板文件规则 - $request = Request::instance(); - $controller = Loader::parseName($request->controller()); - if ($controller && 0 !== strpos($template, '/')) { - $depr = $this->config['view_depr']; - $template = str_replace(['/', ':'], $depr, $template); - if ('' == $template) { - // 如果模板文件名为空 按照默认规则定位 - $template = str_replace('.', DS, $controller) . $depr . $request->action(); - } elseif (false === strpos($template, $depr)) { - $template = str_replace('.', DS, $controller) . $depr . $template; + $depr = $this->config['view_depr']; + + if (0 !== strpos($template, '/')) { + $template = str_replace(['/', ':'], $depr, $template); + $controller = Loader::parseName($request->controller()); + + if ($controller) { + if ('' == $template) { + // 如果模板文件名为空 按照默认规则定位 + $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . $this->getActionTemplate($request); + } elseif (false === strpos($template, $depr)) { + $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . $template; + } } + } else { + $template = str_replace(['/', ':'], $depr, substr($template, 1)); } + return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.'); } + protected function getActionTemplate($request) + { + $rule = [$request->action(true), Loader::parseName($request->action(true)), $request->action()]; + $type = $this->config['auto_rule']; + + return isset($rule[$type]) ? $rule[$type] : $rule[0]; + } + /** * 配置模板引擎 * @access private - * @param string|array $name 参数名 - * @param mixed $value 参数值 + * @param string|array $name 参数名 + * @param mixed $value 参数值 * @return void */ public function config($name, $value = null) diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 33729b442d6adda714933634e34ac2fda9b83704..9ea068266fab9c32988753700d0cbba08765a7fd 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -2,7 +2,7 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. +// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- @@ -14,40 +14,46 @@ namespace think\view\driver; use think\App; use think\exception\TemplateNotFoundException; use think\Loader; -use think\Log; -use think\Request; use think\Template; class Think { // 模板引擎实例 private $template; + private $app; + // 模板引擎参数 protected $config = [ + // 默认模板渲染规则 1 解析为小写+下划线 2 全部转换小写 + 'auto_rule' => 1, + // 视图基础目录(集中式) + 'view_base' => '', // 模板起始路径 'view_path' => '', // 模板文件后缀 'view_suffix' => 'html', // 模板文件名分隔符 - 'view_depr' => DS, + 'view_depr' => DIRECTORY_SEPARATOR, // 是否开启模板编译缓存,设为false则每次都会重新编译 'tpl_cache' => true, ]; - public function __construct($config = []) + public function __construct(App $app, $config = []) { - $this->config = array_merge($this->config, $config); + $this->app = $app; + $this->config = array_merge($this->config, (array) $config); + if (empty($this->config['view_path'])) { - $this->config['view_path'] = App::$modulePath . 'view' . DS; + $this->config['view_path'] = $app->getModulePath() . 'view' . DIRECTORY_SEPARATOR; } - $this->template = new Template($this->config); + $this->template = new Template($app, $this->config); } /** * 检测是否存在模板文件 * @access public - * @param string $template 模板文件或者模板规则 + * @param string $template 模板文件或者模板规则 * @return bool */ public function exists($template) @@ -56,15 +62,16 @@ class Think // 获取模板文件名 $template = $this->parseTemplate($template); } + return is_file($template); } /** * 渲染模板文件 * @access public - * @param string $template 模板文件 - * @param array $data 模板变量 - * @param array $config 模板参数 + * @param string $template 模板文件 + * @param array $data 模板变量 + * @param array $config 模板参数 * @return void */ public function fetch($template, $data = [], $config = []) @@ -73,21 +80,25 @@ class Think // 获取模板文件名 $template = $this->parseTemplate($template); } + // 模板不存在 抛出异常 if (!is_file($template)) { throw new TemplateNotFoundException('template not exists:' . $template, $template); } + // 记录视图信息 - App::$debug && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); + $this->app + ->log('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]'); + $this->template->fetch($template, $data, $config); } /** * 渲染模板内容 * @access public - * @param string $template 模板内容 - * @param array $data 模板变量 - * @param array $config 模板参数 + * @param string $template 模板内容 + * @param array $data 模板变量 + * @param array $config 模板参数 * @return void */ public function display($template, $data = [], $config = []) @@ -98,42 +109,62 @@ class Think /** * 自动定位模板文件 * @access private - * @param string $template 模板文件规则 + * @param string $template 模板文件规则 * @return string */ private function parseTemplate($template) { + // 分析模板文件规则 + $request = $this->app['request']; + // 获取视图根目录 if (strpos($template, '@')) { // 跨模块调用 list($module, $template) = explode('@', $template); - $path = APP_PATH . $module . DS . 'view' . DS; + } + + if ($this->config['view_base']) { + // 基础视图目录 + $module = isset($module) ? $module : $request->module(); + $path = $this->config['view_base'] . ($module ? $module . DIRECTORY_SEPARATOR : ''); } else { - // 当前视图目录 - $path = $this->config['view_path']; + $path = isset($module) ? $this->app->getAppPath() . $module . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR : $this->config['view_path']; } - // 分析模板文件规则 - $request = Request::instance(); - $controller = Loader::parseName($request->controller()); - if ($controller && 0 !== strpos($template, '/')) { - $depr = $this->config['view_depr']; - $template = str_replace(['/', ':'], $depr, $template); - if ('' == $template) { - // 如果模板文件名为空 按照默认规则定位 - $template = str_replace('.', DS, $controller) . $depr . $request->action(); - } elseif (false === strpos($template, $depr)) { - $template = str_replace('.', DS, $controller) . $depr . $template; + $depr = $this->config['view_depr']; + + if (0 !== strpos($template, '/')) { + $template = str_replace(['/', ':'], $depr, $template); + $controller = Loader::parseName($request->controller()); + + if ($controller) { + if ('' == $template) { + // 如果模板文件名为空 按照默认规则定位 + $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . $this->getActionTemplate($request); + } elseif (false === strpos($template, $depr)) { + $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . $template; + } } + } else { + $template = str_replace(['/', ':'], $depr, substr($template, 1)); } + return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.'); } + protected function getActionTemplate($request) + { + $rule = [$request->action(true), Loader::parseName($request->action(true)), $request->action()]; + $type = $this->config['auto_rule']; + + return isset($rule[$type]) ? $rule[$type] : $rule[0]; + } + /** * 配置或者获取模板引擎参数 * @access private - * @param string|array $name 参数名 - * @param mixed $value 参数值 + * @param string|array $name 参数名 + * @param mixed $value 参数值 * @return mixed */ public function config($name, $value = null) diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index 0fad996dad48ae44c6a7596902e71bdea50800a5..41f7e930a9245cbca24bdfb96b1772e06e14b0a3 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -2,7 +2,6 @@ /** * 用法: - * load_trait('controller/Jump'); * class index * { * use \traits\controller\Jump; @@ -14,40 +13,39 @@ */ namespace traits\controller; -use think\Config; +use think\Container; use think\exception\HttpResponseException; -use think\Request; use think\Response; use think\response\Redirect; -use think\Url; -use think\View as ViewTemplate; trait Jump { + /** + * 应用实例 + * @var \think\App + */ + protected $app; + /** * 操作成功跳转的快捷方法 * @access protected - * @param mixed $msg 提示信息 - * @param string $url 跳转的URL地址 - * @param mixed $data 返回的数据 - * @param integer $wait 跳转等待时间 - * @param array $header 发送的Header信息 + * @param mixed $msg 提示信息 + * @param string $url 跳转的URL地址 + * @param mixed $data 返回的数据 + * @param integer $wait 跳转等待时间 + * @param array $header 发送的Header信息 * @return void */ protected function success($msg = '', $url = null, $data = '', $wait = 3, array $header = []) { - $code = 1; - if (is_numeric($msg)) { - $code = $msg; - $msg = ''; - } if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) { $url = $_SERVER["HTTP_REFERER"]; } elseif ('' !== $url) { - $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : Url::build($url); + $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : Container::get('url')->build($url); } + $result = [ - 'code' => $code, + 'code' => 1, 'msg' => $msg, 'data' => $data, 'url' => $url, @@ -55,61 +53,60 @@ trait Jump ]; $type = $this->getResponseType(); + // 把跳转模板的渲染下沉,这样在 response_send 行为里通过getData()获得的数据是一致性的格式 if ('html' == strtolower($type)) { - $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch(Config::get('dispatch_success_tmpl'), $result); + $type = 'jump'; } - $response = Response::create($result, $type)->header($header); + + $response = Response::create($result, $type)->header($header)->options(['jump_template' => $this->app['config']->get('dispatch_success_tmpl')]); + throw new HttpResponseException($response); } /** * 操作错误跳转的快捷方法 * @access protected - * @param mixed $msg 提示信息 - * @param string $url 跳转的URL地址 - * @param mixed $data 返回的数据 - * @param integer $wait 跳转等待时间 - * @param array $header 发送的Header信息 + * @param mixed $msg 提示信息 + * @param string $url 跳转的URL地址 + * @param mixed $data 返回的数据 + * @param integer $wait 跳转等待时间 + * @param array $header 发送的Header信息 * @return void */ protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = []) { - $code = 0; - if (is_numeric($msg)) { - $code = $msg; - $msg = ''; - } + $type = $this->getResponseType(); if (is_null($url)) { - $url = 'javascript:history.back(-1);'; + $url = $this->app['request']->isAjax() ? '' : 'javascript:history.back(-1);'; } elseif ('' !== $url) { - $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : Url::build($url); + $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app['url']->build($url); } + $result = [ - 'code' => $code, + 'code' => 0, 'msg' => $msg, 'data' => $data, 'url' => $url, 'wait' => $wait, ]; - $type = $this->getResponseType(); if ('html' == strtolower($type)) { - $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch(Config::get('dispatch_error_tmpl'), $result); + $type = 'jump'; } - $response = Response::create($result, $type)->header($header); + + $response = Response::create($result, $type)->header($header)->options(['jump_template' => $this->app['config']->get('dispatch_error_tmpl')]); + throw new HttpResponseException($response); } /** * 返回封装后的API数据到客户端 * @access protected - * @param mixed $data 要返回的数据 - * @param integer $code 返回的code - * @param mixed $msg 提示信息 - * @param string $type 返回数据格式 - * @param array $header 发送的Header信息 + * @param mixed $data 要返回的数据 + * @param integer $code 返回的code + * @param mixed $msg 提示信息 + * @param string $type 返回数据格式 + * @param array $header 发送的Header信息 * @return void */ protected function result($data, $code = 0, $msg = '', $type = '', array $header = []) @@ -117,30 +114,36 @@ trait Jump $result = [ 'code' => $code, 'msg' => $msg, - 'time' => $_SERVER['REQUEST_TIME'], + 'time' => time(), 'data' => $data, ]; + $type = $type ?: $this->getResponseType(); $response = Response::create($result, $type)->header($header); + throw new HttpResponseException($response); } /** * URL重定向 * @access protected - * @param string $url 跳转的URL表达式 - * @param array|integer $params 其它URL参数 - * @param integer $code http code + * @param string $url 跳转的URL表达式 + * @param array|integer $params 其它URL参数 + * @param integer $code http code + * @param array $with 隐式传参 * @return void */ - protected function redirect($url, $params = [], $code = 302) + protected function redirect($url, $params = [], $code = 302, $with = []) { $response = new Redirect($url); + if (is_integer($params)) { $code = $params; $params = []; } - $response->code($code)->params($params); + + $response->code($code)->params($params)->with($with); + throw new HttpResponseException($response); } @@ -151,7 +154,15 @@ trait Jump */ protected function getResponseType() { - $isAjax = Request::instance()->isAjax(); - return $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type'); + if (!$this->app) { + $this->app = Container::get('app'); + } + + $isAjax = $this->app['request']->isAjax(); + $config = $this->app['config']; + + return $isAjax + ? $config->get('default_ajax_return') + : $config->get('default_return_type'); } } diff --git a/phpunit.xml b/phpunit.xml deleted file mode 100644 index 7c6ef03ca07245e23593ad27ab18d0d21214e0cb..0000000000000000000000000000000000000000 --- a/phpunit.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - ./tests/thinkphp/ - - - - - - - - ./ - - tests - vendor - - - - - - - - - - diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000000000000000000000000000000000000..37c3d2b53bc6ad79920cf78cf8b8ddfd56654548 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + ./library/think/*/tests/ + + + + + + ./library/ + + ./library/think/*/tests + ./library/think/*/assets + ./library/think/*/resources + ./library/think/*/vendor + + + + \ No newline at end of file diff --git a/tests/.gitignore b/tests/.gitignore deleted file mode 100644 index a0306ecc081c95d006f51f7a460f966a08aa3d23..0000000000000000000000000000000000000000 --- a/tests/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/runtime/ -/application/common.php -/application/demo/ -/application/runtime/ \ No newline at end of file diff --git a/tests/README.md b/tests/README.md deleted file mode 100644 index 0c1d0869e3a09ed216c1faf3b10c877871346db2..0000000000000000000000000000000000000000 --- a/tests/README.md +++ /dev/null @@ -1,132 +0,0 @@ -## 测试目录结构 - -测试文件主要在 tests 文件下面,主要有以下几个文件夹 - -- conf 测试环境配置文件。 -- script 测试环境配置脚本。 -- thinkphp 测试用例和相关文件,与项目文件夹结构一致。 -- mock.php 测试入口文件。 - -## 主要测试流程 - -thinkphp5 的测试的主要流程是跟 thinkphp 的系统流程是相似的,大体的流程为: - -1. 引用 mock.php 文件加载框架 - -2. 根据文件目录,添加测试文件 - -3. 执行单元测试,输出结果 - -## 测试举例 - -例如测试 thinkphp 里的 apc 缓存,将分为以下几个过程: - -1. 创建 apcTest.php 文件 - -该文件应与 apc.php 目录路径 `thinkphp/library/think/cache/driver` 一致,命名空间与目录所在一致,并引用 `PHPUnit_Framework_TestCase`。 - - ```php - markTestSkipped('apc扩展不可用!'); - }; - ``` - - - 编写测试用例 - - *具体写法参照 [PHPUnit 官方文档](https://phpunit.de/manual/4.8/zh_cn/index.html)* - - ```php - public function testGet() - { - App::run(); - $this->assertInstanceOf( - '\think\cache\driver\Apc', - Cache::connect(['type' => 'apc', 'expire' => 1]) - ); - $this->assertTrue(Cache::set('key', 'value')); - $this->assertEquals('value', Cache::get('key')); - $this->assertTrue(Cache::rm('key')); - $this->assertFalse(Cache::get('key')); - $this->assertTrue(Cache::clear('key')); - Config::reset(); - } - ``` - -3. 执行单元测试命令 - - 在项目根目录执行 - - ```bash - $ phpunit - ``` - - 若想看到所有结果,请添加-v参数 - - ```bash - $ phpunit -v - ``` - -4. 输出结果 - -## 相关文档 - -[各个部分单元测试说明](http://www.kancloud.cn/brother_simon/tp5_test/96971 "各部分单元测试说明") - -## 大家一起来 - -单元测试的内容会跟框架同步,测试内容方方面面,是一个相对复杂的模块,同时也是一个值得重视的部分。希望大家能够多多提出意见,多多参与。如果你有任何问题或想法,可以随时提 issue,我们期待着收到听大家的质疑和讨论。 - -## 任务进度 - -单元测试任务进度,请大家认领模块 - -|模块|认领人|进度| -|---|---|---| -|Base||| -|App|Haotong Lin|√| -|Build|刘志淳|| -|Config|Haotong Lin|√| -|Cache||| -|Controller|Haotong Lin|√| -|Cookie|Haotong Lin|√| -|Db||| -|Debug|大漠|√| -|Error|大漠|| -|Exception|Haotong Lin|√| -|Hook|流年|√| -|Input|Haotong Lin|√| -|Lang|流年|√| -|Loader|流年|| -|Log||| -|Model||| -|Response|大漠|√| -|Route|流年|| -|Session|大漠|√| -|Template|oldrind|| -|Url|流年|| -|View|mahuan|| diff --git a/tests/application/config.php b/tests/application/config.php deleted file mode 100644 index 7bf368d65f158172edb97e0d62a556820021ea04..0000000000000000000000000000000000000000 --- a/tests/application/config.php +++ /dev/null @@ -1,33 +0,0 @@ - -// +---------------------------------------------------------------------- -// $Id$ - -return [ - 'url_route_on' => true, - 'log' => [ - 'type' => 'trace', // 支持 socket trace file - ], - 'view' => [ - // 模板引擎 - 'engine_type' => 'think', - // 模板引擎配置 - 'engine_config' => [ - // 模板路径 - 'view_path' => '', - // 模板后缀 - 'view_suffix' => '.html', - // 模板文件名分隔符 - 'view_depr' => DS, - ], - // 输出字符串替换 - 'parse_str' => [], - ], -]; diff --git a/tests/application/database.php b/tests/application/database.php deleted file mode 100644 index 24434efb2c02f6973314e135b82e683e9d8a37c2..0000000000000000000000000000000000000000 --- a/tests/application/database.php +++ /dev/null @@ -1,44 +0,0 @@ - -// +---------------------------------------------------------------------- -// $Id$ - -return [ - // 数据库类型 - 'type' => 'mysql', - // 数据库连接DSN配置 - 'dsn' => '', - // 服务器地址 - 'hostname' => '127.0.0.1', - // 数据库名 - 'database' => '', - // 数据库用户名 - 'username' => 'root', - // 数据库密码 - 'password' => '', - // 数据库连接端口 - 'hostport' => '', - // 数据库连接参数 - 'params' => [], - // 数据库编码默认采用utf8 - 'charset' => 'utf8', - // 数据库表前缀 - 'prefix' => '', - // 数据库调试模式 - 'debug' => true, - // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) - 'deploy' => 0, - // 数据库读写是否分离 主从式有效 - 'rw_separate' => false, - // 读写分离后 主服务器数量 - 'master_num' => 1, - // 指定从服务器序号 - 'slave_no' => '', -]; diff --git a/tests/application/index/controller/Index.php b/tests/application/index/controller/Index.php deleted file mode 100644 index 803fe952f365ef56164f2e90c78e670e5feb815d..0000000000000000000000000000000000000000 --- a/tests/application/index/controller/Index.php +++ /dev/null @@ -1,10 +0,0 @@ -*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }

:)

ThinkPHP V5
十年磨一剑 - 为API开发设计的高性能框架

[ V5.0 版本由 七牛云 独家赞助发布 ]
'; - } -} diff --git a/tests/conf/apcu.ini b/tests/conf/apcu.ini deleted file mode 100644 index 9c2abed2c98dc0fd355543383d574ea2de85e2ce..0000000000000000000000000000000000000000 --- a/tests/conf/apcu.ini +++ /dev/null @@ -1,3 +0,0 @@ -extension=apcu.so - -apc.enable_cli=1 diff --git a/tests/conf/apcu_bc.ini b/tests/conf/apcu_bc.ini deleted file mode 100644 index a7f6182da10b8bce0c638d0e69b330fb4c9540b7..0000000000000000000000000000000000000000 --- a/tests/conf/apcu_bc.ini +++ /dev/null @@ -1,4 +0,0 @@ -extension=apcu.so -extension=apc.so - -apc.enable_cli=1 diff --git a/tests/conf/memcached.ini b/tests/conf/memcached.ini deleted file mode 100644 index 7d09664ee5a8102fa136499cf98949cbfe73569b..0000000000000000000000000000000000000000 --- a/tests/conf/memcached.ini +++ /dev/null @@ -1 +0,0 @@ -extension=memcached.so diff --git a/tests/conf/redis.ini b/tests/conf/redis.ini deleted file mode 100644 index 6aecae4895d5fd045e6f692a2e328bc0055d5b62..0000000000000000000000000000000000000000 --- a/tests/conf/redis.ini +++ /dev/null @@ -1 +0,0 @@ -extension=redis.so diff --git a/tests/conf/timezone.ini b/tests/conf/timezone.ini deleted file mode 100644 index ced3e0d705667502f39877f28a522cc86915f44a..0000000000000000000000000000000000000000 --- a/tests/conf/timezone.ini +++ /dev/null @@ -1 +0,0 @@ -date.timezone = UTC \ No newline at end of file diff --git a/tests/extensions/5.4/apcu.so b/tests/extensions/5.4/apcu.so deleted file mode 100755 index 42a24a660e00f2fc2f57494bc4f62172da7cddf9..0000000000000000000000000000000000000000 Binary files a/tests/extensions/5.4/apcu.so and /dev/null differ diff --git a/tests/extensions/5.5/apcu.so b/tests/extensions/5.5/apcu.so deleted file mode 100755 index 26e5228a6b22f4599222f0a76b5f6ecf4c6509b4..0000000000000000000000000000000000000000 Binary files a/tests/extensions/5.5/apcu.so and /dev/null differ diff --git a/tests/extensions/5.6/apcu.so b/tests/extensions/5.6/apcu.so deleted file mode 100755 index fe952969ee5e3b7dae3305c44929714a4780e7c0..0000000000000000000000000000000000000000 Binary files a/tests/extensions/5.6/apcu.so and /dev/null differ diff --git a/tests/extensions/7.0/apc.so b/tests/extensions/7.0/apc.so deleted file mode 100755 index 7948350dab56ee7e9976db1776d7e202b8e38ad6..0000000000000000000000000000000000000000 Binary files a/tests/extensions/7.0/apc.so and /dev/null differ diff --git a/tests/extensions/7.0/apcu.so b/tests/extensions/7.0/apcu.so deleted file mode 100755 index c2f0ad1402d0e709af094ee60ff617c1f0a34bd5..0000000000000000000000000000000000000000 Binary files a/tests/extensions/7.0/apcu.so and /dev/null differ diff --git a/tests/extensions/7.0/memcached.so b/tests/extensions/7.0/memcached.so deleted file mode 100755 index 544ba6d52ee89046ac2ddab0d4acfe2d95e8bfda..0000000000000000000000000000000000000000 Binary files a/tests/extensions/7.0/memcached.so and /dev/null differ diff --git a/tests/extensions/7.0/redis.so b/tests/extensions/7.0/redis.so deleted file mode 100755 index e3aea8fcb15ca3b61d31dcedc298f7ae33ff39ee..0000000000000000000000000000000000000000 Binary files a/tests/extensions/7.0/redis.so and /dev/null differ diff --git a/tests/script/install.sh b/tests/script/install.sh deleted file mode 100755 index 0adee7ed10314694bc3b63c43746ed3a23f662fe..0000000000000000000000000000000000000000 --- a/tests/script/install.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash - -if [ $(phpenv version-name) != "hhvm" ]; then - cp tests/extensions/$(phpenv version-name)/*.so $(php-config --extension-dir) - - if [ $(phpenv version-name) = "7.0" ]; then - phpenv config-add tests/conf/apcu_bc.ini - else - phpenv config-add tests/conf/apcu.ini - fi - - phpenv config-add tests/conf/memcached.ini - phpenv config-add tests/conf/redis.ini - - phpenv config-add tests/conf/timezone.ini -fi - -composer install --no-interaction --ignore-platform-reqs diff --git a/tests/thinkphp/baseTest.php b/tests/thinkphp/baseTest.php deleted file mode 100644 index 18f1d3dd4a41f3451b0a96297dc166c7b1359f96..0000000000000000000000000000000000000000 --- a/tests/thinkphp/baseTest.php +++ /dev/null @@ -1,39 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * 保证运行环境正常 - */ -class baseTest extends \PHPUnit_Framework_TestCase -{ - public function testConstants() - { - $this->assertNotEmpty(THINK_START_TIME); - $this->assertNotEmpty(THINK_START_MEM); - $this->assertNotEmpty(THINK_VERSION); - $this->assertNotEmpty(DS); - $this->assertNotEmpty(THINK_PATH); - $this->assertNotEmpty(LIB_PATH); - $this->assertNotEmpty(EXTEND_PATH); - $this->assertNotEmpty(CORE_PATH); - $this->assertNotEmpty(TRAIT_PATH); - $this->assertNotEmpty(APP_PATH); - $this->assertNotEmpty(RUNTIME_PATH); - $this->assertNotEmpty(LOG_PATH); - $this->assertNotEmpty(CACHE_PATH); - $this->assertNotEmpty(TEMP_PATH); - $this->assertNotEmpty(VENDOR_PATH); - $this->assertNotEmpty(EXT); - $this->assertNotEmpty(ENV_PREFIX); - $this->assertTrue(!is_null(IS_WIN)); - $this->assertTrue(!is_null(IS_CLI)); - } -} diff --git a/tests/thinkphp/library/think/appTest.php b/tests/thinkphp/library/think/appTest.php deleted file mode 100644 index 366b4f557b997121b242ba7cd711b140cbdb22db..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/appTest.php +++ /dev/null @@ -1,91 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * app类测试 - * @author Haotong Lin - */ - -namespace tests\thinkphp\library\think; - -use ReflectionClass; -use think\App; -use think\Config; -use think\Request; - -function func_trim($value) -{ - return trim($value); -} - -function func_strpos($haystack, $needle) -{ - return strpos($haystack, $needle); -} - -class AppInvokeMethodTestClass -{ - public static function staticRun($string) - { - return $string; - } - - public function run($string) - { - return $string; - } -} - -class appTest extends \PHPUnit_Framework_TestCase -{ - public function testRun() - { - $response = App::run(Request::create("http://www.example.com")); - - $expectOutputString = '

:)

ThinkPHP V5
十年磨一剑 - 为API开发设计的高性能框架

[ V5.0 版本由 七牛云 独家赞助发布 ]
'; - - $this->assertEquals($expectOutputString, $response->getContent()); - $this->assertEquals(200, $response->getCode()); - - $this->assertEquals(true, function_exists('lang')); - $this->assertEquals(true, function_exists('config')); - $this->assertEquals(true, function_exists('input')); - - $this->assertEquals(Config::get('default_timezone'), date_default_timezone_get()); - - } - - // function调度 - public function testInvokeFunction() - { - $args1 = ['a b c ']; - $this->assertEquals( - trim($args1[0]), - App::invokeFunction('tests\thinkphp\library\think\func_trim', $args1) - ); - - $args2 = ['abcdefg', 'g']; - $this->assertEquals( - strpos($args2[0], $args2[1]), - App::invokeFunction('tests\thinkphp\library\think\func_strpos', $args2) - ); - } - - // 类method调度 - public function testInvokeMethod() - { - $result = App::invokeMethod(['tests\thinkphp\library\think\AppInvokeMethodTestClass', 'run'], ['thinkphp']); - $this->assertEquals('thinkphp', $result); - - $result = App::invokeMethod('tests\thinkphp\library\think\AppInvokeMethodTestClass::staticRun', ['thinkphp']); - $this->assertEquals('thinkphp', $result); - } -} diff --git a/tests/thinkphp/library/think/behavior/One.php b/tests/thinkphp/library/think/behavior/One.php deleted file mode 100644 index ae8fa49d17021a23a5fd9c3a728f0f3775f64fed..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/behavior/One.php +++ /dev/null @@ -1,15 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * build测试 - * @author 刘志淳 - */ - -namespace tests\thinkphp\library\think; - -use think\Build; - -class buildTest extends \PHPUnit_Framework_TestCase -{ - public function testRun() - { - $build = [ - // Test run directory - '__dir__' => ['runtime/cache', 'runtime/log', 'runtime/temp', 'runtime/template'], - '__file__' => ['common.php'], - - // Test generation module - 'demo' => [ - '__file__' => ['common.php'], - '__dir__' => ['behavior', 'controller', 'model', 'view', 'service'], - 'controller' => ['Index', 'Test', 'UserType'], - 'model' => ['User', 'UserType'], - 'service' => ['User', 'UserType'], - 'view' => ['index/index'], - ], - ]; - Build::run($build); - - $this->buildFileExists($build); - } - - protected function buildFileExists($build) - { - foreach ($build as $module => $list) { - if ('__dir__' == $module || '__file__' == $module) { - foreach ($list as $file) { - $this->assertFileExists(APP_PATH . $file); - } - } else { - foreach ($list as $path => $moduleList) { - if ('__file__' == $path || '__dir__' == $path) { - foreach ($moduleList as $file) { - $this->assertFileExists(APP_PATH . $module . '/' . $file); - } - } else { - foreach ($moduleList as $file) { - if ('view' == $path) { - $file_name = APP_PATH . $module . '/' . $path . '/' . $file . '.html'; - } else { - $file_name = APP_PATH . $module . '/' . $path . '/' . $file . EXT; - } - $this->assertFileExists($file_name); - } - } - } - $this->assertFileExists(APP_PATH . ($module ? $module . DS : '') . 'config.php'); - } - } - } -} diff --git a/tests/thinkphp/library/think/cache/driver/cacheTestCase.php b/tests/thinkphp/library/think/cache/driver/cacheTestCase.php deleted file mode 100644 index ec8f9b6bb649ac0fd75372255283eaac707e255c..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/cache/driver/cacheTestCase.php +++ /dev/null @@ -1,207 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * 缓存抽象类,提供一些测试 - * @author simon - */ - -namespace tests\thinkphp\library\think\cache\driver; - -use think\Cache; - -abstract class cacheTestCase extends \PHPUnit_Framework_TestCase -{ - - /** - * 获取缓存句柄,子类必须有 - * @access protected - */ - abstract protected function getCacheInstance(); - - /** - * tearDown函数 - */ - protected function tearDown() - { - } - - /** - * 设定一组测试值,包括测试字符串、整数、数组和对象 - * @return mixed - * @access public - */ - public function prepare() - { - $cache = $this->getCacheInstance(); - $cache->clear(); - $cache->set('string_test', 'string_test'); - $cache->set('number_test', 11); - $cache->set('array_test', ['array_test' => 'array_test']); - return $cache; - } - - /** - * 测试缓存设置,包括测试字符串、整数、数组和对象 - * @return mixed - * @access public - */ - public function testSet() - { - $cache = $this->getCacheInstance(); - $this->assertTrue($cache->set('string_test', 'string_test')); - $this->assertTrue($cache->set('number_test', 11)); - $this->assertTrue($cache->set('array_test', ['array_test' => 'array_test'])); - } - - /** - * 测试缓存自增 - * @return mixed - * @access public - */ - public function testInc() - { - $cache = $this->getCacheInstance(); - $this->assertEquals(14, $cache->inc('number_test', 3)); - } - - /** - * 测试缓存自减 - * @return mixed - * @access public - */ - public function testDec() - { - $cache = $this->getCacheInstance(); - $this->assertEquals(8, $cache->dec('number_test', 6)); - } - - /** - * 测试缓存读取,包括测试字符串、整数、数组和对象 - * @return mixed - * @access public - */ - public function testGet() - { - $cache = $this->prepare(); - $this->assertEquals('string_test', $cache->get('string_test')); - $this->assertEquals(11, $cache->get('number_test')); - $array = $cache->get('array_test'); - $this->assertArrayHasKey('array_test', $array); - $this->assertEquals('array_test', $array['array_test']); - - $result = $cache->set('no_expire', 1, 0); - $this->assertTrue($result); - } - - /** - * 测试缓存存在情况,包括测试字符串、整数、数组和对象 - * @return mixed - * @access public - */ - public function testExists() - { - $cache = $this->prepare(); - $this->assertNotEmpty($cache->has('string_test')); - $this->assertNotEmpty($cache->has('number_test')); - $this->assertFalse($cache->has('not_exists')); - } - - /** - * 测试缓存不存在情况,包括测试字符串、整数、数组和对象 - * @return mixed - * @access public - */ - public function testGetNonExistent() - { - $cache = $this->getCacheInstance(); - $this->assertFalse($cache->get('non_existent_key', false)); - } - - /** - * 测试特殊值缓存,包括测试字符串、整数、数组和对象 - * @return mixed - * @access public - */ - public function testStoreSpecialValues() - { - $cache = $this->getCacheInstance(); - $cache->set('null_value', null); - //清空缓存后,返回null而不是false - $this->assertTrue(is_null($cache->get('null_value'))); - } - - /** - * 缓存过期测试 - * @return mixed - * @access public - */ - public function testExpire() - { - $cache = $this->getCacheInstance(); - $this->assertTrue($cache->set('expire_test', 'expire_test', 1)); - usleep(600000); - $this->assertEquals('expire_test', $cache->get('expire_test')); - usleep(800000); - $this->assertFalse($cache->get('expire_test')); - } - - /** - * 删除缓存测试 - * @return mixed - * @access public - */ - public function testDelete() - { - $cache = $this->prepare(); - $this->assertNotNull($cache->rm('number_test')); - $this->assertFalse($cache->get('number_test')); - } - - /** - * 获取并删除缓存测试 - * @return mixed - * @access public - */ - public function testPull() - { - $cache = $this->prepare(); - $this->assertEquals(11, $cache->pull('number_test')); - $this->assertFalse($cache->get('number_test')); - } - - /** - * 清空缓存测试 - * @return mixed - * @access public - */ - public function testClear() - { - $cache = $this->prepare(); - $this->assertTrue($cache->clear()); - $this->assertFalse($cache->get('number_test')); - } - - public function testStaticCall() - { - $this->assertTrue(Cache::set('a', 1)); - $this->assertEquals(1, Cache::get('a')); - $this->assertEquals(2, Cache::inc('a')); - $this->assertEquals(4, Cache::inc('a', 2)); - $this->assertEquals(4, Cache::get('a')); - $this->assertEquals(3, Cache::dec('a')); - $this->assertEquals(1, Cache::dec('a', 2)); - $this->assertEquals(1, Cache::get('a')); - $this->assertNotNull(Cache::rm('a')); - $this->assertNotNull(Cache::clear()); - } - -} diff --git a/tests/thinkphp/library/think/cache/driver/liteTest.php b/tests/thinkphp/library/think/cache/driver/liteTest.php deleted file mode 100644 index b52bdff9f3771a02102bba1976808b016327519e..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/cache/driver/liteTest.php +++ /dev/null @@ -1,69 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Lite缓存驱动测试 - * @author 刘志淳 - */ - -namespace tests\thinkphp\library\think\cache\driver; - -use think\Cache; - -class liteTest extends \PHPUnit_Framework_TestCase -{ - protected function getCacheInstance() - { - return Cache::connect(['type' => 'Lite', 'path' => CACHE_PATH]); - } - - /** - * 测试缓存读取 - * @return mixed - * @access public - */ - public function testGet() - { - $cache = $this->getCacheInstance(); - $this->assertFalse($cache->get('test')); - } - - /** - * 测试缓存设置 - * @return mixed - * @access public - */ - public function testSet() - { - $cache = $this->getCacheInstance(); - $this->assertNotEmpty($cache->set('test', 'test')); - } - - /** - * 删除缓存测试 - * @return mixed - * @access public - */ - public function testRm() - { - $cache = $this->getCacheInstance(); - $this->assertTrue($cache->rm('test')); - } - - /** - * 清空缓存测试 - * @return mixed - * @access public - */ - public function testClear() - { - } -} diff --git a/tests/thinkphp/library/think/cache/driver/redisTest.php b/tests/thinkphp/library/think/cache/driver/redisTest.php deleted file mode 100644 index 839e5165a46406da62c87021eaebd0bd86bec6dc..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/cache/driver/redisTest.php +++ /dev/null @@ -1,66 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Redis缓存驱动测试 - * @author 7IN0SAN9 - */ - -namespace tests\thinkphp\library\think\cache\driver; - -class redisTest extends cacheTestCase -{ - private $_cacheInstance = null; - - protected function setUp() - { - if (!extension_loaded("redis")) { - $this->markTestSkipped("Redis没有安装,已跳过测试!"); - } - \think\Cache::connect(array('type' => 'redis', 'expire' => 2)); - } - - protected function getCacheInstance() - { - if (null === $this->_cacheInstance) { - $this->_cacheInstance = new \think\cache\driver\Redis(['length' => 3]); - } - return $this->_cacheInstance; - } - - public function testGet() - { - $cache = $this->prepare(); - $this->assertEquals('string_test', $cache->get('string_test')); - $this->assertEquals(11, $cache->get('number_test')); - $result = $cache->get('array_test'); - $this->assertEquals('array_test', $result['array_test']); - } - - public function testStoreSpecialValues() - { - $redis = new \think\cache\driver\Redis(['length' => 3]); - $redis->set('key', 'value'); - $redis->get('key'); - - $redis->handler()->setnx('key', 'value'); - $value = $redis->handler()->get('key'); - $this->assertEquals('value', $value); - - $redis->handler()->hset('hash', 'key', 'value'); - $value = $redis->handler()->hget('hash', 'key'); - $this->assertEquals('value', $value); - } - - public function testExpire() - { - } -} diff --git a/tests/thinkphp/library/think/config/driver/fixtures/config.ini b/tests/thinkphp/library/think/config/driver/fixtures/config.ini deleted file mode 100644 index 2a17cc0decd3d1cc09a8cb17e17cc5ca04db8e62..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/config/driver/fixtures/config.ini +++ /dev/null @@ -1 +0,0 @@ -inifile=1 \ No newline at end of file diff --git a/tests/thinkphp/library/think/config/driver/fixtures/config.json b/tests/thinkphp/library/think/config/driver/fixtures/config.json deleted file mode 100644 index 716ed06471ba7b22e3e05c8c40e91322b3f25c2b..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/config/driver/fixtures/config.json +++ /dev/null @@ -1 +0,0 @@ -{"jsonstring":1} \ No newline at end of file diff --git a/tests/thinkphp/library/think/config/driver/fixtures/config.xml b/tests/thinkphp/library/think/config/driver/fixtures/config.xml deleted file mode 100644 index 3c3266a17dbae2badab55b791215891735b10845..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/config/driver/fixtures/config.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - 1 - - \ No newline at end of file diff --git a/tests/thinkphp/library/think/configTest.php b/tests/thinkphp/library/think/configTest.php deleted file mode 100644 index 166f0f8a8a07186cba80b5af76b1d71ab189fb5b..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/configTest.php +++ /dev/null @@ -1,169 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * 配置测试 - * @author Haotong Lin - */ - -namespace tests\thinkphp\library\think; - -use ReflectionClass; -use think\Config; - -class configTest extends \PHPUnit_Framework_TestCase -{ - public function testRange() - { - $reflectedClass = new ReflectionClass('\think\Config'); - $reflectedPropertyRange = $reflectedClass->getProperty('range'); - $reflectedPropertyRange->setAccessible(true); - $reflectedPropertyConfig = $reflectedClass->getProperty('config'); - $reflectedPropertyConfig->setAccessible(true); - // test default range - $this->assertEquals('_sys_', $reflectedPropertyRange->getValue()); - $config = $reflectedPropertyConfig->getValue(); - $this->assertTrue(is_array($config)); - // test range initialization - Config::range('_test_'); - $this->assertEquals('_test_', $reflectedPropertyRange->getValue()); - $config = $reflectedPropertyConfig->getValue(); - $this->assertEquals([], $config['_test_']); - } - - // public function testParse() - // { - // see \think\config\driver\...Test.php - // } - - public function testLoad() - { - $file = APP_PATH . 'config' . EXT; - $config = array_change_key_case(include $file); - $name = '_name_'; - $range = '_test_'; - - $reflectedClass = new ReflectionClass('\think\Config'); - $reflectedPropertyConfig = $reflectedClass->getProperty('config'); - $reflectedPropertyConfig->setAccessible(true); - $reflectedPropertyConfig->setValue([]); - - $this->assertEquals($config, Config::load($file, $name, $range)); - $this->assertNotEquals(null, Config::load($file, $name, $range)); - } - - public function testHas() - { - $range = '_test_'; - $this->assertFalse(Config::has('abcd', $range)); - $reflectedClass = new ReflectionClass('\think\Config'); - $reflectedPropertyConfig = $reflectedClass->getProperty('config'); - $reflectedPropertyConfig->setAccessible(true); - - // if (!strpos($name, '.')): - $reflectedPropertyConfig->setValue([ - $range => ['abcd' => 'value'], - ]); - $this->assertTrue(Config::has('abcd', $range)); - - // else ... - $this->assertFalse(Config::has('abcd.efg', $range)); - - $reflectedPropertyConfig->setValue([ - $range => ['abcd' => ['efg' => 'value']], - ]); - $this->assertTrue(Config::has('abcd.efg', $range)); - } - - public function testGet() - { - $range = '_test_'; - $reflectedClass = new ReflectionClass('\think\Config'); - $reflectedPropertyConfig = $reflectedClass->getProperty('config'); - $reflectedPropertyConfig->setAccessible(true); - // test all configurations - $reflectedPropertyConfig->setValue([$range => []]); - $this->assertEquals([], Config::get(null, $range)); - $this->assertEquals(null, Config::get(null, 'does_not_exist')); - $value = 'value'; - // test getting configuration - $reflectedPropertyConfig->setValue([$range => ['abcd' => 'efg']]); - $this->assertEquals('efg', Config::get('abcd', $range)); - $this->assertEquals(null, Config::get('does_not_exist', $range)); - $this->assertEquals(null, Config::get('abcd', 'does_not_exist')); - // test getting configuration with dot syntax - $reflectedPropertyConfig->setValue([$range => [ - 'one' => ['two' => $value], - ]]); - $this->assertEquals($value, Config::get('one.two', $range)); - $this->assertEquals(null, Config::get('one.does_not_exist', $range)); - $this->assertEquals(null, Config::get('one.two', 'does_not_exist')); - } - - public function testSet() - { - $range = '_test_'; - $reflectedClass = new ReflectionClass('\think\Config'); - $reflectedPropertyConfig = $reflectedClass->getProperty('config'); - $reflectedPropertyConfig->setAccessible(true); - $reflectedPropertyConfig->setValue([]); - // if (is_string($name)): - // without dot syntax - $name = 'name'; - $value = 'value'; - Config::set($name, $value, $range); - $config = $reflectedPropertyConfig->getValue(); - $this->assertEquals($value, $config[$range][$name]); - // with dot syntax - $name = 'one.two'; - $value = 'dot value'; - Config::set($name, $value, $range); - $config = $reflectedPropertyConfig->getValue(); - $this->assertEquals($value, $config[$range]['one']['two']); - // if (is_array($name)): - // see testLoad() - // ... - // test getting all configurations...? - // return self::$config[$range]; ?? - $value = ['all' => 'configuration']; - $reflectedPropertyConfig->setValue([$range => $value]); - $this->assertEquals($value, Config::set(null, null, $range)); - $this->assertNotEquals(null, Config::set(null, null, $range)); - } - - public function testReset() - { - $range = '_test_'; - $reflectedClass = new ReflectionClass('\think\Config'); - $reflectedPropertyConfig = $reflectedClass->getProperty('config'); - $reflectedPropertyConfig->setAccessible(true); - $reflectedPropertyConfig->setValue([$range => ['abcd' => 'efg']]); - - // clear all configurations - Config::reset(true); - $config = $reflectedPropertyConfig->getValue(); - $this->assertEquals([], $config); - // clear the configuration in range of parameter. - $reflectedPropertyConfig->setValue([ - $range => [ - 'abcd' => 'efg', - 'hijk' => 'lmn', - ], - 'a' => 'b', - ]); - Config::reset($range); - $config = $reflectedPropertyConfig->getValue(); - $this->assertEquals([ - $range => [], - 'a' => 'b', - ], $config); - } -} diff --git a/tests/thinkphp/library/think/controller/.gitignore b/tests/thinkphp/library/think/controller/.gitignore deleted file mode 100644 index a3a0c8b5f48c0260a4cb43aa577f9b18896ee280..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/controller/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/tests/thinkphp/library/think/controllerTest.php b/tests/thinkphp/library/think/controllerTest.php deleted file mode 100644 index ce5f49a06e9b816a32cdc9b000f3a0d331749bcb..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/controllerTest.php +++ /dev/null @@ -1,194 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * 控制器测试 - * @author Haotong Lin - */ - -namespace tests\thinkphp\library\think; - -use ReflectionClass; -use think\Controller; -use think\Request; -use think\View; - -require_once CORE_PATH . '../../helper.php'; - -class Foo extends Controller -{ - public $test = 'test'; - - public function _initialize() - { - $this->test = 'abcd'; - } - - public function assignTest() - { - $this->assign('abcd', 'dcba'); - $this->assign(['key1' => 'value1', 'key2' => 'value2']); - } - - public function fetchTest() - { - $template = dirname(__FILE__) . '/display.html'; - return $this->fetch($template, ['name' => 'ThinkPHP']); - } - - public function displayTest() - { - $template = dirname(__FILE__) . '/display.html'; - return $this->display($template, ['name' => 'ThinkPHP']); - } - public function test() - { - $data = [ - 'username' => 'username', - 'nickname' => 'nickname', - 'password' => '123456', - 'repassword' => '123456', - 'email' => 'abc@abc.com', - 'sex' => '0', - 'age' => '20', - 'code' => '1234', - ]; - - $validate = [ - ['username', 'length:5,15', '用户名长度为5到15个字符'], - ['nickname', 'require', '请填昵称'], - ['password', '[\w-]{6,15}', '密码长度为6到15个字符'], - ['repassword', 'confirm:password', '两次密码不一到致'], - ['email', 'filter:validate_email', '邮箱格式错误'], - ['sex', 'in:0,1', '性别只能为为男或女'], - ['age', 'between:1,80', '年龄只能在10-80之间'], - ]; - return $this->validate($data, $validate); - } -} - -class Bar extends Controller -{ - public $test = 1; - - public $beforeActionList = ['action1', 'action2']; - - public function action1() - { - $this->test += 2; - return 'action1'; - } - - public function action2() - { - $this->test += 4; - return 'action2'; - } -} - -class Baz extends Controller -{ - public $test = 1; - - public $beforeActionList = [ - 'action1' => ['only' => 'index'], - 'action2' => ['except' => 'index'], - 'action3' => ['only' => 'abcd'], - 'action4' => ['except' => 'abcd'], - ]; - - public function action1() - { - $this->test += 2; - return 'action1'; - } - - public function action2() - { - $this->test += 4; - return 'action2'; - } - - public function action3() - { - $this->test += 8; - return 'action2'; - } - - public function action4() - { - $this->test += 16; - return 'action2'; - } -} - -class controllerTest extends \PHPUnit_Framework_TestCase -{ - public function testInitialize() - { - $foo = new Foo(Request::instance()); - $this->assertEquals('abcd', $foo->test); - } - - public function testBeforeAction() - { - $obj = new Bar(Request::instance()); - $this->assertEquals(7, $obj->test); - - $obj = new Baz(Request::instance()); - $this->assertEquals(19, $obj->test); - } - - private function getView($controller) - { - $view = new View(); - $rc = new ReflectionClass(get_class($controller)); - $property = $rc->getProperty('view'); - $property->setAccessible(true); - $property->setValue($controller, $view); - return $view; - } - - public function testFetch() - { - $controller = new Foo(Request::instance()); - $view = $this->getView($controller); - $template = dirname(__FILE__) . '/display.html'; - $viewFetch = $view->fetch($template, ['name' => 'ThinkPHP']); - $this->assertEquals($controller->fetchTest(), $viewFetch); - } - - public function testDisplay() - { - $controller = new Foo; - $view = $this->getView($controller); - $template = dirname(__FILE__) . '/display.html'; - $viewFetch = $view->display($template, ['name' => 'ThinkPHP']); - - $this->assertEquals($controller->displayTest(), $viewFetch); - } - - public function testAssign() - { - $controller = new Foo(Request::instance()); - $view = $this->getView($controller); - $controller->assignTest(); - $expect = ['abcd' => 'dcba', 'key1' => 'value1', 'key2' => 'value2']; - $this->assertAttributeEquals($expect, 'data', $view); - } - - public function testValidate() - { - $controller = new Foo(Request::instance()); - $result = $controller->test(); - $this->assertTrue($result); - } -} diff --git a/tests/thinkphp/library/think/cookieTest.php b/tests/thinkphp/library/think/cookieTest.php deleted file mode 100644 index 24cb153e4b32634b0920b7b702c4b87a8dbbf7f2..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/cookieTest.php +++ /dev/null @@ -1,150 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Cookie测试 - * @author Haotong Lin - */ - -namespace tests\thinkphp\library\think; - -use ReflectionClass; -use think\Cookie; - -class cookieTest extends \PHPUnit_Framework_TestCase -{ - protected $ref; - - protected $default = [ - // cookie 名称前缀 - 'prefix' => '', - // cookie 保存时间 - 'expire' => 0, - // cookie 保存路径 - 'path' => '/', - // cookie 有效域名 - 'domain' => '', - // cookie 启用安全传输 - 'secure' => false, - // httponly设置 - 'httponly' => '', - // 是否使用 setcookie - 'setcookie' => false, - ]; - - protected function setUp() - { - $reflectedClass = new ReflectionClass('\think\Cookie'); - $reflectedPropertyConfig = $reflectedClass->getProperty('config'); - $reflectedPropertyConfig->setAccessible(true); - $reflectedPropertyConfig->setValue($this->default); - $this->ref = $reflectedPropertyConfig; - } - - public function testInit() - { - $config = [ - // cookie 名称前缀 - 'prefix' => 'think_', - // cookie 保存时间 - 'expire' => 0, - // cookie 保存路径 - 'path' => '/path/to/test/', - // cookie 有效域名 - 'domain' => '.thinkphp.cn', - // cookie 启用安全传输 - 'secure' => true, - // httponly设置 - 'httponly' => '1', - ]; - Cookie::init($config); - - $this->assertEquals( - array_merge($this->default, array_change_key_case($config)), - $this->ref->getValue() - ); - } - - public function testPrefix() - { - $this->assertEquals($this->default['prefix'], Cookie::prefix()); - - $prefix = '_test_'; - $this->assertNotEquals($prefix, Cookie::prefix()); - Cookie::prefix($prefix); - - $config = $this->ref->getValue(); - $this->assertEquals($prefix, $config['prefix']); - } - - public function testSet() - { - $value = 'value'; - - $name = 'name1'; - Cookie::set($name, $value, 10); - $this->assertEquals($value, $_COOKIE[$this->default['prefix'] . $name]); - - $name = 'name2'; - Cookie::set($name, $value, null); - $this->assertEquals($value, $_COOKIE[$this->default['prefix'] . $name]); - - $name = 'name3'; - Cookie::set($name, $value, 'expire=100&prefix=pre_'); - $this->assertEquals($value, $_COOKIE['pre_' . $name]); - - $name = 'name4'; - $value = ['_test_中文_']; - Cookie::set($name, $value); - $this->assertEquals('think:' . json_encode([urlencode('_test_中文_')]), $_COOKIE[$name]); - } - - public function testGet() - { - $_COOKIE = [ - 'a' => 'b', - 'pre_abc' => 'c', - 'd' => 'think:' . json_encode([urlencode('_test_中文_')]), - ]; - $this->assertEquals('b', Cookie::get('a')); - $this->assertEquals(null, Cookie::get('does_not_exist')); - $this->assertEquals('c', Cookie::get('abc', 'pre_')); - $this->assertEquals(['_test_中文_'], Cookie::get('d')); - } - - public function testDelete() - { - $_COOKIE = [ - 'a' => 'b', - 'pre_abc' => 'c', - ]; - $this->assertEquals('b', Cookie::get('a')); - Cookie::delete('a'); - $this->assertEquals(null, Cookie::get('a')); - - $this->assertEquals('c', Cookie::get('abc', 'pre_')); - Cookie::delete('abc', 'pre_'); - $this->assertEquals(null, Cookie::get('abc', 'pre_')); - } - - public function testClear() - { - $_COOKIE = []; - $this->assertEquals(null, Cookie::clear()); - - $_COOKIE = [ - 'a' => 'b', - 'pre_abc' => 'c', - ]; - Cookie::clear('pre_'); - $this->assertEquals(['a' => 'b'], $_COOKIE); - } -} diff --git a/tests/thinkphp/library/think/db/driver/.gitignore b/tests/thinkphp/library/think/db/driver/.gitignore deleted file mode 100644 index a3a0c8b5f48c0260a4cb43aa577f9b18896ee280..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/db/driver/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/tests/thinkphp/library/think/debugTest.php b/tests/thinkphp/library/think/debugTest.php deleted file mode 100644 index 12ff815f24e5d09a846e5f5273985c917b747756..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/debugTest.php +++ /dev/null @@ -1,179 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Debug测试 - * @author 大漠 - */ - -namespace tests\thinkphp\library\think; - -use think\Debug; - -class debugTest extends \PHPUnit_Framework_TestCase -{ - - /** - * - * @var Debug - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - $this->object = new Debug(); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - {} - - /** - * @covers think\Debug::remark - * @todo Implement testRemark(). - */ - public function testRemark() - { - $name = "testremarkkey"; - Debug::remark($name); - } - - /** - * @covers think\Debug::getRangeTime - * @todo Implement testGetRangeTime(). - */ - public function testGetRangeTime() - { - $start = "testGetRangeTimeStart"; - $end = "testGetRangeTimeEnd"; - Debug::remark($start); - usleep(20000); - // \think\Debug::remark($end); - - $time = Debug::getRangeTime($start, $end); - $this->assertLessThan(0.03, $time); - //$this->assertEquals(0.03, ceil($time)); - } - - /** - * @covers think\Debug::getUseTime - * @todo Implement testGetUseTime(). - */ - public function testGetUseTime() - { - $time = Debug::getUseTime(); - $this->assertLessThan(20, $time); - } - - /** - * @covers think\Debug::getThroughputRate - * @todo Implement testGetThroughputRate(). - */ - public function testGetThroughputRate() - { - usleep(100000); - $throughputRate = Debug::getThroughputRate(); - $this->assertLessThan(10, $throughputRate); - } - - /** - * @covers think\Debug::getRangeMem - * @todo Implement testGetRangeMem(). - */ - public function testGetRangeMem() - { - $start = "testGetRangeMemStart"; - $end = "testGetRangeMemEnd"; - Debug::remark($start); - $str = ""; - for ($i = 0; $i < 10000; $i++) { - $str .= "mem"; - } - - $rangeMem = Debug::getRangeMem($start, $end); - - $this->assertLessThan(33, explode(" ", $rangeMem)[0]); - } - - /** - * @covers think\Debug::getUseMem - * @todo Implement testGetUseMem(). - */ - public function testGetUseMem() - { - $useMem = Debug::getUseMem(); - - $this->assertLessThan(30, explode(" ", $useMem)[0]); - } - - /** - * @covers think\Debug::getMemPeak - * @todo Implement testGetMemPeak(). - */ - public function testGetMemPeak() - { - $start = "testGetMemPeakStart"; - $end = "testGetMemPeakEnd"; - Debug::remark($start); - $str = ""; - for ($i = 0; $i < 100000; $i++) { - $str .= "mem"; - } - $memPeak = Debug::getMemPeak($start, $end); - $this->assertLessThan(500, explode(" ", $memPeak)[0]); - } - - /** - * @covers think\Debug::getFile - * @todo Implement testGetFile(). - */ - public function testGetFile() - { - $count = Debug::getFile(); - - $this->assertEquals(count(get_included_files()), $count); - - $info = Debug::getFile(true); - $this->assertEquals(count(get_included_files()), count($info)); - - $this->assertContains("KB", $info[0]); - } - - /** - * @covers think\Debug::dump - * @todo Implement testDump(). - */ - public function testDump() - { - if (strstr(PHP_VERSION, 'hhvm')) { - return ; - } - - $var = []; - $var["key"] = "val"; - $output = Debug::dump($var, false, $label = "label"); - $array = explode("array", json_encode($output)); - if (IS_WIN) { - $this->assertEquals("(1) {\\n [\\\"key\\\"] => string(3) \\\"val\\\"\\n}\\n\\r\\n\"", end($array)); - } else if (strstr(PHP_OS, 'Darwin')) { - $this->assertEquals("(1) {\\n [\\\"key\\\"] => string(3) \\\"val\\\"\\n}\\n\\n\"", end($array)); - } else { - $this->assertEquals("(1) {\\n 'key' =>\\n string(3) \\\"val\\\"\\n}\\n\\n\"", end($array)); - } - } -} diff --git a/tests/thinkphp/library/think/display.html b/tests/thinkphp/library/think/display.html deleted file mode 100644 index e99d3025e5f416b14f042714b3ca8091f5b0255b..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/display.html +++ /dev/null @@ -1 +0,0 @@ -{$name??'default'} \ No newline at end of file diff --git a/tests/thinkphp/library/think/exceptionTest.php b/tests/thinkphp/library/think/exceptionTest.php deleted file mode 100644 index 66957ce67d8230a8aeb2924617b957c007a9688b..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/exceptionTest.php +++ /dev/null @@ -1,52 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * exception类测试 - * @author Haotong Lin - */ - -namespace tests\thinkphp\library\think; - -use ReflectionMethod; -use think\Exception as ThinkException; -use think\exception\HttpException; - -class MyException extends ThinkException -{ - -} - -class exceptionTest extends \PHPUnit_Framework_TestCase -{ - public function testGetHttpStatus() - { - try { - throw new HttpException(404, "Error Processing Request"); - } catch (HttpException $e) { - $this->assertEquals(404, $e->getStatusCode()); - } - } - - public function testDebugData() - { - $data = ['a' => 'b', 'c' => 'd']; - try { - $e = new MyException("Error Processing Request", 1); - $method = new ReflectionMethod($e, 'setData'); - $method->setAccessible(true); - $method->invokeArgs($e, ['test', $data]); - throw $e; - } catch (MyException $e) { - $this->assertEquals(['test' => $data], $e->getData()); - } - } -} diff --git a/tests/thinkphp/library/think/extend.html b/tests/thinkphp/library/think/extend.html deleted file mode 100644 index 922192dc8ed6fa5905b4417398b0d6ae3372973e..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/extend.html +++ /dev/null @@ -1,2 +0,0 @@ -{extend name="extend2" /} -{block name="head"}header{/block} \ No newline at end of file diff --git a/tests/thinkphp/library/think/extend2.html b/tests/thinkphp/library/think/extend2.html deleted file mode 100644 index eb22e1da59831251a593f1514fb629a133d1639a..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/extend2.html +++ /dev/null @@ -1,17 +0,0 @@ -{layout name="layout2" replace="[__REPLACE__]" /} -{block name="head"}{/block} -
- {include file="include" name="info" value="$info.value" /} -{block name="main"} -{block name="side"} - side -{/block} -{block name="mainbody"} - -{/block} -{/block} -{literal} - {$name} -{/literal} - -
\ No newline at end of file diff --git a/tests/thinkphp/library/think/hookTest.php b/tests/thinkphp/library/think/hookTest.php deleted file mode 100644 index 930ecf533a62b6077679d8d7a5fe6c04fa267a05..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/hookTest.php +++ /dev/null @@ -1,67 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Hook类测试 - * @author liu21st - */ - -namespace tests\thinkphp\library\think; - -use think\Hook; - -class hookTest extends \PHPUnit_Framework_TestCase -{ - - public function testRun() - { - Hook::add('my_pos', '\tests\thinkphp\library\think\behavior\One'); - Hook::add('my_pos', ['\tests\thinkphp\library\think\behavior\Two']); - Hook::add('my_pos', '\tests\thinkphp\library\think\behavior\Three', true); - $data['id'] = 0; - $data['name'] = 'thinkphp'; - Hook::listen('my_pos', $data); - $this->assertEquals(2, $data['id']); - $this->assertEquals('thinkphp', $data['name']); - $this->assertEquals([ - '\tests\thinkphp\library\think\behavior\Three', - '\tests\thinkphp\library\think\behavior\One', - '\tests\thinkphp\library\think\behavior\Two'], - Hook::get('my_pos')); - } - - public function testImport() - { - Hook::import(['my_pos' => [ - '\tests\thinkphp\library\think\behavior\One', - '\tests\thinkphp\library\think\behavior\Three'], - ]); - Hook::import(['my_pos' => ['\tests\thinkphp\library\think\behavior\Two']], false); - Hook::import(['my_pos' => ['\tests\thinkphp\library\think\behavior\Three', '_overlay' => true]]); - $data['id'] = 0; - $data['name'] = 'thinkphp'; - Hook::listen('my_pos', $data); - $this->assertEquals(3, $data['id']); - - } - - public function testExec() - { - $data['id'] = 0; - $data['name'] = 'thinkphp'; - $this->assertEquals(true, Hook::exec('\tests\thinkphp\library\think\behavior\One')); - $this->assertEquals(false, Hook::exec('\tests\thinkphp\library\think\behavior\One', 'test', $data)); - $this->assertEquals('test', $data['name']); - $this->assertEquals('Closure', Hook::exec(function (&$data) {$data['name'] = 'Closure';return 'Closure';})); - - } - -} diff --git a/tests/thinkphp/library/think/include.html b/tests/thinkphp/library/think/include.html deleted file mode 100644 index e01ae9ef878dc79d4e76da2d5db5a3269b4a1c8a..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/include.html +++ /dev/null @@ -1,2 +0,0 @@ - -{include file="include2" /} \ No newline at end of file diff --git a/tests/thinkphp/library/think/include2.html b/tests/thinkphp/library/think/include2.html deleted file mode 100644 index 24bdacb35e1fdd78182166bfc89702d4d0bd7fe9..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/include2.html +++ /dev/null @@ -1 +0,0 @@ -{$info.value}: \ No newline at end of file diff --git a/tests/thinkphp/library/think/lang/lang.php b/tests/thinkphp/library/think/lang/lang.php deleted file mode 100644 index 044b171b2fc6eb5aa14b621338dbe77b6183c187..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/lang/lang.php +++ /dev/null @@ -1,4 +0,0 @@ -'加载', -]; \ No newline at end of file diff --git a/tests/thinkphp/library/think/langTest.php b/tests/thinkphp/library/think/langTest.php deleted file mode 100644 index 360ee43dc0d8746900d451eaaf2a2f4a05814a85..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/langTest.php +++ /dev/null @@ -1,76 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Lang测试 - * @author liu21st - */ - -namespace tests\thinkphp\library\think; - -use think\Config; -use think\Lang; - -class langTest extends \PHPUnit_Framework_TestCase -{ - - public function testSetAndGet() - { - Lang::set('hello,%s', '欢迎,%s'); - $this->assertEquals('欢迎,ThinkPHP', Lang::get('hello,%s', ['ThinkPHP'])); - Lang::set('hello,%s', '歡迎,%s', 'zh-tw'); - $this->assertEquals('歡迎,ThinkPHP', Lang::get('hello,%s', ['ThinkPHP'], 'zh-tw')); - Lang::set(['hello' => '欢迎', 'use' => '使用']); - $this->assertEquals('欢迎', Lang::get('hello')); - $this->assertEquals('欢迎', Lang::get('HELLO')); - $this->assertEquals('使用', Lang::get('use')); - - Lang::set('hello,{:name}', '欢迎,{:name}'); - $this->assertEquals('欢迎,liu21st', Lang::get('hello,{:name}', ['name' => 'liu21st'])); - } - - public function testLoad() - { - Lang::load(__DIR__ . DS . 'lang' . DS . 'lang.php'); - $this->assertEquals('加载', Lang::get('load')); - Lang::load(__DIR__ . DS . 'lang' . DS . 'lang.php', 'test'); - $this->assertEquals('加载', Lang::get('load', [], 'test')); - } - - public function testDetect() - { - - Config::set('lang_list', ['zh-cn', 'zh-tw']); - Lang::set('hello', '欢迎', 'zh-cn'); - Lang::set('hello', '歡迎', 'zh-tw'); - - Config::set('lang_detect_var', 'lang'); - Config::set('lang_cookie_var', 'think_cookie'); - - $_GET['lang'] = 'zh-tw'; - Lang::detect(); - $this->assertEquals('歡迎', Lang::get('hello')); - - $_GET['lang'] = 'zh-cn'; - Lang::detect(); - $this->assertEquals('欢迎', Lang::get('hello')); - - } - - public function testRange() - { - $this->assertEquals('zh-cn', Lang::range()); - Lang::set('hello', '欢迎', 'test'); - Lang::range('test'); - $this->assertEquals('test', Lang::range()); - $this->assertEquals('欢迎', Lang::get('hello')); - } -} diff --git a/tests/thinkphp/library/think/layout.html b/tests/thinkphp/library/think/layout.html deleted file mode 100644 index be8d4a071c71a38c5775ea94707cba3ad538ede2..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/layout.html +++ /dev/null @@ -1,2 +0,0 @@ -
{__CONTENT__} -
\ No newline at end of file diff --git a/tests/thinkphp/library/think/layout2.html b/tests/thinkphp/library/think/layout2.html deleted file mode 100644 index a5b757296b666ec1edca5d49ac1dcd6eae1a170b..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/layout2.html +++ /dev/null @@ -1,2 +0,0 @@ - \ No newline at end of file diff --git a/tests/thinkphp/library/think/loader/test/Hello.php b/tests/thinkphp/library/think/loader/test/Hello.php deleted file mode 100644 index c141456183ddb411a7d56065044da6bd236f5692..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/loader/test/Hello.php +++ /dev/null @@ -1,7 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Loader测试 - * @author liu21st - */ - -namespace tests\thinkphp\library\think; - -use think\Loader; - -class loaderTest extends \PHPUnit_Framework_TestCase -{ - - public function testAutoload() - { - $this->assertEquals(false, Loader::autoload('\think\Url')); - $this->assertEquals(false, Loader::autoload('think\Test')); - $this->assertEquals(false, Loader::autoload('my\HelloTest')); - } - - public function testAddClassMap() - { - Loader::addClassMap('my\hello\Test', __DIR__ . DS . 'loader' . DS . 'Test.php'); - } - - public function testAddNamespace() - { - Loader::addNamespace('top', __DIR__ . DS . 'loader' . DS); - $this->assertEquals(true, Loader::autoload('top\test\Hello')); - } - - public function testAddNamespaceAlias() - { - Loader::addNamespaceAlias('top', 'top\test'); - Loader::addNamespaceAlias(['top' => 'top\test', 'app' => 'app\index']); - //$this->assertEquals(true, Loader::autoload('top\Hello')); - } - - public function testTable() - { - Loader::db('mysql://root@127.0.0.1/test#utf8'); - } - - public function testImport() - { - $this->assertEquals(false, Loader::import('think.log.driver.MyTest')); - } - - public function testParseName() - { - $this->assertEquals('HelloTest', Loader::parseName('hello_test', 1)); - $this->assertEquals('hello_test', Loader::parseName('HelloTest', 0)); - } - - public function testParseClass() - { - $this->assertEquals('app\index\controller\User', Loader::parseClass('index', 'controller', 'user')); - $this->assertEquals('app\index\controller\user\Type', Loader::parseClass('index', 'controller', 'user.type')); - $this->assertEquals('app\admin\model\UserType', Loader::parseClass('admin', 'model', 'user_type')); - } -} diff --git a/tests/thinkphp/library/think/model/.gitignore b/tests/thinkphp/library/think/model/.gitignore deleted file mode 100644 index a3a0c8b5f48c0260a4cb43aa577f9b18896ee280..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/model/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/tests/thinkphp/library/think/paginateTest.php b/tests/thinkphp/library/think/paginateTest.php deleted file mode 100644 index 5bbcc96128e4ff8d9f8cee40d29e183746dd141c..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/paginateTest.php +++ /dev/null @@ -1,44 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace tests\thinkphp\library\think; - - -use think\paginator\driver\Bootstrap; - -class paginateTest extends \PHPUnit_Framework_TestCase -{ - public function testPaginatorInfo() - { - $p = Bootstrap::make($array = ['item3', 'item4'], 2, 2, 4); - - $this->assertEquals(4, $p->total()); - - $this->assertEquals(2, $p->listRows()); - - $this->assertEquals(2, $p->currentPage()); - - $p2 = Bootstrap::make($array2 = ['item3', 'item4'], 2, 2, 2); - $this->assertEquals(1, $p2->currentPage()); - } - - public function testPaginatorRender() - { - $p = Bootstrap::make($array = ['item3', 'item4'], 2, 2, 100); - $render = ''; - - $this->assertEquals($render, $p->render()); - } - - - - -} \ No newline at end of file diff --git a/tests/thinkphp/library/think/requestTest.php b/tests/thinkphp/library/think/requestTest.php deleted file mode 100644 index 964b5c85969a44593bc7381ca12bc5e3098dccdc..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/requestTest.php +++ /dev/null @@ -1,186 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Db类测试 - */ - -namespace tests\thinkphp\library\think; - -use think\Config; -use think\Request; -use think\Route; - -class requestTest extends \PHPUnit_Framework_TestCase -{ - protected $request; - - public function setUp() - { - //$request = Request::create('http://www.domain.com/index/index/hello/?name=thinkphp'); - - } - - public function testCreate() - { - $request = Request::create('http://www.thinkphp.cn/index/index/hello.html?name=thinkphp'); - $this->assertEquals('http://www.thinkphp.cn', $request->domain()); - $this->assertEquals('/index/index/hello.html?name=thinkphp', $request->url()); - $this->assertEquals('/index/index/hello.html', $request->baseurl()); - $this->assertEquals('index/index/hello.html', $request->pathinfo()); - $this->assertEquals('index/index/hello', $request->path()); - $this->assertEquals('html', $request->ext()); - $this->assertEquals('name=thinkphp', $request->query()); - $this->assertEquals('www.thinkphp.cn', $request->host()); - $this->assertEquals(80, $request->port()); - $this->assertEquals($_SERVER['REQUEST_TIME'], $request->time()); - $this->assertEquals($_SERVER['REQUEST_TIME_FLOAT'], $request->time(true)); - $this->assertEquals('GET', $request->method()); - $this->assertEquals(['name' => 'thinkphp'], $request->param()); - $this->assertFalse($request->isSsl()); - $this->assertEquals('http', $request->scheme()); - } - - public function testDomain() - { - $request = Request::instance(); - $request->domain('http://thinkphp.cn'); - $this->assertEquals('http://thinkphp.cn', $request->domain()); - } - - public function testUrl() - { - $request = Request::instance(); - $request->url('/index.php/index/hello?name=thinkphp'); - $this->assertEquals('/index.php/index/hello?name=thinkphp', $request->url()); - $this->assertEquals('http://thinkphp.cn/index.php/index/hello?name=thinkphp', $request->url(true)); - } - - public function testBaseUrl() - { - $request = Request::instance(); - $request->baseurl('/index.php/index/hello'); - $this->assertEquals('/index.php/index/hello', $request->baseurl()); - $this->assertEquals('http://thinkphp.cn/index.php/index/hello', $request->baseurl(true)); - } - - public function testbaseFile() - { - $request = Request::instance(); - $request->basefile('/index.php'); - $this->assertEquals('/index.php', $request->basefile()); - $this->assertEquals('http://thinkphp.cn/index.php', $request->basefile(true)); - } - - public function testroot() - { - $request = Request::instance(); - $request->root('/index.php'); - $this->assertEquals('/index.php', $request->root()); - $this->assertEquals('http://thinkphp.cn/index.php', $request->root(true)); - } - - public function testType() - { - $request = Request::instance(); - $_SERVER['HTTP_ACCEPT'] = 'application/json'; - $this->assertEquals('json', $request->type()); - $request->mimeType('test', 'application/test'); - $request->mimeType(['test' => 'application/test']); - $_SERVER['HTTP_ACCEPT'] = 'application/test'; - $this->assertEquals('test', $request->type()); - } - - public function testmethod() - { - $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE'; - - $request = new Request(); - $this->assertEquals('DELETE', $request->method()); - $this->assertEquals('GET', $request->method(true)); - - Config::set('var_method', '_method'); - $_POST['_method'] = 'POST'; - $request = new Request(); - $this->assertEquals('POST', $request->method()); - $this->assertEquals('GET', $request->method(true)); - $this->assertTrue($request->isPost()); - $this->assertFalse($request->isGet()); - $this->assertFalse($request->isPut()); - $this->assertFalse($request->isDelete()); - $this->assertFalse($request->isHead()); - $this->assertFalse($request->isPatch()); - $this->assertFalse($request->isOptions()); - } - - public function testCli() - { - $request = Request::instance(); - $this->assertTrue($request->isCli()); - } - - public function testVar() - { - Config::set('app_multi_module', true); - $request = new Request(); - $request->route(['name' => 'thinkphp', 'id' => 6]); - $request->get(['id' => 10]); - $request->post(['id' => 8]); - $request->put(['id' => 7]); - $request->request(['test' => 'value']); - $this->assertEquals(['name' => 'thinkphp', 'id' => 6], $request->route()); - //$this->assertEquals(['id' => 10], $request->get()); - $this->assertEquals('thinkphp', $request->route('name')); - $this->assertEquals('default', $request->route('test', 'default')); - $this->assertEquals(10, $request->get('id')); - $this->assertEquals(0, $request->get('ids', 0)); - $this->assertEquals(8, $request->post('id')); - $this->assertEquals(7, $request->put('id')); - $this->assertEquals('value', $request->request('test')); - $this->assertEquals('thinkphp', $request->param('name')); - $this->assertEquals(6, $request->param('id')); - $this->assertFalse($request->has('user_id')); - $this->assertTrue($request->has('test', 'request')); - $this->assertEquals(['id' => 6], $request->only('id')); - $this->assertEquals(['name' => 'thinkphp', 'lang' => 'zh-cn'], $request->except('id')); - $this->assertEquals('THINKPHP', $request->param('name', '', 'strtoupper')); - } - - public function testIsAjax() - { - $request = new Request(); - $_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest'; - $this->assertTrue($request->isAjax()); - } - - public function testIsPjax() - { - $request = new Request(); - $_SERVER['HTTP_X_PJAX'] = true; - $this->assertTrue($request->isPjax()); - } - - public function testIsMobile() - { - $request = new Request(); - $_SERVER['HTTP_VIA'] = 'wap'; - $this->assertTrue($request->isMobile()); - } - - public function testBind() - { - $request = new Request(); - $request->user = 'User1'; - $request->bind(['user' => 'User2']); - $this->assertEquals('User2', $request->user); - } - -} diff --git a/tests/thinkphp/library/think/responseTest.php b/tests/thinkphp/library/think/responseTest.php deleted file mode 100644 index aa21a4b6a6224e303a2e676d0654e0019acf7ce7..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/responseTest.php +++ /dev/null @@ -1,95 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Response测试 - * @author 大漠 - */ - -namespace tests\thinkphp\library\think; - -use think\Config; -use think\Request; -use think\Response; - -class responseTest extends \PHPUnit_Framework_TestCase -{ - - /** - * - * @var \think\Response - */ - protected $object; - - protected $default_return_type; - - protected $default_ajax_return; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - // 1. - // restore_error_handler(); - // Warning: Cannot modify header information - headers already sent by (output started at PHPUnit\Util\Printer.php:173) - // more see in https://www.analysisandsolutions.com/blog/html/writing-phpunit-tests-for-wordpress-plugins-wp-redirect-and-continuing-after-php-errors.htm - - // 2. - // the Symfony used the HeaderMock.php - - // 3. - // not run the eclipse will held, and travis-ci.org Searching for coverage reports - // **> Python coverage not found - // **> No coverage report found. - // add the - // /** - // * @runInSeparateProcess - // */ - if (!$this->default_return_type) { - $this->default_return_type = Config::get('default_return_type'); - } - if (!$this->default_ajax_return) { - $this->default_ajax_return = Config::get('default_ajax_return'); - } - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - Config::set('default_ajax_return', $this->default_ajax_return); - Config::set('default_return_type', $this->default_return_type); - } - - /** - * @covers think\Response::send - * @todo Implement testSend(). - */ - public function testSend() - { - $dataArr = []; - $dataArr["key"] = "value"; - - $response = Response::create($dataArr, 'json'); - $result = $response->getContent(); - $this->assertEquals('{"key":"value"}', $result); - $request = Request::instance(); - $request->get(['callback' => 'callback']); - $response = Response::create($dataArr, 'jsonp'); - $result = $response->getContent(); - $this->assertEquals('callback({"key":"value"});', $result); - } - -} diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php deleted file mode 100644 index d6790347461d3036c384cee3a634afaf6ec4781d..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/routeTest.php +++ /dev/null @@ -1,287 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Route测试 - * @author liu21st - */ - -namespace tests\thinkphp\library\think; - -use think\Config; -use think\Request; -use think\Route; - -class routeTest extends \PHPUnit_Framework_TestCase -{ - - protected function setUp() - { - Config::set('app_multi_module', true); - } - - public function testRegister() - { - $request = Request::instance(); - Route::get('hello/:name', 'index/hello'); - Route::get(['hello/:name' => 'index/hello']); - Route::post('hello/:name', 'index/post'); - Route::put('hello/:name', 'index/put'); - Route::delete('hello/:name', 'index/delete'); - Route::patch('hello/:name', 'index/patch'); - Route::any('user/:id', 'index/user'); - $result = Route::check($request, 'hello/thinkphp'); - $this->assertEquals([null, 'index', 'hello'], $result['module']); - $this->assertEquals(['hello' => true, 'user/:id' => true, 'hello/:name' => ['rule' => 'hello/:name', 'route' => 'index/hello', 'var' => ['name' => 1], 'option' => [], 'pattern' => []]], Route::rules('GET')); - Route::rule('type1/:name', 'index/type', 'PUT|POST'); - Route::rule(['type2/:name' => 'index/type1']); - Route::rule([['type3/:name', 'index/type2', ['method' => 'POST']]]); - Route::rule(['name', 'type4/:name'], 'index/type4'); - } - - public function testImport() - { - $rule = [ - '__domain__' => ['subdomain2.thinkphp.cn' => 'blog1'], - '__alias__' => ['blog1' => 'blog1'], - '__rest__' => ['res' => ['index/blog']], - 'bbb' => ['index/blog1', ['method' => 'POST']], - 'ddd' => '', - ['hello1/:ddd', 'index/hello1', ['method' => 'POST']], - ]; - Route::import($rule); - } - - public function testResource() - { - $request = Request::instance(); - Route::resource('res', 'index/blog'); - Route::resource(['res' => ['index/blog']]); - $result = Route::check($request, 'res'); - $this->assertEquals(['index', 'blog', 'index'], $result['module']); - $result = Route::check($request, 'res/create'); - $this->assertEquals(['index', 'blog', 'create'], $result['module']); - $result = Route::check($request, 'res/8'); - $this->assertEquals(['index', 'blog', 'read'], $result['module']); - $result = Route::check($request, 'res/8/edit'); - $this->assertEquals(['index', 'blog', 'edit'], $result['module']); - - Route::resource('blog.comment', 'index/comment'); - $result = Route::check($request, 'blog/8/comment/10'); - $this->assertEquals(['index', 'comment', 'read'], $result['module']); - $result = Route::check($request, 'blog/8/comment/10/edit'); - $this->assertEquals(['index', 'comment', 'edit'], $result['module']); - - } - - public function testRest() - { - $request = Request::instance(); - Route::rest('read', ['GET', '/:id', 'look']); - Route::rest('create', ['GET', '/create', 'add']); - Route::rest(['read' => ['GET', '/:id', 'look'], 'create' => ['GET', '/create', 'add']]); - Route::resource('res', 'index/blog'); - $result = Route::check($request, 'res/create'); - $this->assertEquals(['index', 'blog', 'add'], $result['module']); - $result = Route::check($request, 'res/8'); - $this->assertEquals(['index', 'blog', 'look'], $result['module']); - - } - - public function testMixVar() - { - $request = Request::instance(); - Route::get('hello-', 'index/hello', [], ['name' => '\w+']); - $result = Route::check($request, 'hello-thinkphp'); - $this->assertEquals([null, 'index', 'hello'], $result['module']); - Route::get('hello-', 'index/hello', [], ['name' => '\w+', 'id' => '\d+']); - $result = Route::check($request, 'hello-thinkphp2016'); - $this->assertEquals([null, 'index', 'hello'], $result['module']); - Route::get('hello-/[:id]', 'index/hello', [], ['name' => '\w+', 'id' => '\d+']); - $result = Route::check($request, 'hello-thinkphp/2016'); - $this->assertEquals([null, 'index', 'hello'], $result['module']); - } - - public function testParseUrl() - { - $result = Route::parseUrl('hello'); - $this->assertEquals(['hello', null, null], $result['module']); - $result = Route::parseUrl('index/hello'); - $this->assertEquals(['index', 'hello', null], $result['module']); - $result = Route::parseUrl('index/hello?name=thinkphp'); - $this->assertEquals(['index', 'hello', null], $result['module']); - $result = Route::parseUrl('index/user/hello'); - $this->assertEquals(['index', 'user', 'hello'], $result['module']); - $result = Route::parseUrl('index/user/hello/name/thinkphp'); - $this->assertEquals(['index', 'user', 'hello'], $result['module']); - $result = Route::parseUrl('index-index-hello', '-'); - $this->assertEquals(['index', 'index', 'hello'], $result['module']); - } - - public function testCheckRoute() - { - Route::get('hello/:name', 'index/hello'); - Route::get('blog/:id', 'blog/read', [], ['id' => '\d+']); - $request = Request::instance(); - $this->assertEquals(false, Route::check($request, 'test/thinkphp')); - $this->assertEquals(false, Route::check($request, 'blog/thinkphp')); - $result = Route::check($request, 'blog/5'); - $this->assertEquals([null, 'blog', 'read'], $result['module']); - $result = Route::check($request, 'hello/thinkphp/abc/test'); - $this->assertEquals([null, 'index', 'hello'], $result['module']); - } - - public function testCheckRouteGroup() - { - $request = Request::instance(); - Route::pattern(['id' => '\d+']); - Route::pattern('name', '\w{6,25}'); - Route::group('group', [':id' => 'index/hello', ':name' => 'index/say']); - $this->assertEquals(false, Route::check($request, 'empty/think')); - $result = Route::check($request, 'group/think'); - $this->assertEquals(false, $result['module']); - $result = Route::check($request, 'group/10'); - $this->assertEquals([null, 'index', 'hello'], $result['module']); - $result = Route::check($request, 'group/thinkphp'); - $this->assertEquals([null, 'index', 'say'], $result['module']); - Route::group('group2', function () { - Route::group('group3', [':id' => 'index/hello', ':name' => 'index/say']); - Route::rule(':name', 'index/hello'); - Route::auto('index'); - }); - $result = Route::check($request, 'group2/thinkphp'); - $this->assertEquals([null, 'index', 'hello'], $result['module']); - $result = Route::check($request, 'group2/think'); - $this->assertEquals(['index', 'group2', 'think'], $result['module']); - $result = Route::check($request, 'group2/group3/thinkphp'); - $this->assertEquals([null, 'index', 'say'], $result['module']); - Route::group('group4', function () { - Route::group('group3', [':id' => 'index/hello', ':name' => 'index/say']); - Route::rule(':name', 'index/hello'); - Route::miss('index/__miss__'); - }); - $result = Route::check($request, 'group4/thinkphp'); - $this->assertEquals([null, 'index', 'hello'], $result['module']); - $result = Route::check($request, 'group4/think'); - $this->assertEquals([null, 'index', '__miss__'], $result['module']); - - Route::group(['prefix' => 'prefix/'], function () { - Route::rule('hello4/:name', 'hello'); - }); - Route::group(['prefix' => 'prefix/'], [ - 'hello4/:name' => 'hello', - ]); - $result = Route::check($request, 'hello4/thinkphp'); - $this->assertEquals([null, 'prefix', 'hello'], $result['module']); - Route::group('group5', [ - [':name', 'hello', ['method' => 'GET|POST']], - ':id' => 'hello', - ], ['prefix' => 'prefix/']); - $result = Route::check($request, 'group5/thinkphp'); - $this->assertEquals([null, 'prefix', 'hello'], $result['module']); - } - - public function testControllerRoute() - { - $request = Request::instance(); - Route::controller('controller', 'index/Blog'); - $result = Route::check($request, 'controller/info'); - $this->assertEquals(['index', 'Blog', 'getinfo'], $result['module']); - Route::setMethodPrefix('GET', 'read'); - Route::setMethodPrefix(['get' => 'read']); - Route::controller('controller', 'index/Blog'); - $result = Route::check($request, 'controller/phone'); - $this->assertEquals(['index', 'Blog', 'readphone'], $result['module']); - } - - public function testAliasRoute() - { - $request = Request::instance(); - Route::alias('alias', 'index/Alias'); - $result = Route::check($request, 'alias/info'); - $this->assertEquals('index/Alias/info', $result['module']); - } - - public function testRouteToModule() - { - $request = Request::instance(); - Route::get('hello/:name', 'index/hello'); - Route::get('blog/:id', 'blog/read', [], ['id' => '\d+']); - $this->assertEquals(false, Route::check($request, 'test/thinkphp')); - $this->assertEquals(false, Route::check($request, 'blog/thinkphp')); - $result = Route::check($request, 'hello/thinkphp'); - $this->assertEquals([null, 'index', 'hello'], $result['module']); - $result = Route::check($request, 'blog/5'); - $this->assertEquals([null, 'blog', 'read'], $result['module']); - } - - public function testRouteToController() - { - $request = Request::instance(); - Route::get('say/:name', '@index/hello'); - $this->assertEquals(['type' => 'controller', 'controller' => 'index/hello'], Route::check($request, 'say/thinkphp')); - } - - public function testRouteToMethod() - { - $request = Request::instance(); - Route::get('user/:name', '\app\index\service\User::get', [], ['name' => '\w+']); - Route::get('info/:name', '\app\index\model\Info@getInfo', [], ['name' => '\w+']); - $this->assertEquals(['type' => 'method', 'method' => '\app\index\service\User::get'], Route::check($request, 'user/thinkphp')); - $this->assertEquals(['type' => 'method', 'method' => ['\app\index\model\Info', 'getInfo']], Route::check($request, 'info/thinkphp')); - } - - public function testRouteToRedirect() - { - $request = Request::instance(); - Route::get('art/:id', '/article/read/id/:id', [], ['id' => '\d+']); - $this->assertEquals(['type' => 'redirect', 'url' => '/article/read/id/8', 'status' => 301], Route::check($request, 'art/8')); - } - - public function testBind() - { - $request = Request::instance(); - Route::bind('index/blog'); - Route::get('blog/:id', 'index/blog/read'); - $result = Route::check($request, 'blog/10'); - $this->assertEquals(['index', 'blog', 'read'], $result['module']); - $result = Route::parseUrl('test'); - $this->assertEquals(['index', 'blog', 'test'], $result['module']); - - Route::bind('\app\index\controller', 'namespace'); - $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read']], Route::check($request, 'blog/read')); - - Route::bind('\app\index\controller\blog', 'class'); - $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read']], Route::check($request, 'read')); - } - - public function testDomain() - { - $request = Request::create('http://subdomain.thinkphp.cn'); - Route::domain('subdomain.thinkphp.cn', 'sub?abc=test&status=1'); - $rules = Route::rules('GET'); - Route::checkDomain($request, $rules); - $this->assertEquals('sub', Route::getbind('module')); - $this->assertEquals('test', $_GET['abc']); - $this->assertEquals(1, $_GET['status']); - - Route::domain('subdomain.thinkphp.cn', '\app\index\controller'); - $rules = Route::rules('GET'); - Route::checkDomain($request, $rules); - $this->assertEquals('\app\index\controller', Route::getbind('namespace')); - - Route::domain(['subdomain.thinkphp.cn' => '@\app\index\controller\blog']); - $rules = Route::rules('GET'); - Route::checkDomain($request, $rules); - $this->assertEquals('\app\index\controller\blog', Route::getbind('class')); - - } -} diff --git a/tests/thinkphp/library/think/session/.gitignore b/tests/thinkphp/library/think/session/.gitignore deleted file mode 100644 index a3a0c8b5f48c0260a4cb43aa577f9b18896ee280..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/session/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/tests/thinkphp/library/think/sessionTest.php b/tests/thinkphp/library/think/sessionTest.php deleted file mode 100644 index ab3e64f499175f721c5b6cd4a046c1152b83d5ac..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/sessionTest.php +++ /dev/null @@ -1,319 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Session测试 - * @author 大漠 - */ - -namespace tests\thinkphp\library\think; - -use think\Session; - -class sessionTest extends \PHPUnit_Framework_TestCase -{ - - /** - * - * @var \think\Session - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - // $this->object = new Session (); - // register_shutdown_function ( function () { - // } ); // 此功能无法取消,需要回调函数配合。 - set_exception_handler(function () {}); - set_error_handler(function () {}); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - register_shutdown_function('think\Error::appShutdown'); - set_error_handler('think\Error::appError'); - set_exception_handler('think\Error::appException'); - } - - /** - * @covers think\Session::prefix - * - * @todo Implement testPrefix(). - */ - public function testPrefix() - { - Session::prefix(null); - Session::prefix('think_'); - - $this->assertEquals('think_', Session::prefix()); - } - - /** - * @covers think\Session::init - * - * @todo Implement testInit(). - */ - public function testInit() - { - Session::prefix(null); - $config = [ - // cookie 名称前缀 - 'prefix' => 'think_', - // cookie 保存时间 - 'expire' => 60, - // cookie 保存路径 - 'path' => '/path/to/test/session/', - // cookie 有效域名 - 'domain' => '.thinkphp.cn', - 'var_session_id' => 'sessionidtest', - 'id' => 'sess_8fhgkjuakhatbeg2fa14lo84q1', - 'name' => 'session_name', - 'use_trans_sid' => '1', - 'use_cookies' => '1', - 'cache_limiter' => '60', - 'cache_expire' => '60', - 'type' => '', // memcache - 'namespace' => '\\think\\session\\driver\\', // ? - 'auto_start' => '1', - ]; - - $_REQUEST[$config['var_session_id']] = $config['id']; - Session::init($config); - - // 开始断言 - $this->assertEquals($config['prefix'], Session::prefix()); - $this->assertEquals($config['id'], $_REQUEST[$config['var_session_id']]); - $this->assertEquals($config['name'], session_name()); - - $this->assertEquals($config['path'], session_save_path()); - $this->assertEquals($config['use_cookies'], ini_get('session.use_cookies')); - $this->assertEquals($config['domain'], ini_get('session.cookie_domain')); - $this->assertEquals($config['expire'], ini_get('session.gc_maxlifetime')); - $this->assertEquals($config['expire'], ini_get('session.cookie_lifetime')); - - $this->assertEquals($config['cache_limiter'], session_cache_limiter($config['cache_limiter'])); - $this->assertEquals($config['cache_expire'], session_cache_expire($config['cache_expire'])); - - // 检测分支 - $_REQUEST[$config['var_session_id']] = null; - session_write_close(); - session_destroy(); - - Session::init($config); - - // 测试auto_start - // PHP_SESSION_DISABLED - // PHP_SESSION_NONE - // PHP_SESSION_ACTIVE - // session_status() - if (strstr(PHP_VERSION, 'hhvm')) { - $this->assertEquals('', ini_get('session.auto_start')); - } else { - $this->assertEquals(0, ini_get('session.auto_start')); - } - - $this->assertEquals($config['use_trans_sid'], ini_get('session.use_trans_sid')); - - Session::init($config); - $this->assertEquals($config['id'], session_id()); - } - - /** - * 单独重现异常 - * @expectedException \think\Exception - */ - public function testException() - { - $config = [ - // cookie 名称前缀 - 'prefix' => 'think_', - // cookie 保存时间 - 'expire' => 0, - // cookie 保存路径 - 'path' => '/path/to/test/session/', - // cookie 有效域名 - 'domain' => '.thinkphp.cn', - 'var_session_id' => 'sessionidtest', - 'id' => 'sess_8fhgkjuakhatbeg2fa14lo84q1', - 'name' => 'session_name', - 'use_trans_sid' => '1', - 'use_cookies' => '1', - 'cache_limiter' => '60', - 'cache_expire' => '60', - 'type' => '\\think\\session\\driver\\Memcache', // - 'auto_start' => '1', - ]; - - // 测试session驱动是否存在 - // @expectedException 异常类名 - $this->setExpectedException('\think\exception\ClassNotFoundException', 'error session handler'); - - Session::init($config); - } - - /** - * @covers think\Session::set - * - * @todo Implement testSet(). - */ - public function testSet() - { - Session::prefix(null); - Session::set('sessionname', 'sessionvalue'); - $this->assertEquals('sessionvalue', $_SESSION['sessionname']); - - Session::set('sessionnamearr.subname', 'sessionvalue'); - $this->assertEquals('sessionvalue', $_SESSION['sessionnamearr']['subname']); - - Session::set('sessionnameper', 'sessionvalue', 'think_'); - $this->assertEquals('sessionvalue', $_SESSION['think_']['sessionnameper']); - - Session::set('sessionnamearrper.subname', 'sessionvalue', 'think_'); - $this->assertEquals('sessionvalue', $_SESSION['think_']['sessionnamearrper']['subname']); - } - - /** - * @covers think\Session::get - * - * @todo Implement testGet(). - */ - public function testGet() - { - Session::prefix(null); - - Session::set('sessionnameget', 'sessionvalue'); - $this->assertEquals(Session::get('sessionnameget'), $_SESSION['sessionnameget']); - - Session::set('sessionnamegetarr.subname', 'sessionvalue'); - $this->assertEquals(Session::get('sessionnamegetarr.subname'), $_SESSION['sessionnamegetarr']['subname']); - - Session::set('sessionnamegetarrperall', 'sessionvalue', 'think_'); - $this->assertEquals(Session::get('', 'think_')['sessionnamegetarrperall'], $_SESSION['think_']['sessionnamegetarrperall']); - - Session::set('sessionnamegetper', 'sessionvalue', 'think_'); - $this->assertEquals(Session::get('sessionnamegetper', 'think_'), $_SESSION['think_']['sessionnamegetper']); - - Session::set('sessionnamegetarrper.subname', 'sessionvalue', 'think_'); - $this->assertEquals(Session::get('sessionnamegetarrper.subname', 'think_'), $_SESSION['think_']['sessionnamegetarrper']['subname']); - } - - public function testPull() - { - Session::prefix(null); - Session::set('sessionnamedel', 'sessionvalue'); - $this->assertEquals('sessionvalue', Session::pull('sessionnameget')); - $this->assertNull(Session::get('sessionnameget')); - } - - /** - * @covers think\Session::delete - * - * @todo Implement testDelete(). - */ - public function testDelete() - { - Session::prefix(null); - Session::set('sessionnamedel', 'sessionvalue'); - Session::delete('sessionnamedel'); - $this->assertEmpty($_SESSION['sessionnamedel']); - - Session::set('sessionnamedelarr.subname', 'sessionvalue'); - Session::delete('sessionnamedelarr.subname'); - $this->assertEmpty($_SESSION['sessionnamedelarr']['subname']); - - Session::set('sessionnamedelper', 'sessionvalue', 'think_'); - Session::delete('sessionnamedelper', 'think_'); - $this->assertEmpty($_SESSION['think_']['sessionnamedelper']); - - Session::set('sessionnamedelperarr.subname', 'sessionvalue', 'think_'); - Session::delete('sessionnamedelperarr.subname', 'think_'); - $this->assertEmpty($_SESSION['think_']['sessionnamedelperarr']['subname']); - } - - /** - * @covers think\Session::clear - * - * @todo Implement testClear(). - */ - public function testClear() - { - Session::prefix(null); - - Session::set('sessionnameclsper', 'sessionvalue1', 'think_'); - Session::clear('think_'); - $this->assertNull($_SESSION['think_']); - - Session::set('sessionnameclsper', 'sessionvalue1', 'think_'); - Session::clear(); - $this->assertEmpty($_SESSION); - } - - /** - * @covers think\Session::has - * - * @todo Implement testHas(). - */ - public function testHas() - { - Session::prefix(null); - Session::set('sessionnamehas', 'sessionvalue'); - $this->assertTrue(Session::has('sessionnamehas')); - - Session::set('sessionnamehasarr.subname', 'sessionvalue'); - $this->assertTrue(Session::has('sessionnamehasarr.subname')); - - Session::set('sessionnamehasper', 'sessionvalue', 'think_'); - $this->assertTrue(Session::has('sessionnamehasper', 'think_')); - - Session::set('sessionnamehasarrper.subname', 'sessionvalue', 'think_'); - $this->assertTrue(Session::has('sessionnamehasarrper.subname', 'think_')); - } - - /** - * @covers think\Session::pause - * - * @todo Implement testPause(). - */ - public function testPause() - { - Session::pause(); - } - - /** - * @covers think\Session::start - * - * @todo Implement testStart(). - */ - public function testStart() - { - Session::start(); - } - - /** - * @covers think\Session::destroy - * - * @todo Implement testDestroy(). - */ - public function testDestroy() - { - Session::set('sessionnamedestroy', 'sessionvalue'); - Session::destroy(); - $this->assertEmpty($_SESSION['sessionnamedestroy']); - } -} diff --git a/tests/thinkphp/library/think/template/driver/.gitignore b/tests/thinkphp/library/think/template/driver/.gitignore deleted file mode 100644 index a3a0c8b5f48c0260a4cb43aa577f9b18896ee280..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/template/driver/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/tests/thinkphp/library/think/template/taglib/cxTest.php b/tests/thinkphp/library/think/template/taglib/cxTest.php deleted file mode 100644 index a77824b69caa144942a327d8740b8847bda5fce5..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/template/taglib/cxTest.php +++ /dev/null @@ -1,575 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * 模板测试 - * @author Haotong Lin - */ - -namespace tests\thinkphp\library\think\tempplate\taglib; - -use think\Template; -use think\template\taglib\Cx; - -class templateTest extends \PHPUnit_Framework_TestCase -{ - public function testPhp() - { - $template = new template(); - $cx = new Cx($template); - - $content = << -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - } - - public function testVolist() - { - $template = new template(); - $cx = new Cx($template); - - $content = <<\$vo): \$mod = (\$key % 2 );++\$key;?> - - -EOF; - $cx->parseTag($content); - $this->assertEquals($data, $content); - - $content = <<display($content, ['list' => [1, 2, 3, 4, 5]]); - $this->expectOutputString('234'); - } - - public function testForeach() - { - $template = new template(); - $cx = new Cx($template); - - $content = <<\$val} - -{/foreach} -EOF; - $data = <<\$val): ?> - - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = <<\$val): ?> - - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = <<display($content); - $this->expectOutputString('234'); - } - - public function testIf() - { - $template = new template(); - $cx = new Cx($template); - - $content = << -one - -two - -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - } - - public function testSwitch() - { - $template = new template(); - $cx = new Cx($template); - - $content = << - -a - - -b - - -d - - -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - } - - public function testCompare() - { - $template = new template(); - $cx = new Cx($template); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << '0'): ?> -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = <<= '0'): ?> -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - } - - public function testRange() - { - $template = new template(); - $cx = new Cx($template); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = <<display($content); - $this->expectOutputString('yesno'); - } - - public function testPresent() - { - $template = new template(); - $cx = new Cx($template); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - } - - public function testEmpty() - { - $template = new template(); - $cx = new Cx($template); - - $content = <<isEmpty())): ?> -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = <<isEmpty()))): ?> -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - } - - public function testDefined() - { - $template = new template(); - $cx = new Cx($template); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -default - -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - } - - public function testImport() - { - $template = new template(); - $cx = new Cx($template); - - $content = << -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - } - - public function testAssign() - { - $template = new template(); - $cx = new Cx($template); - - $content = << -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - } - - public function testDefine() - { - $template = new template(); - $cx = new Cx($template); - - $content = << -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - - $content = << -EOF; - $cx->parseTag($content); - $this->assertEquals($content, $data); - } - - public function testFor() - { - $template = new template(); - - $content = <<display($content); - $this->expectOutputString('123456789'); - } - public function testUrl() - { - $template = new template(); - $content = <<display($content); - $this->expectOutputString(\think\Url::build('Index/index')); - } - - public function testFunction() - { - $template = new template(); - $data = [ - 'list' => ['language' => 'php', 'version' => ['5.4', '5.5']], - 'a' => '[', - 'b' => ']', - ]; - - $content = <<\$val} -{if is_array(\$val)} -{~\$func(\$val)} -{else} -{if !is_numeric(\$key)} -{\$key.':'.\$val.','} -{else} -{\$a.\$val.\$b} -{/if} -{/if} -{/foreach} -{/function} -EOF; - $template->display($content, $data); - $this->expectOutputString("language:php,[5.4][5.5]"); - } -} diff --git a/tests/thinkphp/library/think/templateTest.php b/tests/thinkphp/library/think/templateTest.php deleted file mode 100644 index 29100f4d9fd46096c7d9f14f9c79b1090c1d56e1..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/templateTest.php +++ /dev/null @@ -1,414 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * 模板测试 - * @author oldrind - */ - -namespace tests\thinkphp\library\think; - -use think\Template; - -class templateTest extends \PHPUnit_Framework_TestCase -{ - public function testVar() - { - $template = new Template(); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = <<parse($content); - $this->assertEquals($data, $content); - - $content = <<parse($content); - $this->assertEquals($data, $content); - - } - - public function testVarFunction() - { - $template = new Template(); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << - -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - } - - public function testVarIdentify() - { - $config['tpl_begin'] = '<#'; - $config['tpl_end'] = '#>'; - $config['tpl_var_identify'] = ''; - $template = new Template($config); - - $content = << -EOF; - $data = <<a)) ? (is_array(\$info)?\$info['a']:\$info->a) : 'test'; ?> -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - $data = <<a)) echo 'test'; ?> -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - $data = <<a)==(is_array(\$info)?\$info['b']:\$info->b)) echo 'test'; ?> -EOF; - - $template->parse($content); - $this->assertEquals($data, $content); - - $content = << -EOF; - $data = <<a) !== ''?(is_array(\$info)?\$info['a']:\$info->a):'test')?'yes':'no'; ?> -EOF; - $template->parse($content); - $this->assertEquals($data, $content); - - $template2 = new Template(); - $template2->tpl_var_identify = 'obj'; - $content = <<b)?'yes':'no'; ?> -EOF; - $template2->parse($content); - $this->assertEquals($data, $content); - } - - public function testThinkVar() - { - $config['tpl_begin'] = '{'; - $config['tpl_end'] = '}'; - $template = new Template($config); - - $_SERVER['SERVER_NAME'] = 'server_name'; - $_GET['action'] = 'action'; - $_POST['action'] = 'action'; - $_COOKIE['name'] = 'name'; - $_SESSION['action'] = ['name' => 'name']; - define('SITE_NAME', 'site_name'); - - $content = << -{\$Think.GET.action}
-{\$Think.POST.action}
-{\$Think.COOKIE.action}
-{\$Think.COOKIE.action.name}
-{\$Think.SESSION.action}
-{\$Think.SESSION.action.name}
-{\$Think.ENV.OS}
-{\$Think.REQUEST.action}
-{\$Think.CONST.SITE_NAME}
-{\$Think.LANG.action}
-{\$Think.CONFIG.action.name}
-{\$Think.NOW}
-{\$Think.VERSION}
-{\$Think.LDELIM}
-{\$Think.RDELIM}
-{\$Think.SITE_NAME}
-{\$Think.SITE.URL} -EOF; - $data = <<
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -EOF; - $template->parse($content); - $this->assertEquals($data, $content); - } - - public function testFetch() - { - $template = new Template(); - $template->assign('name', 'name'); - $config = [ - 'strip_space' => true, - 'view_path' => dirname(__FILE__) . DS, - 'cache_id' => '__CACHE_ID__', - 'display_cache' => true, - ]; - $data = ['name' => 'value']; - $template->layout('layout')->fetch('display', $data, $config); - $this->expectOutputString('value'); - } - - public function testDisplay() - { - $config['view_path'] = dirname(__FILE__) . DS; - $config['view_suffix'] = '.html'; - $config['layout_on'] = true; - $config['layout_name'] = 'layout'; - $template = new Template($config); - $files = ['extend' => 'extend', 'include' => 'include']; - $template->assign('files', $files); - $template->assign('user', ['name' => 'name', 'account' => 100]); - $template->assign('message', 'message'); - $template->assign('info', ['value' => 'value']); - - $content = << -header -
- -value: - -main - - - side - - -value: - message{\$message} - - - mainbody - - - - {\$name} - - php code
- -EOF; - $template->display($content); - $this->expectOutputString($content2); -// $template->parse($content); - // var_dump($content); - } - - public function testVarAssign() - { - $template = new Template(); - $template->assign('name', 'value'); - $value = $template->get('name'); - $this->assertEquals('value', $value); - } - - public function testVarGet() - { - $template = new Template(); - $data = ['a' => 'a', 'b' => 'b']; - $template->assign($data); - $this->assertEquals($data, $template->get()); - } - - public function testIsCache() - { - $template = new Template(['cache_id' => '__CACHE_ID__', 'display_cache' => true]); - $this->assertTrue($template->isCache('__CACHE_ID__')); - $template->display_cache = false; - $this->assertTrue(!$template->isCache('__CACHE_ID__')); - } -} diff --git a/tests/thinkphp/library/think/urlTest.php b/tests/thinkphp/library/think/urlTest.php deleted file mode 100644 index 94dfc71d628896385f624127e6810e9c414011b3..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/urlTest.php +++ /dev/null @@ -1,116 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Url测试 - * @author liu21st - */ - -namespace tests\thinkphp\library\think; - -use think\Config; -use think\Route; -use think\Url; - -class urlTest extends \PHPUnit_Framework_TestCase -{ - - public function setUp() - { - Route::rules([]); - Route::name([]); - } - - public function testBuildModule() - { - - Route::get('blog/:name', 'index/blog'); - Route::get('blog/:id', 'index/blog'); - Config::set('pathinfo_depr', '/'); - Config::set('url_html_suffix', ''); - - $this->assertEquals('/blog/thinkphp', Url::build('index/blog?name=thinkphp')); - $this->assertEquals('/blog/thinkphp.html', Url::build('index/blog', 'name=thinkphp', 'html')); - $this->assertEquals('/blog/10', Url::build('index/blog?id=10')); - $this->assertEquals('/blog/10.html', Url::build('index/blog', 'id=10', 'html')); - - Route::get('item-', 'blog/item', [], ['name' => '\w+', 'id' => '\d+']); - $this->assertEquals('/item-thinkphp', Url::build('blog/item?name=thinkphp')); - $this->assertEquals('/item-thinkphp2016', Url::build('blog/item?name=thinkphp&id=2016')); - } - - public function testBuildController() - { - Config::set('url_html_suffix', ''); - Route::get('blog/:id', '@index/blog/read'); - $this->assertEquals('/blog/10.html', Url::build('@index/blog/read', 'id=10', 'html')); - - Route::get('foo/bar', '@foo/bar/index'); - $this->assertEquals('/foo/bar', Url::build('@foo/bar/index')); - - Route::get('foo/bar/baz', '@foo/bar.BAZ/index'); - $this->assertEquals('/foo/bar/baz', Url::build('@foo/bar.BAZ/index')); - } - - public function testBuildMethod() - { - Route::get('blog/:id', '\app\index\controller\blog@read'); - $this->assertEquals('/blog/10.html', Url::build('[\app\index\controller\blog@read]', 'id=10', 'html')); - } - - public function testBuildRoute() - { - Route::get('blog/:id', 'index/blog'); - Config::set('url_html_suffix', 'shtml'); - $this->assertNotEquals('/blog/10.html', Url::build('/blog/10')); - $this->assertEquals('/blog/10.shtml', Url::build('/blog/10')); - } - - public function testBuildNameRoute() - { - Route::get(['name', 'blog/:id'], 'index/blog'); - $this->assertEquals([['blog/:id', ['id' => 1], null]], Route::name('name')); - Config::set('url_html_suffix', 'shtml'); - $this->assertEquals('/blog/10.shtml', Url::build('name?id=10')); - } - - public function testBuildAnchor() - { - Route::get('blog/:id', 'index/blog'); - Config::set('url_html_suffix', 'shtml'); - $this->assertEquals('/blog/10.shtml#detail', Url::build('/blog/10#detail')); - - Config::set('url_common_param', true); - $this->assertEquals('/blog/10.shtml?foo=bar#detail', Url::build('/blog/10#detail', "foo=bar")); - } - - public function testBuildDomain() - { - Config::set('url_domain_deploy', true); - Route::domain('subdomain.thinkphp.cn', 'admin'); - $this->assertEquals('http://subdomain.thinkphp.cn/blog/10.shtml', Url::build('/blog/10')); - Route::domain('subdomain.thinkphp.cn', [ - 'hello/:name' => 'index/hello', - ]); - $this->assertEquals('http://subdomain.thinkphp.cn/hello/thinkphp.shtml', Url::build('index/hello?name=thinkphp')); - } - - public function testRoot() - { - Config::set('url_domain_deploy', false); - Config::set('url_common_param', false); - Url::root('/index.php'); - Route::get('blog/:id', 'index/blog/read'); - Config::set('url_html_suffix', 'shtml'); - $this->assertEquals('/index.php/blog/10/name/thinkphp.shtml', Url::build('index/blog/read?id=10&name=thinkphp')); - - } -} diff --git a/tests/thinkphp/library/think/validateTest.php b/tests/thinkphp/library/think/validateTest.php deleted file mode 100644 index 4d7819b55332ad7c551eae991d05a50865e257d3..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/validateTest.php +++ /dev/null @@ -1,200 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * Validate类测试 - */ - -namespace tests\thinkphp\library\think; - -use think\File; -use think\Validate; - -class validateTest extends \PHPUnit_Framework_TestCase -{ - - public function testCheck() - { - $rule = [ - 'name' => 'require|max:25', - 'age' => 'number|between:1,120', - 'email' => 'email', - ]; - $msg = [ - 'name.require' => '名称必须', - 'name.max' => '名称最多不能超过25个字符', - 'age.number' => '年龄必须是数字', - 'age.between' => '年龄只能在1-120之间', - 'email' => '邮箱格式错误', - ]; - $data = [ - 'name' => 'thinkphp', - 'age' => 10, - 'email' => 'thinkphp@qq.com', - ]; - $validate = new Validate($rule, $msg); - $result = $validate->check($data); - $this->assertEquals(true, $result); - } - - public function testRule() - { - $rule = [ - 'name' => 'require|method:get|alphaNum|max:25|expire:2016-1-1,2026-1-1', - 'account' => 'requireIf:name,thinkphp|alphaDash|min:4|length:4,30', - 'age' => 'number|between:1,120', - 'email' => 'requireWith:name|email', - 'host' => 'activeUrl|activeUrl:A', - 'url' => 'url', - 'ip' => 'ip|ip:ipv4', - 'score' => 'float|gt:60|notBetween:90,100|notIn:70,80|lt:100|elt:100|egt:60', - 'status' => 'integer|in:0,1,2', - 'begin_time' => 'after:2016-3-18', - 'end_time' => 'before:2016-10-01', - 'info' => 'require|array|length:4|max:5|min:2', - 'info.name' => 'require|length:8|alpha|same:thinkphp', - 'value' => 'same:100|different:status', - 'bool' => 'boolean', - 'title' => 'chsAlpha', - 'city' => 'chs', - 'nickname' => 'chsDash', - 'aliasname' => 'chsAlphaNum', - 'file' => 'file|fileSize:20480', - 'image' => 'image|fileMime:image/png|image:80,80,png', - 'test' => 'test', - ]; - $data = [ - 'name' => 'thinkphp', - 'account' => 'liuchen', - 'age' => 10, - 'email' => 'thinkphp@qq.com', - 'host' => 'thinkphp.cn', - 'url' => 'http://thinkphp.cn/topic', - 'ip' => '114.34.54.5', - 'score' => '89.15', - 'status' => 1, - 'begin_time' => '2016-3-20', - 'end_time' => '2016-5-1', - 'info' => [1, 2, 3, 'name' => 'thinkphp'], - 'zip' => '200000', - 'date' => '16-3-8', - 'ok' => 'yes', - 'value' => 100, - 'bool' => 'true', - 'title' => '流年ThinkPHP', - 'city' => '上海', - 'nickname' => '流年ThinkPHP_2016', - 'aliasname' => '流年Think2016', - 'file' => new File(THINK_PATH . 'base.php'), - 'image' => new File(THINK_PATH . 'logo.png'), - 'test' => 'test', - ]; - $validate = new Validate($rule); - $validate->extend('test', function ($value) {return 'test' == $value ? true : false;}); - $validate->rule('zip', '/^\d{6}$/'); - $validate->rule([ - 'ok' => 'require|accepted', - 'date' => 'date|dateFormat:y-m-d', - ]); - $result = $validate->batch()->check($data); - $this->assertEquals(true, $result); - } - - public function testMsg() - { - $validate = new Validate(); - $validate->message('name.require', '名称必须'); - $validate->message([ - 'name.require' => '名称必须', - 'name.max' => '名称最多不能超过25个字符', - 'age.number' => '年龄必须是数字', - 'age.between' => '年龄只能在1-120之间', - 'email' => '邮箱格式错误', - ]); - } - - public function testMake() - { - $rule = [ - 'name' => 'require|max:25', - 'age' => 'number|between:1,120', - 'email' => 'email', - ]; - $msg = [ - 'name.require' => '名称必须', - 'name.max' => '名称最多不能超过25个字符', - 'age.number' => '年龄必须是数字', - 'age.between' => '年龄只能在1-120之间', - 'email' => '邮箱格式错误', - ]; - $validate = Validate::make($rule, $msg); - } - - public function testExtend() - { - $validate = new Validate(['name' => 'check:1']); - $validate->extend('check', function ($value, $rule) {return $rule == $value ? true : false;}); - $validate->extend(['check' => function ($value, $rule) {return $rule == $value ? true : false;}]); - $data = ['name' => 1]; - $result = $validate->check($data); - $this->assertEquals(true, $result); - } - - public function testScene() - { - $rule = [ - 'name' => 'require|max:25', - 'age' => 'number|between:1,120', - 'email' => 'email', - ]; - $msg = [ - 'name.require' => '名称必须', - 'name.max' => '名称最多不能超过25个字符', - 'age.number' => '年龄必须是数字', - 'age.between' => '年龄只能在1-120之间', - 'email' => '邮箱格式错误', - ]; - $data = [ - 'name' => 'thinkphp', - 'age' => 10, - 'email' => 'thinkphp@qq.com', - ]; - $validate = new Validate($rule); - $validate->scene(['edit' => ['name', 'age']]); - $validate->scene('edit', ['name', 'age']); - $validate->scene('edit'); - $result = $validate->check($data); - $this->assertEquals(true, $result); - } - - public function testSetTypeMsg() - { - $rule = [ - 'name|名称' => 'require|max:25', - 'age' => 'number|between:1,120', - 'email' => 'email', - ['sex', 'in:1,2', '性别错误'], - ]; - $data = [ - 'name' => '', - 'age' => 10, - 'email' => 'thinkphp@qq.com', - 'sex' => '3', - ]; - $validate = new Validate($rule); - $validate->setTypeMsg('require', ':attribute必须'); - $validate->setTypeMsg(['require' => ':attribute必须']); - $result = $validate->batch()->check($data); - $this->assertFalse($result); - $this->assertEquals(['name' => '名称必须', 'sex' => '性别错误'], $validate->getError()); - } - -} diff --git a/tests/thinkphp/library/think/view/driver/.gitignore b/tests/thinkphp/library/think/view/driver/.gitignore deleted file mode 100644 index a3a0c8b5f48c0260a4cb43aa577f9b18896ee280..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/view/driver/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/tests/thinkphp/library/think/view/theme/index/template.html b/tests/thinkphp/library/think/view/theme/index/template.html deleted file mode 100644 index 5f4548be097253b2bd5c61b42b7e2d18321ff1f8..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/view/theme/index/template.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - Document - - - - - diff --git a/tests/thinkphp/library/think/viewTest.php b/tests/thinkphp/library/think/viewTest.php deleted file mode 100644 index 56804798fd2653bab7a740595dad09354508a033..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/think/viewTest.php +++ /dev/null @@ -1,76 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * view测试 - * @author mahuan - */ - -namespace tests\thinkphp\library\think; - -class viewTest extends \PHPUnit_Framework_TestCase -{ - - /** - * 句柄测试 - * @return mixed - * @access public - */ - public function testGetInstance() - { - \think\Cookie::get('a'); - $view_instance = \think\View::instance(); - $this->assertInstanceOf('\think\view', $view_instance, 'instance方法返回错误'); - } - - /** - * 测试变量赋值 - * @return mixed - * @access public - */ - public function testAssign() - { - $view_instance = \think\View::instance(); - $view_instance->key = 'value'; - $this->assertTrue(isset($view_instance->key)); - $this->assertEquals('value', $view_instance->key); - $data = $view_instance->assign(array('key' => 'value')); - $data = $view_instance->assign('key2', 'value2'); - //测试私有属性 - $expect_data = array('key' => 'value', 'key2' => 'value2'); - $this->assertAttributeEquals($expect_data, 'data', $view_instance); - } - - /** - * 测试引擎设置 - * @return mixed - * @access public - */ - public function testEngine() - { - $view_instance = \think\View::instance(); - $data = $view_instance->engine('php'); - $data = $view_instance->engine(['type' => 'php', 'view_path' => '', 'view_suffix' => '.php', 'view_depr' => DS]); - $php_engine = new \think\view\driver\Php(['view_path' => '', 'view_suffix' => '.php', 'view_depr' => DS]); - $this->assertAttributeEquals($php_engine, 'engine', $view_instance); - //测试模板引擎驱动 - $data = $view_instance->engine(['type' => 'think', 'view_path' => '', 'view_suffix' => '.html', 'view_depr' => DS]); - $think_engine = new \think\view\driver\Think(['view_path' => '', 'view_suffix' => '.html', 'view_depr' => DS]); - $this->assertAttributeEquals($think_engine, 'engine', $view_instance); - } - - public function testReplace() - { - $view_instance = \think\View::instance(); - $view_instance->replace('string', 'replace')->display('string'); - } - -} diff --git a/tests/thinkphp/library/traits/controller/.gitignore b/tests/thinkphp/library/traits/controller/.gitignore deleted file mode 100644 index a3a0c8b5f48c0260a4cb43aa577f9b18896ee280..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/traits/controller/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/tests/thinkphp/library/traits/model/.gitignore b/tests/thinkphp/library/traits/model/.gitignore deleted file mode 100644 index a3a0c8b5f48c0260a4cb43aa577f9b18896ee280..0000000000000000000000000000000000000000 --- a/tests/thinkphp/library/traits/model/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/tpl/default_index.tpl b/tpl/default_index.tpl index 8538b4dfabbb2040d22aacc6051dfbb05ac49f64..e5c1363ac6d80f02698a7f77f63f13bc2cf7e693 100644 --- a/tpl/default_index.tpl +++ b/tpl/default_index.tpl @@ -5,6 +5,6 @@ class Index{$suffix} { public function index() { - return '

:)

ThinkPHP V5
十年磨一剑 - 为API开发设计的高性能框架

[ V5.0 版本由 七牛云 独家赞助发布 ]
'; + return '

:)

ThinkPHP V5.1
12载初心不改(2006-2018) - 你值得信赖的PHP框架

'; } } diff --git a/tpl/dispatch_jump.tpl b/tpl/dispatch_jump.tpl index 18ee01bd55638ce56d46f9956576493205696243..583376bbb694e26c82a5852645745f93a0f9fda7 100644 --- a/tpl/dispatch_jump.tpl +++ b/tpl/dispatch_jump.tpl @@ -2,6 +2,7 @@ + 跳转提示