From 62fa7bd73c55daa96400e86b678fd96945cc4eb8 Mon Sep 17 00:00:00 2001 From: molong Date: Wed, 11 May 2016 10:18:14 +0800 Subject: [PATCH 001/670] =?UTF-8?q?URL=E7=94=9F=E6=88=90=E7=9A=84=E4=B8=80?= =?UTF-8?q?=E4=B8=AAbug=EF=BC=8C=E5=90=AB=E5=8F=82=E6=95=B0=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Url.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Url.php b/library/think/Url.php index 509ef6c6..2987dc44 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -247,9 +247,9 @@ class Url if (empty($pattern) && empty($param)) { // 没有任何变量 return $url; - } elseif (!empty($match) || !empty($param) && array_intersect($param, $array) == $param) { + } elseif (!empty($match) || (!empty($param) && array_intersect_assoc($param, $array) == $param)) { // 存在变量定义 - $vars = array_diff($array, $param); + $vars = array_diff_key($array, $param); return $url; } } From 9843eaf243dabab3ca7ba745dafee5130edbeb2c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 11:53:07 +0800 Subject: [PATCH 002/670] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=9C=AA=E5=8C=B9?= =?UTF-8?q?=E9=85=8D=E8=B7=AF=E7=94=B1=E7=9A=84=E8=A7=84=E5=88=99=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/library/think/Route.php b/library/think/Route.php index 17505a98..d57d1c10 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -254,6 +254,12 @@ class Route } } + // 注册未匹配路由规则后的处理 + public static function miss($route, $method = '*', $option = []) + { + self::register('__miss__', $route, $method, $option, []); + } + // 获取路由定义 public static function getRules($method = '') { @@ -385,6 +391,11 @@ class Route // 路由规则检测 if (!empty($rules)) { + if (isset($rules['__miss__'])) { + // 指定未匹配路由的处理 + $miss = $rules['__miss__']; + unset($rules['__miss__']); + } foreach ($rules as $rule => $val) { $option = $val['option']; $pattern = $val['pattern']; @@ -436,6 +447,12 @@ class Route } } } + if (isset($miss)) { + // 未匹配所有路由的路由规则处理 + if (self::checkOption($miss['option'], $url)) { + return self::parseRule('', $miss['route'], $url, []); + } + } } return false; } From b50eeb5e7d290873ad68bdbe24d431a73c2441e5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 12:25:29 +0800 Subject: [PATCH 003/670] =?UTF-8?q?App=E7=B1=BB=E6=94=B9=E8=BF=9Brun?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E4=BC=A0=E5=85=A5Request=E5=AF=B9=E8=B1=A1?= =?UTF-8?q?=20=E4=BE=BF=E4=BA=8E=E6=9E=84=E9=80=A0=E8=87=AA=E5=B7=B1?= =?UTF-8?q?=E7=9A=84Request=E5=AF=B9=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 21 ++++++++++++--------- library/think/Route.php | 8 +++----- start.php | 2 +- tests/thinkphp/library/think/urlTest.php | 18 +++++++++--------- 4 files changed, 25 insertions(+), 24 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 2d0e0623..7f5f2c21 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -23,10 +23,12 @@ class App /** * 执行应用程序 * @access public + * @param \think\Request $request Request对象 * @return void */ - public static function run() + public static function run($request) { + // 初始化应用(公共模块) self::initModule(COMMON_MODULE, Config::get()); @@ -66,10 +68,10 @@ class App } // 获取当前请求的调度信息 - $dispatch = Request::instance()->dispatch(); + $dispatch = $request->dispatch(); if (empty($dispatch)) { // 未指定调度类型 则进行URL路由检测 - $dispatch = self::route($config); + $dispatch = self::route($request, $config); } // 记录路由信息 APP_DEBUG && Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info'); @@ -308,21 +310,22 @@ class App /** * URL路由检测(根据PATH_INFO) * @access public + * @param \think\Request $request * @param array $config * @throws Exception */ - public static function route(array $config) + public static function route($request, array $config) { - define('__INFO__', Request::instance()->pathinfo()); - define('__EXT__', Request::instance()->ext()); + define('__INFO__', $request->pathinfo()); + define('__EXT__', $request->ext()); // 检测URL禁用后缀 if ($config['url_deny_suffix'] && preg_match('/\.(' . $config['url_deny_suffix'] . ')$/i', __INFO__)) { throw new Exception('url suffix deny'); } - $_SERVER['PATH_INFO'] = Request::instance()->path(); + $_SERVER['PATH_INFO'] = $request->path(); $depr = $config['pathinfo_depr']; $result = false; // 路由检测 @@ -333,7 +336,7 @@ class App Route::register($config['route']); } // 路由检测(根据路由定义返回不同的URL调度) - $result = Route::check($_SERVER['PATH_INFO'], $depr, !IS_CLI ? $config['url_domain_deploy'] : false); + $result = Route::check($request, $_SERVER['PATH_INFO'], $depr, !IS_CLI ? $config['url_domain_deploy'] : false); if (APP_ROUTE_MUST && false === $result && $config['url_route_must']) { // 路由无效 throw new Exception('route not define '); @@ -346,7 +349,7 @@ class App //保证$_REQUEST正常取值 $_REQUEST = array_merge($_POST, $_GET, $_COOKIE); // 注册调度机制 - return Request::instance()->dispatch($result); + return $request->dispatch($result); } } diff --git a/library/think/Route.php b/library/think/Route.php index d57d1c10..7e60af01 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -11,8 +11,6 @@ namespace think; -use think\Request; - class Route { // 路由规则 @@ -358,7 +356,7 @@ class Route } // 检测URL路由 - public static function check($url, $depr = '/', $checkDomain = false) + public static function check($request, $url, $depr = '/', $checkDomain = false) { // 检测域名部署 if ($checkDomain) { @@ -429,7 +427,7 @@ class Route } $result = self::checkRule($key, $route, $url1, $pattern, $option); if (false !== $result) { - Request::instance()->route(['rule' => $key, 'route' => $route, 'pattern' => $pattern, 'option' => $option]); + $request->route(['rule' => $key, 'route' => $route, 'pattern' => $pattern, 'option' => $option]); return $result; } } @@ -442,7 +440,7 @@ class Route // 规则路由 $result = self::checkRule($rule, $route, $url, $pattern, $option); if (false !== $result) { - Request::instance()->route(['rule' => $rule, 'route' => $route, 'pattern' => $pattern, 'option' => $option]); + $request->route(['rule' => $rule, 'route' => $route, 'pattern' => $pattern, 'option' => $option]); return $result; } } diff --git a/start.php b/start.php index 5ad6f069..17f42442 100644 --- a/start.php +++ b/start.php @@ -64,5 +64,5 @@ if (APP_HOOK && isset($mode['tags'])) { // 是否自动运行 if (APP_AUTO_RUN) { - App::run(); + App::run(new Request()); } diff --git a/tests/thinkphp/library/think/urlTest.php b/tests/thinkphp/library/think/urlTest.php index 151cd4d6..a82c0936 100644 --- a/tests/thinkphp/library/think/urlTest.php +++ b/tests/thinkphp/library/think/urlTest.php @@ -26,17 +26,17 @@ class urlTest extends \PHPUnit_Framework_TestCase public function testBuildModule() { - Route::get('hello/:name', 'index/hello'); - Route::get('hello/:id', 'index/hello'); + Route::get('blog/:name', 'index/blog'); + Route::get('blog/:id', 'index/blog'); Config::set('pathinfo_depr', '/'); - $this->assertEquals('/hello/thinkphp', Url::build('index/hello?name=thinkphp')); - $this->assertEquals('/hello/thinkphp.html', Url::build('index/hello', 'name=thinkphp', 'html')); - $this->assertEquals('/hello/10', Url::build('index/hello?id=10')); - $this->assertEquals('/hello/10.html', Url::build('index/hello', 'id=10', 'html')); + $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-', 'good/item', [], ['item' => '\w+', 'id' => '\d+']); - $this->assertEquals('/item-thinkphp', Url::build('good/item?item=thinkphp')); - $this->assertEquals('/item-thinkphp2016', Url::build('good/item?item=thinkphp&id=2016')); + 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() From 3cb9c65c7a054708ad42b41d7cb170710baa56bc Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 12:32:52 +0800 Subject: [PATCH 004/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3request=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E5=92=8Cstart=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 10 ++++------ start.php | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/helper.php b/helper.php index 7db8de1d..726e3ae0 100644 --- a/helper.php +++ b/helper.php @@ -362,14 +362,12 @@ function route($rule = '', $route = [], $type = '*', $option = [], $pattern = [] } /** - * 获取Request参数 - * @param string $name 方法 - * @param mixed $param 参数 - * @return mixed + * 获取当前Request对象实例 + * @return \think\Request */ -function request($name, $param = '') +function request() { - return Request::instance()->$name($param); + return Request::instance(); } /** diff --git a/start.php b/start.php index 17f42442..9ad4264e 100644 --- a/start.php +++ b/start.php @@ -64,5 +64,5 @@ if (APP_HOOK && isset($mode['tags'])) { // 是否自动运行 if (APP_AUTO_RUN) { - App::run(new Request()); + App::run(Request::instance()); } From 79c381353d8feafef056262f454c4b4b76641ba1 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 12:34:04 +0800 Subject: [PATCH 005/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 1 - library/think/Request.php | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 7f5f2c21..b8f7556e 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -28,7 +28,6 @@ class App */ public static function run($request) { - // 初始化应用(公共模块) self::initModule(COMMON_MODULE, Config::get()); diff --git a/library/think/Request.php b/library/think/Request.php index f502869a..f88f4e51 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -101,7 +101,7 @@ class Request * 初始化 * @access public * @param array $options 参数 - * @return object + * @return \think\Request */ public static function instance($options = []) { From 03b87a9eb06d8440fa379283c690b990bd0d0329 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 12:45:06 +0800 Subject: [PATCH 006/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BApp=E7=B1=BB=20?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 12 +++-- library/think/Request.php | 2 +- tests/thinkphp/library/think/appTest.php | 3 +- tests/thinkphp/library/think/routeTest.php | 54 +++++++++++----------- 4 files changed, 38 insertions(+), 33 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index b8f7556e..407980d9 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -105,10 +105,14 @@ class App } // 输出数据到客户端 if (isset($data)) { - // 监听app_end - APP_HOOK && Hook::listen('app_end', $data); - // 自动响应输出 - return Response::send($data, '', Config::get('response_return')); + if ($data instanceof Response) { + return $data->send(); + } else { + // 监听app_end + APP_HOOK && Hook::listen('app_end', $data); + // 自动响应输出 + return Response::send($data, '', Config::get('response_return')); + } } } diff --git a/library/think/Request.php b/library/think/Request.php index f88f4e51..5a4f9da0 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -120,7 +120,7 @@ class Request * @param array $cookie * @param array $files * @param array $server - * @return object + * @return \think\Request */ public static function create($uri, $method = 'GET', $params = [], $cookie = [], $files = [], $server = []) { diff --git a/tests/thinkphp/library/think/appTest.php b/tests/thinkphp/library/think/appTest.php index ddf47076..97640ab9 100644 --- a/tests/thinkphp/library/think/appTest.php +++ b/tests/thinkphp/library/think/appTest.php @@ -19,6 +19,7 @@ namespace tests\thinkphp\library\think; use ReflectionClass; use think\App; use think\Config; +use think\Request; function func_trim($value) { @@ -49,7 +50,7 @@ class appTest extends \PHPUnit_Framework_TestCase { Config::set('root_namespace', ['/path/']); - App::run(); + App::run(Request::instance()); $expectOutputString = '

:)

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

[ V5.0 版本由 七牛云 独家赞助发布 ]
'; $this->expectOutputString($expectOutputString); diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index def9b611..aa480910 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -30,7 +30,7 @@ class routeTest extends \PHPUnit_Framework_TestCase Route::put('hello/:name', 'index/put'); Route::delete('hello/:name', 'index/delete'); Route::any('user/:id', 'index/user'); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check('hello/thinkphp')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello/thinkphp')); $this->assertEquals(['hello/:name' => ['route' => 'index/hello', 'option' => [], 'pattern' => []]], Route::getRules('GET')); Route::register('type/:name', 'index/type', 'PUT|POST'); } @@ -40,14 +40,14 @@ class routeTest extends \PHPUnit_Framework_TestCase Route::resource('res', 'index/blog'); Route::resource(['res' => ['index/blog']]); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'index']], Route::check('res')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'create']], Route::check('res/create')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::check('res/8')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'edit']], Route::check('res/8/edit')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'index']], Route::check(Request::instance(), 'res')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'create']], Route::check(Request::instance(), 'res/create')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::check(Request::instance(), 'res/8')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'edit']], Route::check(Request::instance(), 'res/8/edit')); Route::resource('blog.comment', 'index/comment'); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'comment', 'read']], Route::check('blog/8/comment/10')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'comment', 'edit']], Route::check('blog/8/comment/10/edit')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'comment', 'read']], Route::check(Request::instance(), 'blog/8/comment/10')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'comment', 'edit']], Route::check(Request::instance(), 'blog/8/comment/10/edit')); } public function testRest() @@ -57,8 +57,8 @@ class routeTest extends \PHPUnit_Framework_TestCase Route::rest(['read' => ['GET', '/:id', 'look'], 'create' => ['GET', '/create', 'add']]); Route::resource('res', 'index/blog'); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'add']], Route::check('res/create')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'look']], Route::check('res/8')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'add']], Route::check(Request::instance(), 'res/create')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'look']], Route::check(Request::instance(), 'res/8')); } @@ -66,17 +66,17 @@ class routeTest extends \PHPUnit_Framework_TestCase { Route::map('hello', 'index/hello'); $this->assertEquals('index/hello', Route::map('hello')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'hello', null]], Route::check('hello')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'hello', null]], Route::check(Request::instance(), 'hello')); } public function testMixVar() { Route::get('hello-', 'index/hello', [], ['name' => '\w+']); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check('hello-thinkphp')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello-thinkphp')); Route::get('hello-', 'index/hello', [], ['name' => '\w+', 'id' => '\d+']); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check('hello-thinkphp2016')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello-thinkphp2016')); Route::get('hello-/[:id]', 'index/hello', [], ['name' => '\w+', 'id' => '\d+']); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check('hello-thinkphp/2016')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello-thinkphp/2016')); } public function testParseUrl() @@ -96,8 +96,8 @@ class routeTest extends \PHPUnit_Framework_TestCase $this->assertEquals(false, Route::check('test/thinkphp')); $this->assertEquals(false, Route::check('blog/thinkphp')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check('blog/5')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check('hello/thinkphp/abc/test')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check(Request::instance(), 'blog/5')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello/thinkphp/abc/test')); } public function testCheckRouteGroup() @@ -105,9 +105,9 @@ class routeTest extends \PHPUnit_Framework_TestCase Route::pattern(['id' => '\d+', 'name' => '\w{6,25}']); Route::group('group', [':id' => 'index/hello', ':name' => 'index/say']); $this->assertEquals(false, Route::check('empty/think')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check('group/think')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check('group/10')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check('group/thinkphp')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check(Request::instance(), 'group/think')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'group/10')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check(Request::instance(), 'group/thinkphp')); } public function testRouteToModule() @@ -116,28 +116,28 @@ class routeTest extends \PHPUnit_Framework_TestCase Route::get('blog/:id', 'blog/read', [], ['id' => '\d+']); $this->assertEquals(false, Route::check('test/thinkphp')); $this->assertEquals(false, Route::check('blog/thinkphp')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check('hello/thinkphp')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check('blog/5')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello/thinkphp')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check(Request::instance(), 'blog/5')); } public function testRouteToController() { Route::get('say/:name', '@app\index\controller\index\hello'); - $this->assertEquals(['type' => 'controller', 'controller' => 'app\index\controller\index\hello', 'params' => ['name' => 'thinkphp']], Route::check('say/thinkphp')); + $this->assertEquals(['type' => 'controller', 'controller' => 'app\index\controller\index\hello', 'params' => ['name' => 'thinkphp']], Route::check(Request::instance(), 'say/thinkphp')); } public function testRouteToMethod() { 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', 'params' => ['name' => 'thinkphp']], Route::check('user/thinkphp')); - $this->assertEquals(['type' => 'method', 'method' => ['\app\index\model\Info', 'getInfo'], 'params' => ['name' => 'thinkphp']], Route::check('info/thinkphp')); + $this->assertEquals(['type' => 'method', 'method' => '\app\index\service\User::get', 'params' => ['name' => 'thinkphp']], Route::check(Request::instance(), 'user/thinkphp')); + $this->assertEquals(['type' => 'method', 'method' => ['\app\index\model\Info', 'getInfo'], 'params' => ['name' => 'thinkphp']], Route::check(Request::instance(), 'info/thinkphp')); } public function testRouteToRedirect() { Route::get('art/:id', '/article/read/id/:id', [], ['id' => '\d+']); - $this->assertEquals(['type' => 'redirect', 'url' => '/article/read/id/8', 'status' => 301], Route::check('art/8')); + $this->assertEquals(['type' => 'redirect', 'url' => '/article/read/id/8', 'status' => 301], Route::check(Request::instance(), 'art/8')); } public function testBind() @@ -146,13 +146,13 @@ class routeTest extends \PHPUnit_Framework_TestCase $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::parseUrl('read/10')); Route::get('index/blog/:id', 'index/blog/read'); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::check('10')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::check(Request::instance(), '10')); Route::bind('namespace', '\app\index\controller'); - $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check('blog/read')); + $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check(Request::instance(), 'blog/read')); Route::bind('class', '\app\index\controller\blog'); - $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check('read')); + $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check(Request::instance(), 'read')); } public function testSsl() From f83632cb7fcd2f8672276a40032c048ab660ee8d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 12:49:10 +0800 Subject: [PATCH 007/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/thinkphp/library/think/routeTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index aa480910..cfba2634 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -16,6 +16,7 @@ namespace tests\thinkphp\library\think; +use think\Request; use think\Route; class routeTest extends \PHPUnit_Framework_TestCase From fce80eb623202ea9f414860db7cc95d1ed115564 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 12:55:56 +0800 Subject: [PATCH 008/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/thinkphp/library/think/routeTest.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index cfba2634..eb27b456 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -95,8 +95,8 @@ class routeTest extends \PHPUnit_Framework_TestCase Route::get('hello/:name', 'index/hello'); Route::get('blog/:id', 'blog/read', [], ['id' => '\d+']); - $this->assertEquals(false, Route::check('test/thinkphp')); - $this->assertEquals(false, Route::check('blog/thinkphp')); + $this->assertEquals(false, Route::check(Request::instance(), 'test/thinkphp')); + $this->assertEquals(false, Route::check(Request::instance(), 'blog/thinkphp')); $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check(Request::instance(), 'blog/5')); $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello/thinkphp/abc/test')); } @@ -105,7 +105,7 @@ class routeTest extends \PHPUnit_Framework_TestCase { Route::pattern(['id' => '\d+', 'name' => '\w{6,25}']); Route::group('group', [':id' => 'index/hello', ':name' => 'index/say']); - $this->assertEquals(false, Route::check('empty/think')); + $this->assertEquals(false, Route::check(Request::instance(), 'empty/think')); $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check(Request::instance(), 'group/think')); $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'group/10')); $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check(Request::instance(), 'group/thinkphp')); @@ -115,8 +115,8 @@ class routeTest extends \PHPUnit_Framework_TestCase { Route::get('hello/:name', 'index/hello'); Route::get('blog/:id', 'blog/read', [], ['id' => '\d+']); - $this->assertEquals(false, Route::check('test/thinkphp')); - $this->assertEquals(false, Route::check('blog/thinkphp')); + $this->assertEquals(false, Route::check(Request::instance(), 'test/thinkphp')); + $this->assertEquals(false, Route::check(Request::instance(), 'blog/thinkphp')); $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello/thinkphp')); $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check(Request::instance(), 'blog/5')); } From 7f385217b978274be667e98e876ef67ebd89a195 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 14:04:56 +0800 Subject: [PATCH 009/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Bresponse=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 10 +- library/think/App.php | 2 +- library/think/Error.php | 2 +- library/think/Response.php | 149 ++++++++---------- library/think/controller/Rest.php | 6 +- library/traits/controller/Jump.php | 8 +- tests/thinkphp/library/think/responseTest.php | 36 +++-- 7 files changed, 94 insertions(+), 119 deletions(-) diff --git a/helper.php b/helper.php index 726e3ae0..4806a0e5 100644 --- a/helper.php +++ b/helper.php @@ -371,12 +371,10 @@ function request() } /** - * 设置Response输出 - * @param string $name 方法 - * @param mixed $param 参数 - * @return mixed + * 获取当前的Response对象实例 + * @return \think\Response */ -function response($name, $param = '') +function response() { - return Response::$name($param); + return Response::instance(); } diff --git a/library/think/App.php b/library/think/App.php index 407980d9..1d747be6 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -111,7 +111,7 @@ class App // 监听app_end APP_HOOK && Hook::listen('app_end', $data); // 自动响应输出 - return Response::send($data, '', Config::get('response_return')); + return Response::instance()->send($data, '', Config::get('response_return')); } } } diff --git a/library/think/Error.php b/library/think/Error.php index eea83677..9b760e13 100644 --- a/library/think/Error.php +++ b/library/think/Error.php @@ -154,7 +154,7 @@ class Error // 异常信息输出监听 APP_HOOK && Hook::listen('error_output', $data); // 输出异常内容 - Response::send($data, $type, Config::get('response_return')); + Response::instance()->send($data, $type, Config::get('response_return')); } else { //ob_end_clean(); extract($data); diff --git a/library/think/Response.php b/library/think/Response.php index 45eaf327..55e450ae 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -16,17 +16,18 @@ use think\Url; class Response { + protected static $instance; // 输出数据的转换方法 - protected static $transform = null; + protected $transform = null; // 输出数据 - protected static $data = ''; + protected $data = ''; // 是否exit - protected static $isExit = false; + protected $isExit = false; // 输出类型 - protected static $type = ''; + protected $type = ''; // contentType - protected static $contentType = [ + protected $contentType = [ 'json' => 'application/json', 'xml' => 'text/xml', 'html' => 'text/html', @@ -34,56 +35,30 @@ class Response 'script' => 'application/javascript', 'text' => 'text/plain', ]; - // HTTP status - protected static $code = [ - // Informational 1xx - 100 => 'Continue', - 101 => 'Switching Protocols', - // Success 2xx - 200 => 'OK', - 201 => 'Created', - 202 => 'Accepted', - 203 => 'Non-Authoritative Information', - 204 => 'No Content', - 205 => 'Reset Content', - 206 => 'Partial Content', - // Redirection 3xx - 300 => 'Multiple Choices', - 301 => 'Moved Permanently', - 302 => 'Moved Temporarily ', // 1.1 - 303 => 'See Other', - 304 => 'Not Modified', - 305 => 'Use Proxy', - // 306 is deprecated but reserved - 307 => 'Temporary Redirect', - // Client Error 4xx - 400 => 'Bad Request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition Failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed', - // Server Error 5xx - 500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version Not Supported', - 509 => 'Bandwidth Limit Exceeded', - ]; + + /** + * 架构函数 + * @access public + * @param array $options 参数 + */ + public function __construct($type = '') + { + $this->type = $type; + } + + /** + * 初始化 + * @access public + * @param string $type 输出类型 + * @return \think\Request + */ + public static function instance($type = '') + { + if (is_null(self::$instance)) { + self::$instance = new static($type); + } + return self::$instance; + } /** * 发送数据到客户端 @@ -93,20 +68,20 @@ class Response * @param bool $return 是否返回数据 * @return mixed */ - public static function send($data = [], $type = '', $return = false) + public function send($data = [], $type = '', $return = false) { if ('' == $type) { - $type = self::$type ?: (IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type')); + $type = $this->type ?: (IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type')); } $type = strtolower($type); - $data = $data ?: self::$data; + $data = $data ?: $this->data; - if (!headers_sent() && isset(self::$contentType[$type])) { - header('Content-Type:' . self::$contentType[$type] . '; charset=utf-8'); + if (!headers_sent() && isset($this->contentType[$type])) { + header('Content-Type:' . $this->contentType[$type] . '; charset=utf-8'); } - if (is_callable(self::$transform)) { - $data = call_user_func_array(self::$transform, [$data]); + if (is_callable($this->transform)) { + $data = call_user_func_array($this->transform, [$data]); } else { switch ($type) { case 'json': @@ -128,7 +103,7 @@ class Response } echo $data; - self::isExit() && exit(); + $this->isExit() && exit(); } /** @@ -137,9 +112,10 @@ class Response * @param mixed $callback 调用的转换方法 * @return $this */ - public static function transform($callback) + public function transform($callback) { - self::$transform = $callback; + $this->transform = $callback; + return $this; } /** @@ -148,34 +124,37 @@ class Response * @param mixed $data 输出数据 * @return $this */ - public static function data($data) + public function data($data) { - self::$data = $data; + $this->data = $data; + return $this; } /** * 输出类型设置 * @access public * @param string $type 输出内容的格式类型 - * @return mixed + * @return $this */ - public static function type($type) + public function type($type) { - self::$type = $type; + $this->type = $type; + return $this; } /** * 输出是否exit设置 * @access public * @param bool $exit 是否退出 - * @return mixed + * @return $this */ - public static function isExit($exit = null) + public function isExit($exit = null) { if (is_null($exit)) { - return self::$isExit; + return $this->isExit; } - self::$isExit = (boolean) $exit; + $this->isExit = (boolean) $exit; + return $this; } /** @@ -186,7 +165,7 @@ class Response * @param string $msg 提示信息 * @return mixed */ - public static function result($data, $code = 0, $msg = '', $type = '') + public function result($data, $code = 0, $msg = '', $type = '') { $result = [ 'code' => $code, @@ -194,7 +173,7 @@ class Response 'time' => NOW_TIME, 'data' => $data, ]; - self::$type = $type; + $this->type = $type; return $result; } @@ -205,7 +184,7 @@ class Response * @param array|int $params 其它URL参数或http code * @return void */ - public static function redirect($url, $params = []) + public function redirect($url, $params = []) { $http_response_code = 301; if (is_int($params) && in_array($params, [301, 302])) { @@ -221,24 +200,22 @@ class Response * @access public * @param string $name 参数名 * @param string $value 参数值 - * @return void + * @return $this */ - public static function header($name, $value) + public function header($name, $value) { header($name . ':' . $value); + return $this; } /** * 发送HTTP状态 * @param integer $code 状态码 - * @return void + * @return $this */ - public static function code($code) + public function code($code) { - if (isset(self::$statusCode[$code])) { - header('HTTP/1.1 ' . $code . ' ' . self::$statusCode[$code]); - // 确保FastCGI模式下正常 - header('Status:' . $code . ' ' . self::$statusCode[$code]); - } + http_response_code($code); + return $this; } } diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index 33372e1b..1608ff94 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -92,11 +92,7 @@ abstract class Rest */ protected function response($data, $type = '', $code = 200) { - http_response_code($code); - Response::data($data); - if ($type) { - Response::type($type); - } + return Response::instance()->data($data)->type($type)->code($code); } /** diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index c6a3a243..cf54966e 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -50,7 +50,7 @@ trait Jump $result = View::instance(Config::get('template'), Config::get('view_replace_str')) ->fetch(Config::get('dispatch_success_tmpl'), $result); } - Response::send($result, $type); + Response::instance()->send($result, $type); } /** @@ -83,7 +83,7 @@ trait Jump $result = View::instance(Config::get('template'), Config::get('view_replace_str')) ->fetch(Config::get('dispatch_error_tmpl'), $result); } - Response::send($result, $type); + Response::instance()->send($result, $type); } /** @@ -97,7 +97,7 @@ trait Jump */ public function result($data, $code = 0, $msg = '', $type = '') { - return Response::result($data, $code, $msg, $type); + return Response::instance()->result($data, $code, $msg, $type); } /** @@ -109,7 +109,7 @@ trait Jump */ public function redirect($url, $params = []) { - Response::redirect($url, $params); + Response::instance()->redirect($url, $params); } } diff --git a/tests/thinkphp/library/think/responseTest.php b/tests/thinkphp/library/think/responseTest.php index f2b5d6a6..2bba1845 100644 --- a/tests/thinkphp/library/think/responseTest.php +++ b/tests/thinkphp/library/think/responseTest.php @@ -70,7 +70,7 @@ class responseTest extends \PHPUnit_Framework_TestCase { Config::set('default_ajax_return', $this->default_ajax_return); Config::set('default_return_type', $this->default_return_type); - Response::type(Config::get('default_return_type')); // 会影响其他测试 + Response::instance()->type(Config::get('default_return_type')); // 会影响其他测试 } /** @@ -83,23 +83,24 @@ class responseTest extends \PHPUnit_Framework_TestCase $dataArr["key"] = "value"; //$dataArr->key = "val"; - $result = Response::send($dataArr, "", true); + $response = Response::instance(); + $result = $response->send($dataArr, "", true); $this->assertArrayHasKey("key", $result); - $result = Response::send($dataArr, "json", true); + $result = $response->send($dataArr, "json", true); $this->assertEquals('{"key":"value"}', $result); $handler = "callback"; $_GET[Config::get('var_jsonp_handler')] = $handler; - $result = Response::send($dataArr, "jsonp", true); + $result = $response->send($dataArr, "jsonp", true); $this->assertEquals('callback({"key":"value"});', $result); - Response::transform(function () { + $response->transform(function () { return "callbackreturndata"; }); - $result = Response::send($dataArr, "", true); + $result = $response->send($dataArr, "", true); $this->assertEquals("callbackreturndata", $result); $_GET[Config::get('var_jsonp_handler')] = ""; } @@ -110,15 +111,16 @@ class responseTest extends \PHPUnit_Framework_TestCase */ public function testtransform() { - Response::transform(function () { + $response = Response::instance(); + $response->transform(function () { return "callbackreturndata"; }); $dataArr = []; - $result = Response::send($dataArr, "", true); + $result = $response->send($dataArr, "", true); $this->assertEquals("callbackreturndata", $result); - Response::transform(null); + $response->transform(null); } /** @@ -128,7 +130,7 @@ class responseTest extends \PHPUnit_Framework_TestCase public function testType() { $type = "json"; - Response::type($type); + Response::instance()->type($type); } /** @@ -138,8 +140,9 @@ class responseTest extends \PHPUnit_Framework_TestCase public function testData() { $data = "data"; - Response::data($data); - Response::data(null); + $response = Response::instance(); + $response->data($data); + $response->data(null); } /** @@ -149,11 +152,12 @@ class responseTest extends \PHPUnit_Framework_TestCase public function testIsExit() { $isExit = true; - Response::isExit($isExit); + $response = Response::instance(); + $response->isExit($isExit); - $result = Response::isExit(); + $result = $response->isExit(); $this->assertTrue($isExit, $result); - Response::isExit(false); + $response->isExit(false); } /** @@ -166,7 +170,7 @@ class responseTest extends \PHPUnit_Framework_TestCase $code = "1001"; $msg = "the msg"; $type = "json"; - $result = Response::result($data, $code, $msg, $type); + $result = Response::instance()->result($data, $code, $msg, $type); $this->assertEquals($code, $result["code"]); $this->assertEquals($msg, $result["msg"]); From 15e01901fb1122f340e0902ba43dbcbc1c702205 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 18:14:16 +0800 Subject: [PATCH 010/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Query=E7=B1=BB?= =?UTF-8?q?=E4=B8=80=E5=A4=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 71646d7b..9df03d49 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1352,7 +1352,7 @@ class Query } if (!empty($options['with'])) { // 预载入 - $resultSet = $result->eagerlyResultSet($resultSet, $options['with'], is_class($resultSet) ? get_class($resultSet) : ''); + $resultSet = $result->eagerlyResultSet($resultSet, $options['with'], is_object($resultSet) ? get_class($resultSet) : ''); } } } elseif (!empty($options['fail'])) { From cbd8ea477ded87491a15e3003cd0b6a940bf56fa Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 22:03:26 +0800 Subject: [PATCH 011/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Relation=E7=B1=BB=20?= =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB=E7=9A=84group=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 112 +++++++++++++++++---- library/think/model/Relation.php | 6 +- tests/thinkphp/library/think/routeTest.php | 79 ++++++++------- 3 files changed, 143 insertions(+), 54 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 7e60af01..a0a6d511 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -53,6 +53,9 @@ class Route private static $pattern = []; // 域名绑定 private static $bind = []; + // 当前分组 + private static $group; + private static $option = []; // 添加URL映射规则 public static function map($map = '', $route = '') @@ -150,43 +153,118 @@ class Route } self::$rules[$type][$rule] = $result; } + } } - // 路由分组 - public static function group($name, $routes = [], $type = '*', $option = [], $pattern = []) + // 注册路由规则 + public static function rule($rule, $route = '', $type = '*', $option = [], $pattern = [], $group = '') { - self::$rules[$type][$name] = ['routes' => $routes, 'option' => $option, 'pattern' => $pattern]; + $group = $group ?: self::$group; + $option = $option ?: self::$option; + + if (strpos($type, '|')) { + foreach (explode('|', $type) as $val) { + self::rule($rule, $route, $val, $option, $pattern, $group); + } + } else { + $rules = []; + if (is_array($rule)) { + foreach ($rule as $key => $val) { + if (is_numeric($key)) { + $key = array_shift($val); + } + if (is_array($val)) { + $result = ['route' => $val[0], 'option' => $val[1], 'pattern' => isset($val[2]) ? $val[2] : []]; + } else { + $result = ['route' => $val, 'option' => $option, 'pattern' => $pattern]; + } + if ($group) { + self::$rules[$type][$group]['routes'][$key] = $result['route']; + } else { + self::$rules[$type][$key] = $result; + } + } + } else { + if ($group) { + self::$rules[$type][$group]['routes'][$rule] = $route; + } else { + self::$rules[$type][$rule] = ['route' => $route, 'option' => $option, 'pattern' => $pattern]; + } + } + } + } + + // 设置当前的路由分组 + public static function setGroup($name) + { + self::$group = $name; + } + + // 设置当前的路由分组 + public static function setOption($option) + { + self::$option = $option; + } + + // 路由分组 + public static function group($name, $routes, $option = [], $type = '*', $pattern = []) + { + if (is_array($name)) { + $option = $name; + $name = isset($option['name']) ? $option['name'] : ''; + } + if (!empty($name)) { + if ($routes instanceof \Closure) { + self::setGroup($name); + call_user_func_array($routes, []); + self::setGroup(null); + self::$rules[$type][$name]['option'] = $option; + self::$rules[$type][$name]['pattern'] = $pattern; + } else { + self::$rules[$type][$name] = ['routes' => $routes, 'option' => $option, 'pattern' => $pattern]; + } + } else { + if ($routes instanceof \Closure) { + // 闭包注册 + self::setOption($option); + call_user_func_array($routes, []); + self::setOption([]); + } else { + // 批量注册路由 + self::rule($routes, '', $type, $option, $pattern); + } + } } // 注册任意请求的路由规则 - public static function any($rule, $route = '', $option = [], $pattern = []) + public static function any($rule, $route = '', $option = [], $pattern = [], $group = '') { - self::register($rule, $route, '*', $option, $pattern); + self::rule($rule, $route, '*', $option, $pattern, $group); } // 注册get请求的路由规则 - public static function get($rule, $route = '', $option = [], $pattern = []) + public static function get($rule, $route = '', $option = [], $pattern = [], $group = '') { - self::register($rule, $route, 'GET', $option, $pattern); + self::rule($rule, $route, 'GET', $option, $pattern, $group); } // 注册post请求的路由规则 - public static function post($rule, $route = '', $option = [], $pattern = []) + public static function post($rule, $route = '', $option = [], $pattern = [], $group = '') { - self::register($rule, $route, 'POST', $option, $pattern); + self::rule($rule, $route, 'POST', $option, $pattern, $group); } // 注册put请求的路由规则 - public static function put($rule, $route = '', $option = [], $pattern = []) + public static function put($rule, $route = '', $option = [], $pattern = [], $group = '') { - self::register($rule, $route, 'PUT', $option, $pattern); + self::rule($rule, $route, 'PUT', $option, $pattern, $group); } // 注册delete请求的路由规则 - public static function delete($rule, $route = '', $option = [], $pattern = []) + public static function delete($rule, $route = '', $option = [], $pattern = [], $group = '') { - self::register($rule, $route, 'DELETE', $option, $pattern); + self::rule($rule, $route, 'DELETE', $option, $pattern, $group); } // 注册资源路由 @@ -219,7 +297,7 @@ class Route if (strpos($val[1], ':id') && isset($option['var'][$rule])) { $val[1] = str_replace(':id', ':' . $option['var'][$rule], $val[1]); } - self::register($rule . $val[1] . '$', $route . '/' . $val[2], $val[0], $option, $pattern); + self::rule($rule . $val[1] . '$', $route . '/' . $val[2], $val[0], $option, $pattern); } } } @@ -255,7 +333,7 @@ class Route // 注册未匹配路由规则后的处理 public static function miss($route, $method = '*', $option = []) { - self::register('__miss__', $route, $method, $option, []); + self::rule('__miss__', $route, $method, $option, []); } // 获取路由定义 @@ -395,8 +473,8 @@ class Route unset($rules['__miss__']); } foreach ($rules as $rule => $val) { - $option = $val['option']; - $pattern = $val['pattern']; + $option = isset($val['option']) ? $val['option'] : []; + $pattern = isset($val['pattern']) ? $val['pattern'] : []; // 参数有效性检查 if (!self::checkOption($option, $url)) { diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index 654a7b9b..ab605761 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -85,9 +85,9 @@ class Relation break; case self::BELONGS_TO_MANY: // 关联查询 - $pk = $this->parent->getPk(); - $condition['pivot.' . $foreignKey] = $this->parent->$pk; - $result = $this->belongsToManyQuery($relation, $this->middle, $foreignKey, $localKey, $condition)->select(); + $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->toArray() as $key => $val) { diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index eb27b456..bbe31686 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -24,60 +24,65 @@ class routeTest extends \PHPUnit_Framework_TestCase 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::any('user/:id', 'index/user'); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello/thinkphp')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check($request, 'hello/thinkphp')); $this->assertEquals(['hello/:name' => ['route' => 'index/hello', 'option' => [], 'pattern' => []]], Route::getRules('GET')); Route::register('type/:name', 'index/type', 'PUT|POST'); + Route::rule('type/:name', 'index/type', 'PUT|POST'); } public function testResource() { + $request = Request::instance(); Route::resource('res', 'index/blog'); Route::resource(['res' => ['index/blog']]); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'index']], Route::check(Request::instance(), 'res')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'create']], Route::check(Request::instance(), 'res/create')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::check(Request::instance(), 'res/8')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'edit']], Route::check(Request::instance(), 'res/8/edit')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'index']], Route::check($request, 'res')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'create']], Route::check($request, 'res/create')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::check($request, 'res/8')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'edit']], Route::check($request, 'res/8/edit')); Route::resource('blog.comment', 'index/comment'); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'comment', 'read']], Route::check(Request::instance(), 'blog/8/comment/10')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'comment', 'edit']], Route::check(Request::instance(), 'blog/8/comment/10/edit')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'comment', 'read']], Route::check($request, 'blog/8/comment/10')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'comment', 'edit']], Route::check($request, 'blog/8/comment/10/edit')); } 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'); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'add']], Route::check(Request::instance(), 'res/create')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'look']], Route::check(Request::instance(), 'res/8')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'add']], Route::check($request, 'res/create')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'look']], Route::check($request, 'res/8')); } public function testRouteMap() { + $request = Request::instance(); Route::map('hello', 'index/hello'); $this->assertEquals('index/hello', Route::map('hello')); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'hello', null]], Route::check(Request::instance(), 'hello')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'hello', null]], Route::check($request, 'hello')); } public function testMixVar() { + $request = Request::instance(); Route::get('hello-', 'index/hello', [], ['name' => '\w+']); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello-thinkphp')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check($request, 'hello-thinkphp')); Route::get('hello-', 'index/hello', [], ['name' => '\w+', 'id' => '\d+']); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello-thinkphp2016')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check($request, 'hello-thinkphp2016')); Route::get('hello-/[:id]', 'index/hello', [], ['name' => '\w+', 'id' => '\d+']); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello-thinkphp/2016')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check($request, 'hello-thinkphp/2016')); } public function testParseUrl() @@ -94,66 +99,72 @@ class routeTest extends \PHPUnit_Framework_TestCase { Route::get('hello/:name', 'index/hello'); Route::get('blog/:id', 'blog/read', [], ['id' => '\d+']); - - $this->assertEquals(false, Route::check(Request::instance(), 'test/thinkphp')); - $this->assertEquals(false, Route::check(Request::instance(), 'blog/thinkphp')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check(Request::instance(), 'blog/5')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello/thinkphp/abc/test')); + $request = Request::instance(); + $this->assertEquals(false, Route::check($request, 'test/thinkphp')); + $this->assertEquals(false, Route::check($request, 'blog/thinkphp')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check($request, 'blog/5')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check($request, 'hello/thinkphp/abc/test')); } public function testCheckRouteGroup() { + $request = Request::instance(); Route::pattern(['id' => '\d+', 'name' => '\w{6,25}']); Route::group('group', [':id' => 'index/hello', ':name' => 'index/say']); - $this->assertEquals(false, Route::check(Request::instance(), 'empty/think')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check(Request::instance(), 'group/think')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'group/10')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check(Request::instance(), 'group/thinkphp')); + $this->assertEquals(false, Route::check($request, 'empty/think')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check($request, 'group/think')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check($request, 'group/10')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'say']], Route::check($request, 'group/thinkphp')); } 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::instance(), 'test/thinkphp')); - $this->assertEquals(false, Route::check(Request::instance(), 'blog/thinkphp')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check(Request::instance(), 'hello/thinkphp')); - $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check(Request::instance(), 'blog/5')); + $this->assertEquals(false, Route::check($request, 'test/thinkphp')); + $this->assertEquals(false, Route::check($request, 'blog/thinkphp')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check($request, 'hello/thinkphp')); + $this->assertEquals(['type' => 'module', 'module' => [null, 'blog', 'read']], Route::check($request, 'blog/5')); } public function testRouteToController() { + $request = Request::instance(); Route::get('say/:name', '@app\index\controller\index\hello'); - $this->assertEquals(['type' => 'controller', 'controller' => 'app\index\controller\index\hello', 'params' => ['name' => 'thinkphp']], Route::check(Request::instance(), 'say/thinkphp')); + $this->assertEquals(['type' => 'controller', 'controller' => 'app\index\controller\index\hello', 'params' => ['name' => 'thinkphp']], 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', 'params' => ['name' => 'thinkphp']], Route::check(Request::instance(), 'user/thinkphp')); - $this->assertEquals(['type' => 'method', 'method' => ['\app\index\model\Info', 'getInfo'], 'params' => ['name' => 'thinkphp']], Route::check(Request::instance(), 'info/thinkphp')); + $this->assertEquals(['type' => 'method', 'method' => '\app\index\service\User::get', 'params' => ['name' => 'thinkphp']], Route::check($request, 'user/thinkphp')); + $this->assertEquals(['type' => 'method', 'method' => ['\app\index\model\Info', 'getInfo'], 'params' => ['name' => 'thinkphp']], 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::instance(), 'art/8')); + $this->assertEquals(['type' => 'redirect', 'url' => '/article/read/id/8', 'status' => 301], Route::check($request, 'art/8')); } public function testBind() { + $request = Request::instance(); Route::bind('module', 'index/blog'); $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::parseUrl('read/10')); Route::get('index/blog/:id', 'index/blog/read'); - $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::check(Request::instance(), '10')); + $this->assertEquals(['type' => 'module', 'module' => ['index', 'blog', 'read']], Route::check($request, '10')); Route::bind('namespace', '\app\index\controller'); - $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check(Request::instance(), 'blog/read')); + $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check($request, 'blog/read')); Route::bind('class', '\app\index\controller\blog'); - $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check(Request::instance(), 'read')); + $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check($request, 'read')); } public function testSsl() From ee837df7c9fb1050583ddca078459fc7b6097c8c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 22:09:55 +0800 Subject: [PATCH 012/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E4=BA=8B=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 778fc531..8f5b8cdd 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -400,7 +400,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = null; } if (!in_array($field, $this->change)) { - if(in_array($field, $this->autoTimeField)) { + if (in_array($field, $this->autoTimeField)) { $this->__set($field, $value); } else { $this->__set($field, isset($this->data[$field]) ? $this->data[$field] : $value); @@ -867,7 +867,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (!isset(self::$links[$model])) { $class = new static; - self::$links[$model] = Db::connect($class->connection, $model); + self::$links[$model] = Db::connect($class->connection); self::$instance[$model] = $class; } else { $class = self::$instance[$model]; From a4fb28a3109e6ab576a5d683a65877925162864e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 11 May 2016 23:00:59 +0800 Subject: [PATCH 013/670] =?UTF-8?q?=E5=BA=9F=E9=99=A4=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=E6=98=A0=E5=B0=84=E5=8A=9F=E8=83=BD=20=E6=94=B9=E8=BF=9Broute?= =?UTF-8?q?=E5=8A=A9=E6=89=8B=E5=87=BD=E6=95=B0=20Route=E7=B1=BB=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0rule=E6=96=B9=E6=B3=95=E6=9B=BF=E4=BB=A3=E5=8E=9Fregis?= =?UTF-8?q?ter=E6=96=B9=E6=B3=95=EF=BC=8C=E5=8E=9Fregister=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=9B=B4=E5=90=8D=E4=B8=BAimport=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E7=94=A8=E4=BA=8E=E5=AF=BC=E5=85=A5=E8=B7=AF=E7=94=B1=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 2 +- library/think/App.php | 15 +--- library/think/Route.php | 87 +++++++++------------- tests/thinkphp/library/think/routeTest.php | 1 - 4 files changed, 38 insertions(+), 67 deletions(-) diff --git a/helper.php b/helper.php index 4806a0e5..ed0cd711 100644 --- a/helper.php +++ b/helper.php @@ -358,7 +358,7 @@ function view($template = '', $vars = []) */ function route($rule = '', $route = [], $type = '*', $option = [], $pattern = []) { - Route::register($rule, $route, $type, $option, $pattern); + Route::rule($rule, $route, $type, $option, $pattern); } /** diff --git a/library/think/App.php b/library/think/App.php index 1d747be6..49bcd33f 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -191,17 +191,6 @@ class App if (APP_MULTI_MODULE) { // 多模块部署 $module = strtolower($result[0] ?: $config['default_module']); - if ($maps = $config['url_module_map']) { - if (isset($maps[$module])) { - // 记录当前别名 - define('MODULE_ALIAS', $module); - // 获取实际的项目名 - $module = $maps[MODULE_ALIAS]; - } elseif (array_search($module, $maps)) { - // 禁止访问原始项目 - $module = ''; - } - } // 获取模块名称 define('MODULE_NAME', strip_tags($module)); @@ -335,8 +324,8 @@ class App if (APP_ROUTE_ON && !empty($config['url_route_on'])) { // 开启路由 if (!empty($config['route'])) { - // 注册路由定义文件 - Route::register($config['route']); + // 导入路由配置 + Route::import($config['route']); } // 路由检测(根据路由定义返回不同的URL调度) $result = Route::check($request, $_SERVER['PATH_INFO'], $depr, !IS_CLI ? $config['url_domain_deploy'] : false); diff --git a/library/think/Route.php b/library/think/Route.php index a0a6d511..b1e99c5d 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -97,63 +97,46 @@ class Route } } - // 注册路由规则 - public static function register($rule, $route = '', $type = '*', $option = [], $pattern = []) + // 导入配置文件定义的路由规则 + public static function import(array $rule, $type = '*') { - if (strpos($type, '|')) { - foreach (explode('|', $type) as $val) { - self::register($rule, $route, $val, $option); - } - } else { - if (is_array($rule)) { - // 检查域名部署 - 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['__map__'])) { - self::map($rule['__map__']); - unset($rule['__map__']); - } - // 检查资源路由 - if (isset($rule['__rest__'])) { - self::resource($rule['__rest__']); - unset($rule['__rest__']); - } + // 检查域名部署 + 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['__map__'])) { + self::map($rule['__map__']); + unset($rule['__map__']); + } + // 检查资源路由 + if (isset($rule['__rest__'])) { + self::resource($rule['__rest__']); + unset($rule['__rest__']); + } - foreach ($rule as $key => $val) { - if (is_numeric($key)) { - $key = array_shift($val); - } - if (0 === strpos($key, '[')) { - if (empty($val)) { - continue; - } - $key = substr($key, 1, -1); - $result = ['routes' => $val, 'option' => $option, 'pattern' => $pattern]; - } elseif (is_array($val)) { - $result = ['route' => $val[0], 'option' => $val[1], 'pattern' => isset($val[2]) ? $val[2] : []]; - } else { - $result = ['route' => $val, 'option' => $option, 'pattern' => $pattern]; - } - self::$rules[$type][$key] = $result; + foreach ($rule as $key => $val) { + if (is_numeric($key)) { + $key = array_shift($val); + } + if (0 === strpos($key, '[')) { + if (empty($val)) { + continue; } + $key = substr($key, 1, -1); + $result = ['routes' => $val, 'option' => [], 'pattern' => []]; + } elseif (is_array($val)) { + $result = ['route' => $val[0], 'option' => $val[1], 'pattern' => isset($val[2]) ? $val[2] : []]; } else { - if (0 === strpos($rule, '[')) { - $rule = substr($rule, 1, -1); - $result = ['routes' => $route, 'option' => $option, 'pattern' => $pattern]; - } else { - $result = ['route' => $route, 'option' => $option, 'pattern' => $pattern]; - } - self::$rules[$type][$rule] = $result; + $result = ['route' => $val, 'option' => [], 'pattern' => []]; } - + self::$rules[$type][$key] = $result; } } diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index bbe31686..e3d3e20f 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -33,7 +33,6 @@ class routeTest extends \PHPUnit_Framework_TestCase Route::any('user/:id', 'index/user'); $this->assertEquals(['type' => 'module', 'module' => [null, 'index', 'hello']], Route::check($request, 'hello/thinkphp')); $this->assertEquals(['hello/:name' => ['route' => 'index/hello', 'option' => [], 'pattern' => []]], Route::getRules('GET')); - Route::register('type/:name', 'index/type', 'PUT|POST'); Route::rule('type/:name', 'index/type', 'PUT|POST'); } From 49c899acc59ee5b77bd039b6f020d7861b6273bf Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 12 May 2016 08:15:05 +0800 Subject: [PATCH 014/670] =?UTF-8?q?=E8=B0=83=E6=95=B4=20error=E5=92=8Csucc?= =?UTF-8?q?ess=E6=96=B9=E6=B3=95=E7=9A=84=E5=8F=82=E6=95=B0=E9=A1=BA?= =?UTF-8?q?=E5=BA=8F=20=E5=92=8C=E5=8E=9F=E6=9D=A5=E4=BF=9D=E6=8C=81?= =?UTF-8?q?=E4=B8=80=E8=87=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/traits/controller/Jump.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index cf54966e..39f5b761 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -24,12 +24,12 @@ trait Jump * 操作成功跳转的快捷方法 * @access public * @param mixed $msg 提示信息 - * @param mixed $data 返回的数据 * @param string $url 跳转的URL地址 + * @param mixed $data 返回的数据 * @param integer $wait 跳转等待时间 - * @return mixed + * @return void */ - public static function success($msg = '', $data = '', $url = null, $wait = 3) + public static function success($msg = '', $url = null, $data = '', $wait = 3) { $code = 1; if (is_numeric($msg)) { @@ -57,12 +57,12 @@ trait Jump * 操作错误跳转的快捷方法 * @access public * @param mixed $msg 提示信息 - * @param mixed $data 返回的数据 * @param string $url 跳转的URL地址 + * @param mixed $data 返回的数据 * @param integer $wait 跳转等待时间 - * @return mixed + * @return void */ - public static function error($msg = '', $data = '', $url = null, $wait = 3) + public static function error($msg = '', $url = null, $data = '', $wait = 3) { $code = 0; if (is_numeric($msg)) { From 67cebd8ca172ed137f174e7683ec0d0a2d2505bb Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 12 May 2016 09:45:07 +0800 Subject: [PATCH 015/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3traits\controller/Jum?= =?UTF-8?q?p.php?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/traits/controller/Jump.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index 39f5b761..8c2e4b38 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -29,7 +29,7 @@ trait Jump * @param integer $wait 跳转等待时间 * @return void */ - public static function success($msg = '', $url = null, $data = '', $wait = 3) + public function success($msg = '', $url = null, $data = '', $wait = 3) { $code = 1; if (is_numeric($msg)) { @@ -62,7 +62,7 @@ trait Jump * @param integer $wait 跳转等待时间 * @return void */ - public static function error($msg = '', $url = null, $data = '', $wait = 3) + public function error($msg = '', $url = null, $data = '', $wait = 3) { $code = 0; if (is_numeric($msg)) { From dfd1f499fb191ec287cf671153185f163d0736d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=9F=E5=B8=85=E5=B9=B2?= Date: Thu, 12 May 2016 18:05:10 +0800 Subject: [PATCH 016/670] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20=E6=A3=80=E6=B5=8B?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E7=BC=93=E5=AD=98=E6=98=AF=E5=90=A6=E6=9C=89?= =?UTF-8?q?=E6=95=88=20=E6=96=B9=E6=B3=95bug,=20=E5=85=88=E5=88=A4?= =?UTF-8?q?=E6=96=AD=E7=BC=93=E5=AD=98=E6=96=87=E4=BB=B6=E6=98=AF=E5=90=A6?= =?UTF-8?q?=E5=AD=98=E5=9C=A8,=20=E5=A6=82=E6=9E=9C=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E4=B8=8D=E5=AD=98=E5=9C=A8=E8=80=8C=E7=9B=B4=E6=8E=A5=E8=B0=83?= =?UTF-8?q?=E7=94=A8filemtime=E4=BC=9A=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/template/driver/File.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/template/driver/File.php b/library/think/template/driver/File.php index c369390e..bfb2787d 100644 --- a/library/think/template/driver/File.php +++ b/library/think/template/driver/File.php @@ -52,13 +52,16 @@ class File /** * 检查编译缓存是否有效 - * @array $templates 用到的模板文件及更新时间列表 * @string $cacheFile 缓存的文件名 * @int $cacheTime 缓存时间 * @return boolean */ public function check($cacheFile, $cacheTime) { + // 缓存文件不存在, 直接返回false + if (!file_exists($cacheFile)) { + return false; + } if (0 != $cacheTime && time() > filemtime($cacheFile) + $cacheTime) { // 缓存是否在有效期 return false; From c3af0bb1c48f2476486b708cc8b08fa8d19246aa Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 12 May 2016 21:53:54 +0800 Subject: [PATCH 017/670] =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E7=9A=84=E6=97=B6?= =?UTF-8?q?=E9=97=B4=E6=88=B3=E8=87=AA=E5=8A=A8=E5=86=99=E5=85=A5=E6=94=AF?= =?UTF-8?q?=E6=8C=81timestamp=E7=B1=BB=E5=9E=8B=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 26 +++++++++++++++++++++++++- library/think/db/connector/Oracle.php | 1 + library/think/db/connector/Pgsql.php | 1 + library/think/db/connector/Sqlite.php | 1 + library/think/db/connector/Sqlsrv.php | 1 + 5 files changed, 29 insertions(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index 8f5b8cdd..4c974ef5 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -916,7 +916,23 @@ abstract class Model implements \JsonSerializable, \ArrayAccess { if (is_null($value) && in_array($name, $this->autoTimeField)) { // 自动写入的时间戳字段 - $value = NOW_TIME; + if (isset($this->type[$name])) { + $type = $this->type[$name]; + if (strpos($type, ':')) { + list($type, $param) = explode(':', $type, 2); + } + switch ($type) { + case 'timestamp': + $format = !empty($param) ? $param : $this->dateFormat; + $value = date($format, NOW_TIME); + break; + case 'datetime': + $value = NOW_TIME; + break; + } + } else { + $value = NOW_TIME; + } } else { // 检测修改器 $method = 'set' . Loader::parseName($name, 1) . 'Attr'; @@ -947,6 +963,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = strtotime($value); } break; + case 'timestamp': + $format = !empty($param) ? $param : $this->dateFormat; + $value = date($format, is_numeric($valiue) ? $value : strtotime($value)); + break; case 'object': if (is_object($value)) { $value = json_encode($value, JSON_FORCE_OBJECT); @@ -1008,6 +1028,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $format = !empty($param) ? $param : $this->dateFormat; $value = date($format, $value); break; + case 'timestamp': + $format = !empty($param) ? $param : $this->dateFormat; + $value = date($format, strtotime($value)); + break; case 'json': case 'array': $value = json_decode($value, true); diff --git a/library/think/db/connector/Oracle.php b/library/think/db/connector/Oracle.php index cc4f6496..ab35d7bc 100644 --- a/library/think/db/connector/Oracle.php +++ b/library/think/db/connector/Oracle.php @@ -102,6 +102,7 @@ class Oracle extends Connection */ public function getFields($tableName) { + $this->initConnect(true); list($tableName) = explode(' ', $tableName); $sql = "select a.column_name,data_type,DECODE (nullable, 'Y', 0, 1) notnull,data_default, DECODE (A .column_name,b.column_name,1,0) pk from all_tab_columns a,(select column_name from all_constraints c, all_cons_columns col where c.constraint_name = col.constraint_name and c.constraint_type = 'P' and c.table_name = '" . strtoupper($tableName) . "' ) b where table_name = '" . strtoupper($tableName) . "' and a.column_name = b.column_name (+)"; $pdo = $this->linkID->query($sql); diff --git a/library/think/db/connector/Pgsql.php b/library/think/db/connector/Pgsql.php index 58a33c34..a2c40b17 100644 --- a/library/think/db/connector/Pgsql.php +++ b/library/think/db/connector/Pgsql.php @@ -43,6 +43,7 @@ class Pgsql extends Connection */ 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 . ');'; $pdo = $this->linkID->query($sql); diff --git a/library/think/db/connector/Sqlite.php b/library/think/db/connector/Sqlite.php index e3b03afb..cac8c352 100644 --- a/library/think/db/connector/Sqlite.php +++ b/library/think/db/connector/Sqlite.php @@ -40,6 +40,7 @@ class Sqlite extends Connection */ public function getFields($tableName) { + $this->initConnect(true); list($tableName) = explode(' ', $tableName); $sql = 'PRAGMA table_info( ' . $tableName . ' )'; $pdo = $this->linkID->query($sql); diff --git a/library/think/db/connector/Sqlsrv.php b/library/think/db/connector/Sqlsrv.php index 2eead773..cfc80991 100644 --- a/library/think/db/connector/Sqlsrv.php +++ b/library/think/db/connector/Sqlsrv.php @@ -50,6 +50,7 @@ class Sqlsrv extends Connection */ public function getFields($tableName) { + $this->initConnect(true); list($tableName) = explode(' ', $tableName); $sql = "SELECT column_name, data_type, column_default, is_nullable FROM information_schema.tables AS t From 792f1462616b0cc4809455451af6855553585dfa Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 13 May 2016 09:54:26 +0800 Subject: [PATCH 018/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Model=20=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E6=97=B6=E9=97=B4=E6=88=B3=E5=AD=97=E6=AE=B5=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E8=AF=86=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 4c974ef5..01802092 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -76,6 +76,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $updateWhere; // 当前执行的关联对象 protected $relation; + // 属性类型 + protected $fieldType = []; /** * 初始化过的模型. @@ -99,7 +101,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (empty($this->name)) { $this->name = basename(str_replace('\\', '/', get_class($this))); } - + // 获取字段类型信息并缓存 + $this->fieldType = self::db()->getTableInfo('', 'type'); $this->initialize(); $this->relation = new Relation($this); } @@ -880,6 +883,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $name = !empty($class->name) ? $class->name : basename(str_replace('\\', '/', $model)); self::$links[$model]->name($name); } + // 设置当前模型 确保查询返回模型对象 self::$links[$model]->model($model); // 返回当前数据库对象 @@ -930,6 +934,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = NOW_TIME; break; } + } elseif (isset($this->fieldType[$name]) && preg_match('/(datetime|timestamp)/is', $this->fieldType[$name])) { + $value = date($this->dateFormat, NOW_TIME); } else { $value = NOW_TIME; } @@ -965,7 +971,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess break; case 'timestamp': $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, is_numeric($valiue) ? $value : strtotime($value)); + $value = date($format, is_numeric($value) ? $value : strtotime($value)); break; case 'object': if (is_object($value)) { From 13ffe40a448acde244393bb0b827541f7ae0507d Mon Sep 17 00:00:00 2001 From: shuipf Date: Fri, 13 May 2016 10:42:43 +0800 Subject: [PATCH 019/670] =?UTF-8?q?=E4=BC=98=E5=8C=96set=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E5=99=A8=EF=BC=8C$data=E4=B8=8D=E5=AE=8C=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 经常遇到的坑是: 比如新增 a b c d 4个字段内容,进行新增操作调用save方法。由于save对$data是进行遍历调用修改器,导致当前对象的$this->data并不完整。例如b字段是和d字段有一定关联关系的,因为是foreach的方式,导致执行到d的修改器时,压根在$data参数获取不到d的值!,虽然可以在修改器里,直接获取外部提交的变量,但这种方式,不完美!如果我不是外部获取的数据呢?那岂不是没辙了! --- library/think/Model.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 01802092..0504e13e 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -256,7 +256,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (!empty($data)) { // 数据对象赋值 foreach ($data as $key => $value) { - $this->__set($key, $value); + $this->__set($key, $value, $data); } if (!empty($where)) { $this->isUpdate = true; @@ -914,9 +914,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @access public * @param string $name 名称 * @param mixed $value 值 + * @param array $data 数据信息 * @return void */ - public function __set($name, $value) + public function __set($name, $value, $data = []) { if (is_null($value) && in_array($name, $this->autoTimeField)) { // 自动写入的时间戳字段 @@ -943,7 +944,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 检测修改器 $method = 'set' . Loader::parseName($name, 1) . 'Attr'; if (method_exists($this, $method)) { - $value = $this->$method($value, $this->data); + $value = $this->$method($value, array_merge($data, $this->data)); } elseif (isset($this->type[$name])) { // 类型转换 $type = $this->type[$name]; From aaa0fd7c9f02f2cd11f5d5340577483590578fe4 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Fri, 13 May 2016 19:05:41 +0800 Subject: [PATCH 020/670] =?UTF-8?q?=E5=AE=8C=E5=96=84=E6=A1=86=E6=9E=B6?= =?UTF-8?q?=E7=9A=84=E5=BC=82=E5=B8=B8=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 4 +- library/think/App.php | 60 ++--- library/think/Error.php | 194 ++++----------- library/think/Exception.php | 17 +- library/think/Log.php | 20 +- library/think/Response.php | 2 +- .../think/exception/DbBindParamException.php | 9 + library/think/exception/Handle.php | 222 ++++++++++++++++++ library/think/exception/HttpException.php | 37 +++ ...xception.php => HttpResponseException.php} | 34 ++- library/think/exception/ThrowableError.php | 49 ++++ 11 files changed, 434 insertions(+), 214 deletions(-) create mode 100644 library/think/exception/Handle.php create mode 100644 library/think/exception/HttpException.php rename library/think/exception/{NotFoundException.php => HttpResponseException.php} (52%) create mode 100644 library/think/exception/ThrowableError.php diff --git a/convention.php b/convention.php index 86f205c1..10fa3218 100644 --- a/convention.php +++ b/convention.php @@ -123,9 +123,7 @@ return [ // 异常页面的模板文件 'exception_tmpl' => THINK_PATH . 'tpl' . DS . 'think_exception.tpl', - // 异常处理忽略的错误类型,支持PHP所有的错误级别常量,多个级别可以用|运算法 - // 参考:http://php.net/manual/en/errorfunc.constants.php - 'exception_ignore_type' => 0, + // 错误显示信息,非调试模式有效 'error_message' => '页面错误!请稍后再试~', // 错误定向页面 diff --git a/library/think/App.php b/library/think/App.php index 49bcd33f..e37d3f2b 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -11,6 +11,7 @@ namespace think; +use think\exception\HttpResponseException; use think\Response; /** @@ -24,7 +25,8 @@ class App * 执行应用程序 * @access public * @param \think\Request $request Request对象 - * @return void + * @return \think\Response + * @throws Exception */ public static function run($request) { @@ -76,32 +78,36 @@ class App APP_DEBUG && Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info'); // 监听app_begin APP_HOOK && Hook::listen('app_begin', $dispatch); - switch ($dispatch['type']) { - case 'redirect': - // 执行重定向跳转 - header('Location: ' . $dispatch['url'], true, $dispatch['status']); - break; - case 'module': - // 模块/控制器/操作 - $data = self::module($dispatch['module'], $config); - break; - case 'controller': - // 执行控制器操作 - $data = Loader::action($dispatch['controller'], $dispatch['params']); - break; - case 'method': - // 执行回调方法 - $data = self::invokeMethod($dispatch['method'], $dispatch['params']); - break; - case 'function': - // 规则闭包 - $data = self::invokeFunction($dispatch['function'], $dispatch['params']); - break; - case 'finish': - // 已经完成 不再继续执行 - break; - default: - throw new Exception('dispatch type not support', 10008); + try { + switch ($dispatch['type']) { + case 'redirect': + // 执行重定向跳转 + header('Location: ' . $dispatch['url'], true, $dispatch['status']); + break; + case 'module': + // 模块/控制器/操作 + $data = self::module($dispatch['module'], $config); + break; + case 'controller': + // 执行控制器操作 + $data = Loader::action($dispatch['controller'], $dispatch['params']); + break; + case 'method': + // 执行回调方法 + $data = self::invokeMethod($dispatch['method'], $dispatch['params']); + break; + case 'function': + // 规则闭包 + $data = self::invokeFunction($dispatch['function'], $dispatch['params']); + break; + case 'finish': + // 已经完成 不再继续执行 + break; + default: + throw new Exception('dispatch type not support', 10008); + } + } catch (HttpResponseException $exception){ + $data = $exception->getResponse(); } // 输出数据到客户端 if (isset($data)) { diff --git a/library/think/Error.php b/library/think/Error.php index 9b760e13..26fa20c9 100644 --- a/library/think/Error.php +++ b/library/think/Error.php @@ -11,9 +11,9 @@ namespace think; -use think\Config; use think\exception\ErrorException; -use think\Log; +use think\exception\Handle; +use think\exception\ThrowableError; class Error { @@ -23,66 +23,29 @@ class Error */ public static function register() { + error_reporting(-1); set_error_handler([__CLASS__, 'appError']); set_exception_handler([__CLASS__, 'appException']); register_shutdown_function([__CLASS__, 'appShutdown']); + + if (!APP_DEBUG) { + ini_set('display_errors', 'Off'); + } } /** * Exception Handler - * @param \Exception $exception - * @return bool true-禁止往下传播已处理过的异常 + * @param \Exception $e */ - public static function appException($exception) + public static function appException($e) { - // 收集异常数据 - if (APP_DEBUG) { - // 调试模式,获取详细的错误信息 - $data = [ - 'name' => get_class($exception), - 'file' => $exception->getFile(), - 'line' => $exception->getLine(), - 'message' => $exception->getMessage(), - 'trace' => $exception->getTrace(), - 'code' => self::getCode($exception), - 'source' => self::getSourceCode($exception), - 'datas' => self::getExtendData($exception), - - 'tables' => [ - 'GET Data' => $_GET, - 'POST Data' => $_POST, - 'Files' => $_FILES, - 'Cookies' => $_COOKIE, - 'Session' => isset($_SESSION) ? $_SESSION : [], - 'Server/Request Data' => $_SERVER, - 'Environment Variables' => $_ENV, - 'ThinkPHP Constants' => self::getTPConst(), - ], - ]; - $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; - } else { - // 部署模式仅显示 Code 和 Message - $data = [ - 'code' => $exception->getCode(), - 'message' => $exception->getMessage(), - ]; - $log = "[{$data['code']}]{$data['message']}"; + if (!$e instanceof \Exception) { + $e = new ThrowableError($e); } + + self::getExceptionHandler()->report($e); - // 记录异常日志 - Log::record($log, 'error'); - - /* 非API模式下的部署模式,跳转到指定的 Error Page */ - $error_page = Config::get('error_page'); - if (!(APP_DEBUG || IS_API) && !empty($error_page)) { - header("Location: {$error_page}"); - } else { - // 输出错误信息 - self::output($exception, $data); - } - - // 禁止往下传播已处理过的异常 - return true; + self::getExceptionHandler()->render($e)->send(); } /** @@ -91,31 +54,24 @@ class Error * @param integer $errstr 详细错误信息 * @param string $errfile 出错的文件 * @param integer $errline 出错行号 - * @return bool true-禁止往下传播已处理过的异常 + * @param array $errcontext + * @return bool true-禁止往下传播已处理过的异常 + * @throws ErrorException */ - public static function appError($errno, $errstr, $errfile = null, $errline = 0, array $errcontext = []) + public static function appError($errno, $errstr, $errfile = '', $errline = 0, $errcontext = []) { - if ($errno & Config::get('exception_ignore_type')) { - // 忽略的异常记录到日志 - Log::record("[{$errno}]{$errstr}[{$errfile}:{$errline}]", 'notice'); - } else { + if (error_reporting() & $errno) { // 将错误信息托管至 think\exception\ErrorException throw new ErrorException($errno, $errstr, $errfile, $errline, $errcontext); - // 禁止往下传播已处理过的异常 - return true; } } /** * Shutdown Handler - * @return bool true-禁止往下传播已处理过的异常; false-未处理的异常继续传播 */ public static function appShutdown() { - // 写入日志 - Log::save(); - - if ($error = error_get_last()) { + if (!is_null($error = error_get_last()) && self::isFatal($error['type'])) { // 将错误信息托管至think\ErrorException $exception = new ErrorException( $error['type'], @@ -124,108 +80,46 @@ class Error $error['line'] ); - /** - * Shutdown handler 中的异常将不被往下传播 - * 所以,这里我们必须手动传播而不能像 Error handler 中那样 throw - */ self::appException($exception); - // 禁止往下传播已处理过的异常 - return true; } - return false; + + // 写入日志 + Log::save(); } /** - * 输出异常信息 - * @param \Exception $exception - * @param array $data 异常信息 - * @return void + * 确定错误类型是否致命 + * + * @param int $type + * @return bool */ - public static function output($exception, array $data) + protected static function isFatal($type) { - http_response_code($exception instanceof Exception ? $exception->getHttpStatus() : 500); - - $type = Config::get('default_return_type'); - if (!APP_DEBUG && !Config::get('show_error_msg')) { - // 不显示详细错误信息 - $data['message'] = Config::get('error_message'); - } - if (IS_API && 'html' != $type) { - // 异常信息输出监听 - APP_HOOK && Hook::listen('error_output', $data); - // 输出异常内容 - Response::instance()->send($data, $type, Config::get('response_return')); - } else { - //ob_end_clean(); - extract($data); - include Config::get('exception_tmpl'); - } + return in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE]); } - /** - * 获取错误编码 - * ErrorException则使用错误级别作为错误编码 - * @param \Exception $exception - * @return integer 错误编码 - */ - private static function getCode($exception) - { - $code = $exception->getCode(); - if (!$code && $exception instanceof ErrorException) { - $code = $exception->getSeverity(); - } - return $code; - } /** - * 获取出错文件内容 - * 获取错误的前9行和后9行 - * @param \Exception $exception - * @return array 错误文件内容 + * Get an instance of the exception handler. + * + * @return \think\exception\Handle */ - private static function getSourceCode($exception) + protected static function getExceptionHandler() { - // 读取前9行和后9行 - $line = $exception->getLine(); - $first = ($line - 9 > 0) ? $line - 9 : 1; + static $handle; - try { - $contents = file($exception->getFile()); - $source = [ - 'first' => $first, - 'source' => array_slice($contents, $first - 1, 19), - ]; - } catch (Exception $e) { - $source = []; - } - return $source; - } + if (!$handle) { - /** - * 获取异常扩展信息 - * 用于非调试模式html返回类型显示 - * @param \Exception $exception - * @return array 异常类定义的扩展数据 - */ - private static function getExtendData($exception) - { - $data = []; - if ($exception instanceof Exception) { - $data = $exception->getData(); + if ($class = Config::get('exception_handle')) { + if (class_exists($class) && is_subclass_of($class, "\\think\\exception\\Handle")) { + $handle = new $class; + } + } + if (!$handle) { + $handle = new Handle(); + } } - return $data; - } - /** - * 获取ThinkPHP常量列表 - * @return array 常量列表 - */ - private static function getTPConst() - { - $consts = ['THINK_VERSION', 'THINK_PATH', 'LIB_PATH', 'EXTEND_PATH', 'MODE_PATH', 'CORE_PATH', 'TRAIT_PATH', 'APP_PATH', 'RUNTIME_PATH', 'LOG_PATH', 'CACHE_PATH', 'TEMP_PATH', 'MODULE_PATH', 'VIEW_PATH', 'APP_NAMESPACE', 'COMMON_MODULE', 'APP_MULTI_MODULE', 'MODULE_ALIAS', 'MODULE_NAME', 'CONTROLLER_NAME', 'ACTION_NAME', 'MODEL_LAYER', 'VIEW_LAYER', 'CONTROLLER_LAYER', 'APP_DEBUG', 'APP_HOOK', 'ENV_PREFIX', 'IS_API', 'VENDOR_PATH', 'APP_AUTO_RUN', 'APP_MODE', 'REQUEST_METHOD', 'IS_CGI', 'IS_WIN', 'IS_API', 'IS_CLI', 'IS_GET', 'IS_POST', 'IS_PUT', 'IS_AJAX', 'IS_DELETE', 'NOW_TIME', 'LANG_SET', 'EXT', 'DS', '__INFO__', '__EXT__']; - foreach ($consts as $const) { - $data[$const] = defined($const) ? constant($const) : 'undefined'; - } - return $data; + return $handle; } } diff --git a/library/think/Exception.php b/library/think/Exception.php index abf32018..bc4cbdb2 100644 --- a/library/think/Exception.php +++ b/library/think/Exception.php @@ -17,11 +17,6 @@ namespace think; */ class Exception extends \Exception { - /** - * 系统异常后发送给客户端的HTTP Status - * @var integer - */ - protected $httpStatus = 500; /** * 保存异常页面显示的额外Debug数据 @@ -43,7 +38,7 @@ class Exception extends \Exception * key2 value2 * * @param string $label 数据分类,用于异常页面显示 - * @param Array $data 需要显示的数据,必须为关联数组 + * @param array $data 需要显示的数据,必须为关联数组 */ final protected function setData($label, array $data) { @@ -59,13 +54,5 @@ class Exception extends \Exception { return $this->data; } - - /** - * 获取要发送给客户端的HTTP Status - * @return integer HTTP Status - */ - final public function getHttpStatus() - { - return $this->httpStatus; - } + } diff --git a/library/think/Log.php b/library/think/Log.php index 7b41c6ee..a7cb4ec9 100644 --- a/library/think/Log.php +++ b/library/think/Log.php @@ -68,7 +68,7 @@ class Log /** * 记录调试信息 - * @param mixed $msg 调试信息 + * @param mixed $msg 调试信息 * @param string $type 信息类型 * @return void */ @@ -95,15 +95,25 @@ class Log */ public static function save() { - if (is_null(self::$driver)) { - self::init(Config::get('log')); + if (!empty(self::$log)) { + if (is_null(self::$driver)) { + self::init(Config::get('log')); + } + + $result = self::$driver->save(self::$log); + + if ($result) { + self::$log = []; + } + + return $result; } - return self::$driver->save(self::$log); + return true; } /** * 实时写入日志信息 并支持行为 - * @param mixed $msg 调试信息 + * @param mixed $msg 调试信息 * @param string $type 信息类型 * @return bool */ diff --git a/library/think/Response.php b/library/think/Response.php index 55e450ae..e0943711 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -50,7 +50,7 @@ class Response * 初始化 * @access public * @param string $type 输出类型 - * @return \think\Request + * @return \think\Response */ public static function instance($type = '') { diff --git a/library/think/exception/DbBindParamException.php b/library/think/exception/DbBindParamException.php index 21ddcd58..f39c39ac 100644 --- a/library/think/exception/DbBindParamException.php +++ b/library/think/exception/DbBindParamException.php @@ -18,6 +18,15 @@ use think\exception\DbException; */ class DbBindParamException extends DbException { + + /** + * DbBindParamException constructor. + * @param string $message + * @param array $config + * @param string $sql + * @param array $bind + * @param int $code + */ public function __construct($message, $config, $sql, $bind, $code = 10502) { $this->setData('Bind Param', $bind); diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php new file mode 100644 index 00000000..890ef93e --- /dev/null +++ b/library/think/exception/Handle.php @@ -0,0 +1,222 @@ + +// +---------------------------------------------------------------------- + +namespace think\exception; + +use Exception; +use think\Config; +use think\Log; +use think\Response; + +class Handle +{ + + protected $ignoreReport = [ + '\\think\\exception\\HttpException' + ]; + + /** + * Report or log an exception. + * + * @param \Exception $exception + * @return void + */ + public function report(Exception $exception) + { + if (!$this->isIgnoreReport($exception)) { + // 收集异常数据 + if (APP_DEBUG) { + $data = [ + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + 'message' => $exception->getMessage(), + 'code' => $this->getCode($exception) + ]; + $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; + } else { + $data = [ + 'code' => $exception->getCode(), + 'message' => $exception->getMessage(), + ]; + $log = "[{$data['code']}]{$data['message']}"; + } + + Log::record($log, 'error'); + } + } + + protected function isIgnoreReport(Exception $exception) + { + foreach ($this->ignoreReport as $class) { + if ($exception instanceof $class) { + return true; + } + } + + return false; + } + + /** + * Render an exception into an HTTP response. + * + * @param \Exception $e + * @return Response + */ + public function render(Exception $e) + { + if ($e instanceof HttpException) { + return $this->renderHttpException($e); + } else { + return $this->convertExceptionToResponse($e); + } + } + + /** + * @param HttpException $e + * @return \think\Response + */ + protected function renderHttpException(HttpException $e) + { + $status = $e->getStatusCode(); + + //TODO 根据状态码自动输出错误页面 + + return $this->convertExceptionToResponse($e); + } + + /** + * @param Exception $exception + * @return Response + */ + protected function convertExceptionToResponse(Exception $exception) + { + // 收集异常数据 + if (APP_DEBUG) { + // 调试模式,获取详细的错误信息 + $data = [ + 'name' => get_class($exception), + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + 'message' => $exception->getMessage(), + 'trace' => $exception->getTrace(), + 'code' => $this->getCode($exception), + 'source' => $this->getSourceCode($exception), + 'datas' => $this->getExtendData($exception), + + 'tables' => [ + 'GET Data' => $_GET, + 'POST Data' => $_POST, + 'Files' => $_FILES, + 'Cookies' => $_COOKIE, + 'Session' => isset($_SESSION) ? $_SESSION : [], + 'Server/Request Data' => $_SERVER, + 'Environment Variables' => $_ENV, + 'ThinkPHP Constants' => $this->getConst(), + ] + ]; + } else { + // 部署模式仅显示 Code 和 Message + $data = [ + 'code' => $exception->getCode(), + 'message' => $exception->getMessage(), + ]; + } + + if (!APP_DEBUG && !Config::get('show_error_msg')) { + // 不显示详细错误信息 + $data['message'] = Config::get('error_message'); + } + ob_start(); + ob_implicit_flush(0); + extract($data); + include Config::get('exception_tmpl'); + // 获取并清空缓存 + $content = ob_get_clean(); + + $response = Response::instance()->data($content); + + if ($exception instanceof HttpException) { + $statusCode = $exception->getStatusCode(); + //TODO 设置headers 等待response完善 + } + + if (!isset($statusCode)) { + $statusCode = 500; + } + $response->code($statusCode); + + return $response; + } + + /** + * 获取错误编码 + * ErrorException则使用错误级别作为错误编码 + * @param \Exception $exception + * @return integer 错误编码 + */ + protected function getCode(Exception $exception) + { + $code = $exception->getCode(); + if (!$code && $exception instanceof ErrorException) { + $code = $exception->getSeverity(); + } + return $code; + } + + /** + * 获取出错文件内容 + * 获取错误的前9行和后9行 + * @param \Exception $exception + * @return array 错误文件内容 + */ + protected function getSourceCode(Exception $exception) + { + // 读取前9行和后9行 + $line = $exception->getLine(); + $first = ($line - 9 > 0) ? $line - 9 : 1; + + try { + $contents = file($exception->getFile()); + $source = [ + 'first' => $first, + 'source' => array_slice($contents, $first - 1, 19), + ]; + } catch (Exception $e) { + $source = []; + } + return $source; + } + + + /** + * 获取异常扩展信息 + * 用于非调试模式html返回类型显示 + * @param \Exception $exception + * @return array 异常类定义的扩展数据 + */ + protected function getExtendData(Exception $exception) + { + $data = []; + if ($exception instanceof \think\Exception) { + $data = $exception->getData(); + } + return $data; + } + + /** + * 获取常量列表 + * @return array 常量列表 + */ + private static function getConst() + { + return get_defined_constants(true)['user']; + } +} \ No newline at end of file diff --git a/library/think/exception/HttpException.php b/library/think/exception/HttpException.php new file mode 100644 index 00000000..99beb002 --- /dev/null +++ b/library/think/exception/HttpException.php @@ -0,0 +1,37 @@ + +// +---------------------------------------------------------------------- + +namespace think\exception; + + +class HttpException extends \RuntimeException +{ + private $statusCode; + private $headers; + + public function __construct($statusCode, $message = null, \Exception $previous = null, array $headers = [], $code = 0) + { + $this->statusCode = $statusCode; + $this->headers = $headers; + + parent::__construct($message, $code, $previous); + } + + public function getStatusCode() + { + return $this->statusCode; + } + + public function getHeaders() + { + return $this->headers; + } +} \ No newline at end of file diff --git a/library/think/exception/NotFoundException.php b/library/think/exception/HttpResponseException.php similarity index 52% rename from library/think/exception/NotFoundException.php rename to library/think/exception/HttpResponseException.php index 06ae2e5d..249e3da3 100644 --- a/library/think/exception/NotFoundException.php +++ b/library/think/exception/HttpResponseException.php @@ -1,27 +1,35 @@ +// | Author: yunwuxin <448901948@qq.com> // +---------------------------------------------------------------------- namespace think\exception; -use think\Exception; -/** - * Database相关异常处理类 - */ -class NotFoundException extends Exception +use think\Response; + +class HttpResponseException extends \RuntimeException { /** - * 系统异常后发送给客户端的HTTP Status - * @var integer + * @var Response */ - protected $httpStatus = 404; - -} + protected $response; + + public function __construct(Response $response) + { + $this->response = $response; + } + + public function getResponse() + { + return $this->response; + } + + +} \ No newline at end of file diff --git a/library/think/exception/ThrowableError.php b/library/think/exception/ThrowableError.php new file mode 100644 index 00000000..8ba26ea8 --- /dev/null +++ b/library/think/exception/ThrowableError.php @@ -0,0 +1,49 @@ + +// +---------------------------------------------------------------------- + +namespace think\exception; + + +class ThrowableError extends \ErrorException +{ + public function __construct(\Throwable $e) + { + + if ($e instanceof \ParseError) { + $message = 'Parse error: ' . $e->getMessage(); + $severity = E_PARSE; + } elseif ($e instanceof \TypeError) { + $message = 'Type error: ' . $e->getMessage(); + $severity = E_RECOVERABLE_ERROR; + } else { + $message = 'Fatal error: ' . $e->getMessage(); + $severity = E_ERROR; + } + + parent::__construct( + $message, + $e->getCode(), + $severity, + $e->getFile(), + $e->getLine() + ); + + + $this->setTrace($e->getTrace()); + } + + protected function setTrace($trace) + { + $traceReflector = new \ReflectionProperty('Exception', 'trace'); + $traceReflector->setAccessible(true); + $traceReflector->setValue($this, $trace); + } +} \ No newline at end of file From 90b86c684c9719c31df8794d23595a0408d0cc42 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 13 May 2016 22:18:24 +0800 Subject: [PATCH 021/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Model=E7=B1=BB?= =?UTF-8?q?=E5=92=8CConfig=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Config.php | 2 +- library/think/Model.php | 22 ++++++++++++---------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/library/think/Config.php b/library/think/Config.php index 8e181340..2c833111 100644 --- a/library/think/Config.php +++ b/library/think/Config.php @@ -62,7 +62,7 @@ class Config APP_DEBUG && Log::record('[ CONFIG ] ' . $file, 'info'); $type = pathinfo($file, PATHINFO_EXTENSION); if ('php' != $type) { - return self::parse($config, $type, $name, $range); + return self::parse($file, $type, $name, $range); } else { return self::set(include $file, $name, $range); } diff --git a/library/think/Model.php b/library/think/Model.php index 0504e13e..6a6b84ad 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -90,8 +90,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * 架构函数 * @access public * @param array|object $data 数据 + * @param bool $init 是否需要初始化 */ - public function __construct($data = []) + public function __construct($data = [], $init = true) { if (is_object($data)) { $this->data = get_object_vars($data); @@ -101,10 +102,12 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (empty($this->name)) { $this->name = basename(str_replace('\\', '/', get_class($this))); } - // 获取字段类型信息并缓存 - $this->fieldType = self::db()->getTableInfo('', 'type'); - $this->initialize(); - $this->relation = new Relation($this); + if ($init) { + // 获取字段类型信息并缓存 + $this->fieldType = self::db()->getTableInfo('', 'type'); + $this->initialize(); + $this->relation = new Relation($this); + } } /** @@ -256,7 +259,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (!empty($data)) { // 数据对象赋值 foreach ($data as $key => $value) { - $this->__set($key, $value, $data); + $this->__set($key, $value); } if (!empty($where)) { $this->isUpdate = true; @@ -869,7 +872,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $model = get_called_class(); if (!isset(self::$links[$model])) { - $class = new static; + $class = new static([], false); self::$links[$model] = Db::connect($class->connection); self::$instance[$model] = $class; } else { @@ -914,10 +917,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @access public * @param string $name 名称 * @param mixed $value 值 - * @param array $data 数据信息 * @return void */ - public function __set($name, $value, $data = []) + public function __set($name, $value) { if (is_null($value) && in_array($name, $this->autoTimeField)) { // 自动写入的时间戳字段 @@ -944,7 +946,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 检测修改器 $method = 'set' . Loader::parseName($name, 1) . 'Attr'; if (method_exists($this, $method)) { - $value = $this->$method($value, array_merge($data, $this->data)); + $value = $this->$method($value, $this->data); } elseif (isset($this->type[$name])) { // 类型转换 $type = $this->type[$name]; From c8256382524aa342632e1d568ea5c3a7b348d265 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 13 May 2016 22:24:24 +0800 Subject: [PATCH 022/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3File=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/File.php b/library/think/File.php index 6994d534..89c7b248 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -81,7 +81,7 @@ class File extends SplFileObject return false; } - return new SplFileInfo($path . $savename); + return new \SplFileInfo($path . $savename); } /** From b925150d02289eecfd0fa9d1922b876700d6cec6 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 13 May 2016 23:04:56 +0800 Subject: [PATCH 023/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BOracle=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/connector/Oracle.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/library/think/db/connector/Oracle.php b/library/think/db/connector/Oracle.php index ab35d7bc..19954ecc 100644 --- a/library/think/db/connector/Oracle.php +++ b/library/think/db/connector/Oracle.php @@ -21,8 +21,6 @@ use think\db\Connection; class Oracle extends Connection { - private $table = ''; - /** * 解析pdo连接的dsn信息 * @access protected @@ -67,8 +65,8 @@ class Oracle extends Connection } $flag = false; if (preg_match("/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i", $sql, $match)) { - $this->table = Config::get("db_sequence_prefix") . str_ireplace(Config::get("database.prefix"), "", $match[2]); - $flag = (boolean) $this->query("SELECT * FROM all_sequences WHERE sequence_name='" . strtoupper($this->table) . "'"); + $table = Config::get("db_sequence_prefix") . str_ireplace(Config::get("database.prefix"), "", $match[2]); + $flag = (boolean) $this->query("SELECT * FROM all_sequences WHERE sequence_name='" . strtoupper($table) . "'"); } //释放前次的查询结果 if (!empty($this->PDOStatement)) { From 00b17411b67e6619c1e4f62f87a4e7096146b756 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 14 May 2016 20:54:22 +0800 Subject: [PATCH 024/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 60 ++++++++++++++++++++------------------ library/think/db/Query.php | 2 +- 2 files changed, 32 insertions(+), 30 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 6a6b84ad..05c33cf6 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -90,7 +90,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * 架构函数 * @access public * @param array|object $data 数据 - * @param bool $init 是否需要初始化 + * @param bool $init 是否初始化 */ public function __construct($data = [], $init = true) { @@ -102,12 +102,26 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (empty($this->name)) { $this->name = basename(str_replace('\\', '/', get_class($this))); } + if ($init) { // 获取字段类型信息并缓存 - $this->fieldType = self::db()->getTableInfo('', 'type'); + $this->fieldType = self::db('info')->getTableInfo('', 'type'); $this->initialize(); + } + + } + + /** + * 获取关联模型实例 + * + * @return \think\model\Relation + */ + protected function relation() + { + if (is_null($this->relation)) { $this->relation = new Relation($this); } + return $this->relation; } /** @@ -224,7 +238,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function getPk($table = '') { if (empty($this->pk)) { - $this->pk = self::db()->getTableInfo($table, 'pk'); + $this->pk = self::db('info')->getTableInfo($table, 'pk'); } return $this->pk; } @@ -685,8 +699,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public static function has($relation, $operator = '>=', $count = 1, $id = '*') { $class = new static(); - $model = $class->$relation(); - $info = $class->getRelationInfo(); + $info = $class->$relation()->getRelationInfo(); $table = $info['model']::getTable(); return self::db()->alias('a') ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey']) @@ -704,8 +717,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public static function hasWhere($relation, $where = []) { $class = new static(); - $model = $class->$relation(); - $info = $class->getRelationInfo(); + $info = $class->$relation()->getRelationInfo(); $table = $info['model']::getTable(); if (is_array($where)) { foreach ($where as $key => $val) { @@ -749,24 +761,13 @@ abstract class Model implements \JsonSerializable, \ArrayAccess 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 string $name 关联信息 - * @return array|string|integer - */ - public function getRelationInfo($name = '') - { - return $this->relation->getRelationInfo($name); - } - /** * 预载入关联查询 返回数据集 * @access public @@ -776,7 +777,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function eagerlyResultSet($resultSet, $relation) { - return $this->relation->eagerlyResultSet($resultSet, $relation); + return $this->relation()->eagerlyResultSet($resultSet, $relation); } /** @@ -788,7 +789,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function eagerlyResult($result, $relation) { - return $this->relation->eagerlyResult($result, $relation); + return $this->relation()->eagerlyResult($result, $relation); } /** @@ -805,7 +806,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $model = $this->parseModel($model); $localKey = $localKey ?: $this->getPk(); $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; - return $this->relation->hasOne($model, $foreignKey, $localKey); + return $this->relation()->hasOne($model, $foreignKey, $localKey); } /** @@ -822,7 +823,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $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); + return $this->relation()->belongsTo($model, $foreignKey, $otherKey); } /** @@ -839,7 +840,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $model = $this->parseModel($model); $localKey = $localKey ?: $this->getPk(); $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; - return $this->relation->hasMany($model, $foreignKey, $localKey); + return $this->relation()->hasMany($model, $foreignKey, $localKey); } /** @@ -859,21 +860,22 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $table = $table ?: Db::name(Loader::parseName($this->name) . '_' . $name)->getTable(); $foreignKey = $foreignKey ?: $name . '_id'; $localKey = $localKey ?: Loader::parseName($this->name) . '_id'; - return $this->relation->belongsToMany($model, $table, $foreignKey, $localKey); + return $this->relation()->belongsToMany($model, $table, $foreignKey, $localKey); } /** * 初始化数据库对象 * @access public + * @param bool $new 是否采用新的数据库连接 * @return \think\db\Driver */ - public static function db() + public static function db($new = false) { $model = get_called_class(); - if (!isset(self::$links[$model])) { + if ($new || !isset(self::$links[$model])) { $class = new static([], false); - self::$links[$model] = Db::connect($class->connection); + self::$links[$model] = Db::connect($class->connection, $new); self::$instance[$model] = $class; } else { $class = self::$instance[$model]; @@ -1051,7 +1053,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } } elseif (is_null($value) && method_exists($this, $name)) { // 获取关联数据 - $value = $this->relation->getRelation($name); + $value = $this->relation()->getRelation($name); // 保存关联对象值 $this->data[$name] = $value; } diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 9df03d49..7218cbdc 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1077,7 +1077,7 @@ class Query /** @var Relation $model */ $model = $class->$relation(); - $info = $class->getRelationInfo(); + $info = $model->getRelationInfo(); if (in_array($info['type'], [Relation::HAS_ONE, Relation::BELONGS_TO])) { if (0 == $i) { $name = Loader::parseName(basename(str_replace('\\', '/', $currentModel))); From f78ba76767c94b9403578f59631adbfef737ff31 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Sun, 15 May 2016 10:14:17 +0800 Subject: [PATCH 025/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E5=A4=84=E7=90=86=E5=92=8C=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Console.php | 24 ++++++++--------- library/think/Error.php | 10 ++++--- library/think/exception/Handle.php | 14 ++++++++-- mode/console.php | 3 +-- mode/console/Error.php | 26 ------------------- .../thinkphp/library/think/exceptionTest.php | 7 ++--- 6 files changed, 36 insertions(+), 48 deletions(-) delete mode 100644 mode/console/Error.php diff --git a/library/think/Console.php b/library/think/Console.php index 24b85134..884d010a 100644 --- a/library/think/Console.php +++ b/library/think/Console.php @@ -16,7 +16,7 @@ use think\console\helper\Formatter as FormatterHelper; use think\console\helper\Process as ProcessHelper; use think\console\helper\Question as QuestionHelper; use think\console\helper\Set as HelperSet; -use think\console\Input; +use think\console\Input as ConsoleInput; use think\console\input\Argument as InputArgument; use think\console\input\Definition as InputDefinition; use think\console\input\Option as InputOption; @@ -74,7 +74,7 @@ class Console */ public function run() { - $input = new Input(); + $input = new ConsoleInput(); $output = new Output(); $this->configureIO($input, $output); @@ -112,11 +112,11 @@ class Console /** * 执行指令 - * @param Input $input + * @param ConsoleInput $input * @param Output $output * @return int */ - public function doRun(Input $input, Output $output) + public function doRun(ConsoleInput $input, Output $output) { if (true === $input->hasParameterOption(['--version', '-V'])) { $output->writeln($this->getLongVersion()); @@ -129,7 +129,7 @@ class Console if (true === $input->hasParameterOption(['--help', '-h'])) { if (!$name) { $name = 'help'; - $input = new Input(['help']); + $input = new ConsoleInput(['help']); } else { $this->wantHelps = true; } @@ -137,7 +137,7 @@ class Console if (!$name) { $name = $this->defaultCommand; - $input = new Input([$this->defaultCommand]); + $input = new ConsoleInput([$this->defaultCommand]); } $command = $this->find($name); @@ -640,10 +640,10 @@ class Console /** * 配置基于用户的参数和选项的输入和输出实例。 - * @param Input $input 输入实例 + * @param ConsoleInput $input 输入实例 * @param Output $output 输出实例 */ - protected function configureIO(Input $input, Output $output) + protected function configureIO(ConsoleInput $input, Output $output) { if (true === $input->hasParameterOption(['--ansi'])) { $output->setDecorated(true); @@ -683,22 +683,22 @@ class Console /** * 执行指令 * @param Command $command 指令实例 - * @param Input $input 输入实例 + * @param ConsoleInput $input 输入实例 * @param Output $output 输出实例 * @return int * @throws \Exception */ - protected function doRunCommand(Command $command, Input $input, Output $output) + protected function doRunCommand(Command $command, ConsoleInput $input, Output $output) { return $command->run($input, $output); } /** * 获取指令的基础名称 - * @param Input $input + * @param ConsoleInput $input * @return string */ - protected function getCommandName(Input $input) + protected function getCommandName(ConsoleInput $input) { return $input->getFirstArgument(); } diff --git a/library/think/Error.php b/library/think/Error.php index 26fa20c9..08b05b3b 100644 --- a/library/think/Error.php +++ b/library/think/Error.php @@ -14,6 +14,7 @@ namespace think; use think\exception\ErrorException; use think\exception\Handle; use think\exception\ThrowableError; +use think\console\Output as ConsoleOutput; class Error { @@ -35,7 +36,7 @@ class Error /** * Exception Handler - * @param \Exception $e + * @param \Exception|\Throwable $e */ public static function appException($e) { @@ -44,8 +45,11 @@ class Error } self::getExceptionHandler()->report($e); - - self::getExceptionHandler()->render($e)->send(); + if(IS_CLI){ + self::getExceptionHandler()->renderForConsole(new ConsoleOutput, $e); + }else{ + self::getExceptionHandler()->render($e)->send(); + } } /** diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index 890ef93e..a43122b1 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -13,6 +13,8 @@ namespace think\exception; use Exception; use think\Config; +use think\Console; +use think\console\Output; use think\Log; use think\Response; @@ -79,6 +81,15 @@ class Handle } } + /** + * @param $output + * @param Exception $e + */ + public function renderForConsole(Output $output, Exception $e) + { + (new Console)->renderException($e, $output); + } + /** * @param HttpException $e * @return \think\Response @@ -110,8 +121,7 @@ class Handle 'code' => $this->getCode($exception), 'source' => $this->getSourceCode($exception), 'datas' => $this->getExtendData($exception), - - 'tables' => [ + 'tables' => [ 'GET Data' => $_GET, 'POST Data' => $_POST, 'Files' => $_FILES, diff --git a/mode/console.php b/mode/console.php index 5f0c488e..1da52480 100644 --- a/mode/console.php +++ b/mode/console.php @@ -23,8 +23,7 @@ return [ ], // 别名定义 'alias' => [ - 'think\App' => MODE_PATH . 'console/App' . EXT, - 'think\Error' => MODE_PATH . 'console/Error' . EXT + 'think\App' => MODE_PATH . 'console/App' . EXT ], // 配置文件 'config' => THINK_PATH . 'convention' . EXT diff --git a/mode/console/Error.php b/mode/console/Error.php deleted file mode 100644 index a0537e10..00000000 --- a/mode/console/Error.php +++ /dev/null @@ -1,26 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace think; - -class Error -{ - /** - * 注册异常处理 - * @return void - */ - public static function register() - { - ini_set("display_errors","Off"); - //TODO - } - -} \ No newline at end of file diff --git a/tests/thinkphp/library/think/exceptionTest.php b/tests/thinkphp/library/think/exceptionTest.php index e6aa13f8..66957ce6 100644 --- a/tests/thinkphp/library/think/exceptionTest.php +++ b/tests/thinkphp/library/think/exceptionTest.php @@ -18,6 +18,7 @@ namespace tests\thinkphp\library\think; use ReflectionMethod; use think\Exception as ThinkException; +use think\exception\HttpException; class MyException extends ThinkException { @@ -29,9 +30,9 @@ class exceptionTest extends \PHPUnit_Framework_TestCase public function testGetHttpStatus() { try { - throw new ThinkException("Error Processing Request", 1); - } catch (ThinkException $e) { - $this->assertEquals(500, $e->getHttpStatus()); + throw new HttpException(404, "Error Processing Request"); + } catch (HttpException $e) { + $this->assertEquals(404, $e->getStatusCode()); } } From 19d5b1fee956689611e2f4b18e21cbce6a6d902b Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Sun, 15 May 2016 10:15:19 +0800 Subject: [PATCH 026/670] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Console.php | 47 +++++++++++++++++---------------------- library/think/Error.php | 13 ++++------- 2 files changed, 24 insertions(+), 36 deletions(-) diff --git a/library/think/Console.php b/library/think/Console.php index 884d010a..6e5ad424 100644 --- a/library/think/Console.php +++ b/library/think/Console.php @@ -38,7 +38,7 @@ class Console private $runningCommand; private $catchExceptions = true; - private $autoExit = true; + private $autoExit = true; private $definition; private $helperSet; private $terminalDimensions; @@ -90,7 +90,7 @@ class Console $exitCode = $e->getCode(); if (is_numeric($exitCode)) { - $exitCode = (int) $exitCode; + $exitCode = (int)$exitCode; if (0 === $exitCode) { $exitCode = 1; } @@ -112,8 +112,8 @@ class Console /** * 执行指令 - * @param ConsoleInput $input - * @param Output $output + * @param ConsoleInput $input + * @param Output $output * @return int */ public function doRun(ConsoleInput $input, Output $output) @@ -201,7 +201,7 @@ class Console */ public function setCatchExceptions($boolean) { - $this->catchExceptions = (bool) $boolean; + $this->catchExceptions = (bool)$boolean; } /** @@ -211,7 +211,7 @@ class Console */ public function setAutoExit($boolean) { - $this->autoExit = (bool) $boolean; + $this->autoExit = (bool)$boolean; } /** @@ -379,7 +379,7 @@ class Console $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]) . '[^:]*'; }, $namespace); - $namespaces = preg_grep('{^' . $expr . '}', $allNamespaces); + $namespaces = preg_grep('{^' . $expr . '}', $allNamespaces); if (empty($namespaces)) { $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace); @@ -417,7 +417,7 @@ class Console $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]) . '[^:]*'; }, $name); - $commands = preg_grep('{^' . $expr . '}', $allCommands); + $commands = preg_grep('{^' . $expr . '}', $allCommands); if (empty($commands) || count(preg_grep('{^' . $expr . '$}', $commands)) < 1) { if (false !== $pos = strrpos($name, ':')) { @@ -606,19 +606,19 @@ class Console if ('\\' === DS) { if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) { - return [(int) $matches[1], (int) $matches[2]]; + return [(int)$matches[1], (int)$matches[2]]; } if (preg_match('/^(\d+)x(\d+)$/', $this->getConsoleMode(), $matches)) { - return [(int) $matches[1], (int) $matches[2]]; + return [(int)$matches[1], (int)$matches[2]]; } } if ($sttyString = $this->getSttyColumns()) { if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) { - return [(int) $matches[2], (int) $matches[1]]; + return [(int)$matches[2], (int)$matches[1]]; } if (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) { - return [(int) $matches[2], (int) $matches[1]]; + return [(int)$matches[2], (int)$matches[1]]; } } @@ -640,8 +640,8 @@ class Console /** * 配置基于用户的参数和选项的输入和输出实例。 - * @param ConsoleInput $input 输入实例 - * @param Output $output 输出实例 + * @param ConsoleInput $input 输入实例 + * @param Output $output 输出实例 */ protected function configureIO(ConsoleInput $input, Output $output) { @@ -663,18 +663,11 @@ class Console if (true === $input->hasParameterOption(['--quiet', '-q'])) { $output->setVerbosity(Output::VERBOSITY_QUIET); } else { - if ($input->hasParameterOption('-vvv') || $input->hasParameterOption('--verbose=3') - || $input->getParameterOption('--verbose') === 3 - ) { + if ($input->hasParameterOption('-vvv') || $input->hasParameterOption('--verbose=3') || $input->getParameterOption('--verbose') === 3) { $output->setVerbosity(Output::VERBOSITY_DEBUG); - } elseif ($input->hasParameterOption('-vv') || $input->hasParameterOption('--verbose=2') - || $input->getParameterOption('--verbose') === 2 - ) { + } elseif ($input->hasParameterOption('-vv') || $input->hasParameterOption('--verbose=2') || $input->getParameterOption('--verbose') === 2) { $output->setVerbosity(Output::VERBOSITY_VERY_VERBOSE); - } elseif ($input->hasParameterOption('-v') || $input->hasParameterOption('--verbose=1') - || $input->hasParameterOption('--verbose') - || $input->getParameterOption('--verbose') - ) { + } elseif ($input->hasParameterOption('-v') || $input->hasParameterOption('--verbose=1') || $input->hasParameterOption('--verbose') || $input->getParameterOption('--verbose')) { $output->setVerbosity(Output::VERBOSITY_VERBOSE); } } @@ -682,9 +675,9 @@ class Console /** * 执行指令 - * @param Command $command 指令实例 - * @param ConsoleInput $input 输入实例 - * @param Output $output 输出实例 + * @param Command $command 指令实例 + * @param ConsoleInput $input 输入实例 + * @param Output $output 输出实例 * @return int * @throws \Exception */ diff --git a/library/think/Error.php b/library/think/Error.php index 08b05b3b..3807abcc 100644 --- a/library/think/Error.php +++ b/library/think/Error.php @@ -43,11 +43,11 @@ class Error if (!$e instanceof \Exception) { $e = new ThrowableError($e); } - + self::getExceptionHandler()->report($e); - if(IS_CLI){ + if (IS_CLI) { self::getExceptionHandler()->renderForConsole(new ConsoleOutput, $e); - }else{ + } else { self::getExceptionHandler()->render($e)->send(); } } @@ -77,12 +77,7 @@ class Error { if (!is_null($error = error_get_last()) && self::isFatal($error['type'])) { // 将错误信息托管至think\ErrorException - $exception = new ErrorException( - $error['type'], - $error['message'], - $error['file'], - $error['line'] - ); + $exception = new ErrorException($error['type'], $error['message'], $error['file'], $error['line']); self::appException($exception); } From cf6836b56d141c3345974f8d3c6ba738439c1c09 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Sun, 15 May 2016 10:37:37 +0800 Subject: [PATCH 027/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=88=86=E9=A1=B5?= =?UTF-8?q?=E7=B1=BB=E7=AE=80=E6=B4=81=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Paginator.php | 10 ++++--- library/think/paginator/Collection.php | 40 ++++++++++++++++---------- 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/library/think/Paginator.php b/library/think/Paginator.php index 4f1772ae..e891798f 100644 --- a/library/think/Paginator.php +++ b/library/think/Paginator.php @@ -53,12 +53,13 @@ abstract class Paginator $this->simple = $simple; $this->listRows = $listRows; - $this->items = PaginatorCollection::make($items, $this); - if ($simple) { + if (!$items instanceof Collection) { + $items = Collection::make($items); + } $this->currentPage = $this->setCurrentPage($currentPage); - $this->hasMore = count($this->items) > ($this->listRows); - $this->items = $this->items->slice(0, $this->listRows); + $this->hasMore = count($items) > ($this->listRows); + $items = $items->slice(0, $this->listRows); } else { $this->total = $total; $this->lastPage = (int)ceil($total / $listRows); @@ -66,6 +67,7 @@ abstract class Paginator $this->hasMore = $this->currentPage < $this->lastPage; } + $this->items = PaginatorCollection::make($items, $this); } public function items() diff --git a/library/think/paginator/Collection.php b/library/think/paginator/Collection.php index a7939a86..49bd59c0 100644 --- a/library/think/paginator/Collection.php +++ b/library/think/paginator/Collection.php @@ -32,9 +32,6 @@ class Collection extends \think\Collection public function __construct($items = [], Paginator $paginator = null) { - if (!$paginator instanceof Paginator) { - throw new \RuntimeException('Paginator Required!'); - } $this->paginator = $paginator; parent::__construct($items); } @@ -44,26 +41,39 @@ class Collection extends \think\Collection return new static($items, $paginator); } + public function setPaginator(Paginator $paginator) + { + $this->paginator = $paginator; + } + + public function getPaginator() + { + return $this->paginator; + } public function toArray() { - try { - $total = $this->total(); - } catch (Exception $e) { - $total = null; - } + 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() - ]; + return [ + 'total' => $total, + 'per_page' => $this->listRows(), + 'current_page' => $this->currentPage(), + 'data' => parent::toArray() + ]; + } else { + return parent::toArray(); + } } public function __call($method, $args) { - if (method_exists($this->paginator, $method)) { + if ($this->paginator && method_exists($this->paginator, $method)) { return call_user_func_array([$this->paginator, $method], $args); } else { throw new Exception(__CLASS__ . ':' . $method . ' method not exist'); From 891c1f99f29743064e9a73820076b153395c1933 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 16 May 2016 10:41:22 +0800 Subject: [PATCH 028/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=9A=84?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E7=B1=BB=E5=9E=8B=E5=8F=82=E6=95=B0=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=B0=8F=E5=86=99=E4=BC=A0=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/library/think/Route.php b/library/think/Route.php index b1e99c5d..b2481ff1 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -120,7 +120,7 @@ class Route self::resource($rule['__rest__']); unset($rule['__rest__']); } - + $type = strtoupper($type); foreach ($rule as $key => $val) { if (is_numeric($key)) { $key = array_shift($val); @@ -146,6 +146,7 @@ class Route $group = $group ?: self::$group; $option = $option ?: self::$option; + $type = strtoupper($type); if (strpos($type, '|')) { foreach (explode('|', $type) as $val) { self::rule($rule, $route, $val, $option, $pattern, $group); @@ -197,6 +198,7 @@ class Route $option = $name; $name = isset($option['name']) ? $option['name'] : ''; } + $type = strtoupper($type); if (!empty($name)) { if ($routes instanceof \Closure) { self::setGroup($name); From 199825ec32e221343c92d6653711d3d869acf917 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 16 May 2016 14:18:47 +0800 Subject: [PATCH 029/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BResponse=E7=B1=BB=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=89=A9=E5=B1=95=E4=B8=8D=E5=90=8C=E7=9A=84?= =?UTF-8?q?=E8=BE=93=E5=87=BA=E7=B1=BB=E5=9E=8B=20=E6=94=B9=E8=BF=9BModel?= =?UTF-8?q?=E7=B1=BB=20=E4=B8=8D=E5=90=8C=E7=9A=84=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E9=87=87=E7=94=A8=E4=B8=8D=E5=90=8C=E7=9A=84=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E5=AF=B9=E8=B1=A1=E5=AE=9E=E4=BE=8B=20=E4=BF=AE=E6=AD=A3Reques?= =?UTF-8?q?t=E7=B1=BB=E4=B8=80=E5=A4=84=E9=94=99=E8=AF=AF=20=E5=8A=A9?= =?UTF-8?q?=E6=89=8B=E5=87=BD=E6=95=B0view=E6=94=B9=E8=BF=9B=20=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E8=BF=94=E5=9B=9EResponse=E7=B1=BB=E5=AF=B9=E8=B1=A1?= =?UTF-8?q?=E5=AE=9E=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 27 ++- library/think/App.php | 5 +- library/think/Model.php | 53 ++-- library/think/Request.php | 3 +- library/think/Response.php | 227 ++++++++++++------ library/think/Validate.php | 2 +- library/think/controller/Rest.php | 2 +- library/think/db/Connection.php | 23 +- library/think/db/Query.php | 92 ++++--- library/think/exception/Handle.php | 15 +- library/think/response/Json.php | 36 +++ library/think/response/Jsonp.php | 39 +++ library/think/response/Redirect.php | 40 +++ library/traits/controller/Jump.php | 8 +- tests/thinkphp/library/think/responseTest.php | 60 +---- 15 files changed, 420 insertions(+), 212 deletions(-) create mode 100644 library/think/response/Json.php create mode 100644 library/think/response/Jsonp.php create mode 100644 library/think/response/Redirect.php diff --git a/helper.php b/helper.php index ed0cd711..8fe6851f 100644 --- a/helper.php +++ b/helper.php @@ -340,11 +340,14 @@ function trace($log = '[think]', $level = 'log') * 渲染模板输出 * @param string $template 模板文件 * @param array $vars 模板变量 - * @return string + * @param string $type 输出类型 + * @return \think\Response */ -function view($template = '', $vars = []) +function view($template = '', $vars = [], $type = 'html') { - return View::instance(Config::get('template'), Config::get('view_replace_str'))->fetch($template, $vars); + $data = View::instance(Config::get('template'), Config::get('view_replace_str'))->fetch($template, $vars); + $response = Response::create($type); + return $response->data($data); } /** @@ -371,10 +374,22 @@ function request() } /** - * 获取当前的Response对象实例 + * 创建Response对象实例 + * @param string $type 输出类型 + * @param array $options 参数 * @return \think\Response */ -function response() +function response($type = '', $options = []) { - return Response::instance(); + return Response::create($type, $options); +} + +/** + * 获取\think\response\Json对象实例 + * @param array $options 参数 + * @return \think\response\Json + */ +function json($options = []) +{ + return new \think\response\Json($options); } diff --git a/library/think/App.php b/library/think/App.php index e37d3f2b..965951e9 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -106,7 +106,7 @@ class App default: throw new Exception('dispatch type not support', 10008); } - } catch (HttpResponseException $exception){ + } catch (HttpResponseException $exception) { $data = $exception->getResponse(); } // 输出数据到客户端 @@ -116,8 +116,9 @@ class App } else { // 监听app_end APP_HOOK && Hook::listen('app_end', $data); + $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); // 自动响应输出 - return Response::instance()->send($data, '', Config::get('response_return')); + return Response::create($type)->send($data); } } } diff --git a/library/think/Model.php b/library/think/Model.php index 05c33cf6..af278982 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -28,8 +28,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 数据库对象池 private static $links = []; - // 对象实例 - private static $instance = []; // 数据库配置 protected $connection = []; // 当前模型名称 @@ -90,9 +88,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * 架构函数 * @access public * @param array|object $data 数据 - * @param bool $init 是否初始化 */ - public function __construct($data = [], $init = true) + public function __construct($data = []) { if (is_object($data)) { $this->data = get_object_vars($data); @@ -103,12 +100,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->name = basename(str_replace('\\', '/', get_class($this))); } - if ($init) { - // 获取字段类型信息并缓存 - $this->fieldType = self::db('info')->getTableInfo('', 'type'); - $this->initialize(); - } - + $this->initialize(); } /** @@ -238,7 +230,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function getPk($table = '') { if (empty($this->pk)) { - $this->pk = self::db('info')->getTableInfo($table, 'pk'); + $this->pk = self::db()->getTableInfo($table, 'pk'); } return $this->pk; } @@ -866,32 +858,27 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 初始化数据库对象 * @access public - * @param bool $new 是否采用新的数据库连接 - * @return \think\db\Driver + * @return \think\db\Query */ - public static function db($new = false) + public static function db() { $model = get_called_class(); + if (!isset(self::$links[$model])) { + $class = new static(); - if ($new || !isset(self::$links[$model])) { - $class = new static([], false); - self::$links[$model] = Db::connect($class->connection, $new); - self::$instance[$model] = $class; - } else { - $class = self::$instance[$model]; + // 设置当前模型 确保查询返回模型对象 + self::$links[$model] = Db::connect($class->connection)->model($model); + + // 设置当前数据表和模型名 + if (!empty($class->table)) { + self::$links[$model]->table($class->table); + } else { + $name = !empty($class->name) ? $class->name : basename(str_replace('\\', '/', $model)); + self::$links[$model]->name($name); + } } - // 设置当前数据表和模型名 - if (!empty($class->table)) { - self::$links[$model]->table($class->table); - } else { - $name = !empty($class->name) ? $class->name : basename(str_replace('\\', '/', $model)); - self::$links[$model]->name($name); - } - - // 设置当前模型 确保查询返回模型对象 - self::$links[$model]->model($model); - // 返回当前数据库对象 + // 返回当前模型的数据库查询对象 return self::$links[$model]; } @@ -923,6 +910,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function __set($name, $value) { + if (is_null($this->fieldType)) { + // 获取字段类型信息并缓存 + $this->fieldType = self::db()->getTableInfo('', 'type'); + } if (is_null($value) && in_array($name, $this->autoTimeField)) { // 自动写入的时间戳字段 if (isset($this->type[$name])) { diff --git a/library/think/Request.php b/library/think/Request.php index 5a4f9da0..7d0b2290 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -63,10 +63,11 @@ class Request protected $file = []; protected $cookie = []; protected $server = []; + /** * @var array 资源类型 */ - protected $mime = [ + protected $mimeType = [ 'html' => 'text/html,application/xhtml+xml,*/*', 'xml' => 'application/xml,text/xml,application/x-xml', 'json' => 'application/json,text/x-json,application/jsonrequest,text/json', diff --git a/library/think/Response.php b/library/think/Response.php index e0943711..aa1dbbd5 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -11,21 +11,16 @@ namespace think; -use think\Config; -use think\Url; - class Response { - protected static $instance; + // 输出类型的实例化对象 + protected static $instance = []; // 输出数据的转换方法 - protected $transform = null; - + protected $transform; // 输出数据 - protected $data = ''; + protected $data; // 是否exit protected $isExit = false; - // 输出类型 - protected $type = ''; // contentType protected $contentType = [ 'json' => 'application/json', @@ -36,74 +31,83 @@ class Response 'text' => 'text/plain', ]; + // 输出参数 + protected $options = []; + // header参数 + protected $header = []; + /** * 架构函数 * @access public * @param array $options 参数 */ - public function __construct($type = '') + public function __construct($options = []) { - $this->type = $type; + $this->options = array_merge($this->options, $options); } /** - * 初始化 + * 创建一个response对象 * @access public * @param string $type 输出类型 + * @param array $options 参数 * @return \think\Response */ - public static function instance($type = '') + public static function create($type = '', $options = []) { - if (is_null(self::$instance)) { - self::$instance = new static($type); + $type = strtolower($type ?: (IS_AJAX ? 'json' : 'html')); + if (!isset(self::$instance[$type])) { + self::$instance[$type] = new static($options); + self::$instance[$type]->type($type, $options); } - return self::$instance; + return self::$instance[$type]; } /** * 发送数据到客户端 * @access public * @param mixed $data 数据 - * @param string $type 返回类型 - * @param bool $return 是否返回数据 * @return mixed */ - public function send($data = [], $type = '', $return = false) + public function send($data = []) { - if ('' == $type) { - $type = $this->type ?: (IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type')); - } - $type = strtolower($type); $data = $data ?: $this->data; - if (!headers_sent() && isset($this->contentType[$type])) { - header('Content-Type:' . $this->contentType[$type] . '; charset=utf-8'); - } - if (is_callable($this->transform)) { $data = call_user_func_array($this->transform, [$data]); - } else { - switch ($type) { - case 'json': - // 返回JSON数据格式到客户端 包含状态信息 - $data = json_encode($data, JSON_UNESCAPED_UNICODE); - break; - case 'jsonp': - // 返回JSON数据格式到客户端 包含状态信息 - $handler = !empty($_GET[Config::get('var_jsonp_handler')]) ? $_GET[Config::get('var_jsonp_handler')] : Config::get('default_jsonp_handler'); - $data = $handler . '(' . json_encode($data, JSON_UNESCAPED_UNICODE) . ');'; - break; + } + + // 处理输出数据 + $data = $this->output($data); + // 发送头部信息 + if (!headers_sent() && !empty($this->header)) { + // 发送状态码 + if (isset($this->header['status'])) { + http_response_code($this->header['status']); + unset($this->header['status']); + } + + foreach ($this->header as $name => $val) { + header($name . ':' . $val); } } - - APP_HOOK && Hook::listen('return_data', $data); - - if ($return) { + echo $data; + if ($this->isExit) { + exit; + } else { return $data; } + } - echo $data; - $this->isExit() && exit(); + /** + * 处理数据 + * @access protected + * @param mixed $data 要处理的数据 + * @return mixed + */ + protected function output($data) + { + return $data; } /** @@ -118,6 +122,18 @@ class Response return $this; } + /** + * 输出的参数 + * @access public + * @param mixed $options 输出参数 + * @return $this + */ + public function options($options = []) + { + $this->options = array_merge($this->options, $options); + return $this; + } + /** * 输出数据设置 * @access public @@ -134,12 +150,20 @@ class Response * 输出类型设置 * @access public * @param string $type 输出内容的格式类型 + * @param array $options 参数 * @return $this */ - public function type($type) + public function type($type, $options = []) { - $this->type = $type; - return $this; + $type = strtolower($type); + if (!isset(self::$instance[$type])) { + $class = '\\think\\response\\' . ucfirst($type); + self::$instance[$type] = class_exists($class) ? new $class($options) : $this; + } + if (isset($this->contentType[$type])) { + self::$instance[$type]->contentType($this->contentType[$type]); + } + return self::$instance[$type]; } /** @@ -148,11 +172,8 @@ class Response * @param bool $exit 是否退出 * @return $this */ - public function isExit($exit = null) + public function isExit($exit) { - if (is_null($exit)) { - return $this->isExit; - } $this->isExit = (boolean) $exit; return $this; } @@ -165,7 +186,7 @@ class Response * @param string $msg 提示信息 * @return mixed */ - public function result($data, $code = 0, $msg = '', $type = '') + public function result($data, $code = 0, $msg = '') { $result = [ 'code' => $code, @@ -173,26 +194,7 @@ class Response 'time' => NOW_TIME, 'data' => $data, ]; - $this->type = $type; - return $result; - } - - /** - * URL重定向 - * @access public - * @param string $url 跳转的URL表达式 - * @param array|int $params 其它URL参数或http code - * @return void - */ - public function redirect($url, $params = []) - { - $http_response_code = 301; - if (is_int($params) && in_array($params, [301, 302])) { - $http_response_code = $params; - $params = []; - } - $url = preg_match('/^(https?:|\/)/', $url) ? $url : Url::build($url, $params); - header('Location: ' . $url, true, $http_response_code); + return $this->data($result); } /** @@ -204,7 +206,18 @@ class Response */ public function header($name, $value) { - header($name . ':' . $value); + $this->header[$name] = $value; + return $this; + } + + /** + * 发送HTTP Location + * @param string $url Location地址 + * @return $this + */ + public function location($url) + { + $this->header['Location'] = $url; return $this; } @@ -215,7 +228,73 @@ class Response */ public function code($code) { - http_response_code($code); + $this->header['status'] = $code; return $this; } + + /** + * LastModified + * @param string $time + * @return $this + */ + public function lastModified($time) + { + $this->header['Last-Modified'] = $time; + return $this; + } + + /** + * Expires + * @param string $time + * @return $this + */ + public function expires($time) + { + $this->header['Expires'] = $time; + return $this; + } + + /** + * ETag + * @param string $etag + * @return $this + */ + public function eTag($etag) + { + $this->header['etag'] = $etag; + return $this; + } + + /** + * 页面缓存控制 + * @param string $cache 状态码 + * @return $this + */ + public function cacheControl($cache) + { + $this->header['Cache-control'] = $cache; + return $this; + } + + /** + * 页面输出类型 + * @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 头部名称 + * @return mixed + */ + public function getHeader($name = '') + { + return !empty($name) ? $this->header[$name] : $this->header; + } } diff --git a/library/think/Validate.php b/library/think/Validate.php index 5ff0929d..69b1778d 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -335,7 +335,7 @@ class Validate } // 如果不是require 有数据才会行验证 - if (0 === strpos($info, 'require') || !empty($value)) { + if (0 === strpos($info, 'require') || (!is_null($value) && '' !== $value)) { // 验证类型 $callback = isset(self::$type[$type]) ? self::$type[$type] : [$this, $type]; // 验证数据 diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index 1608ff94..c7be9b07 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -92,7 +92,7 @@ abstract class Rest */ protected function response($data, $type = '', $code = 200) { - return Response::instance()->data($data)->type($type)->code($code); + return Response::create($type)->data($data)->code($code); } /** diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 14ce32bc..71d84f3a 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -61,7 +61,8 @@ abstract class Connection protected $attrCase = PDO::CASE_LOWER; // 监听回调 protected static $event = []; - + // 查询对象 + protected $query = []; // 数据库连接参数配置 protected $config = [ // 数据库类型 @@ -119,7 +120,20 @@ abstract class Connection if (!empty($config)) { $this->config = array_merge($this->config, $config); } - $this->query = new Query($this); + } + + /** + * 创建指定模型的查询对象 + * @access public + * @param string $model 模型类名称 + * @return \think\Query + */ + public function model($model) + { + if (!isset($this->query[$model])) { + $this->query[$model] = new Query($this, $model); + } + return $this->query[$model]; } /** @@ -131,7 +145,10 @@ abstract class Connection */ public function __call($method, $args) { - return call_user_func_array([$this->query, $method], $args); + if (!isset($this->query['database'])) { + $this->query['database'] = new Query($this); + } + return call_user_func_array([$this->query['database'], $method], $args); } /** diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 7218cbdc..c23b242c 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -29,7 +29,12 @@ class Query protected $connection; // 数据库驱动类型 protected $driver; - + // 当前模型类名称 + protected $model; + // 当前数据表名称(含前缀) + protected $table; + // 当前数据表名称(不含前缀) + protected $name; // 查询参数 protected $options = []; // 参数绑定 @@ -41,10 +46,11 @@ class Query * @param object|string $connection 数据库对象实例 * @throws Exception */ - public function __construct($connection = '') + public function __construct($connection = '', $model = '') { $this->connection = $connection ?: Db::connect([], true); $this->driver = $this->connection->getDriverName(); + $this->model = $model; } /** @@ -73,6 +79,39 @@ class Query } } + /** + * 执行查询 返回数据集 + * @access public + * @param string $sql sql指令 + * @param array $bind 参数绑定 + * @param boolean $fetch 不执行只是获取SQL + * @param boolean $master 是否在主服务器读操作 + * @param bool|string $class 指定返回的数据集对象 + * @return mixed + * @throws DbBindParamException + * @throws PDOException + */ + public function query($sql, $bind = [], $fetch = false, $master = false, $class = false) + { + return $this->connection->query($sql, $bind, $fetch, $master, $class); + } + + /** + * 执行语句 + * @access public + * @param string $sql sql指令 + * @param array $bind 参数绑定 + * @param boolean $fetch 不执行只是获取SQL + * @param boolean $getLastInsID 是否获取自增ID + * @return int + * @throws DbBindParamException + * @throws PDOException + */ + public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false) + { + return $this->connection->execute($sql, $bind, $fetch, $getLastInsID); + } + /** * 获取当前的builder实例对象 * @access protected @@ -677,7 +716,7 @@ class Query */ public function table($table) { - $this->options['table'] = $table; + $this->table = $table; return $this; } @@ -898,18 +937,6 @@ class Query return $this; } - /** - * 指定当前模型 - * @access public - * @param string $model 模型类名称 - * @return $this - */ - public function model($model) - { - $this->options['model'] = $model; - return $this; - } - /** * 设置当前name * @access public @@ -918,7 +945,7 @@ class Query */ public function name($name) { - $this->options['name'] = $name; + $this->name = $name; return $this; } @@ -929,13 +956,13 @@ class Query */ public function getTable() { - if (empty($this->options['table'])) { + if (empty($this->table)) { $tableName = $this->connection->getConfig('prefix'); - if (isset($this->options['name'])) { - $tableName .= Loader::parseName($this->options['name']); + if (isset($this->name)) { + $tableName .= Loader::parseName($this->name); } } else { - $tableName = $this->options['table']; + $tableName = $this->table; } return $tableName; } @@ -1059,7 +1086,7 @@ class Query } $i = 0; - $currentModel = $this->options['model']; + $currentModel = $this->model; /** @var Model $class */ $class = new $currentModel; @@ -1181,7 +1208,7 @@ class Query // 生成SQL语句 $sql = $this->builder()->insert($data, $options, $replace); // 执行操作 - return $this->connection->execute($sql, $this->getBind(), $options['fetch_sql'], $getLastInsID); + return $this->execute($sql, $this->getBind(), $options['fetch_sql'], $getLastInsID); } /** @@ -1212,7 +1239,7 @@ class Query // 生成SQL语句 $sql = $this->builder()->insertAll($dataSet, $options); // 执行操作 - return $this->connection->execute($sql, $this->getBind(), $options['fetch_sql']); + return $this->execute($sql, $this->getBind(), $options['fetch_sql']); } /** @@ -1230,7 +1257,7 @@ class Query // 生成SQL语句 $sql = $this->builder()->selectInsert($fields, $table, $options); // 执行操作 - return $this->connection->execute($sql, $this->getBind(), $options['fetch_sql']); + return $this->execute($sql, $this->getBind(), $options['fetch_sql']); } /** @@ -1275,7 +1302,7 @@ class Query return 0; } // 执行操作 - return $this->connection->execute($sql, $this->getBind(), $options['fetch_sql']); + return $this->execute($sql, $this->getBind(), $options['fetch_sql']); } /** @@ -1316,7 +1343,7 @@ class Query // 生成查询SQL $sql = $this->builder()->select($options); // 执行查询操作 - $resultSet = $this->connection->query($sql, $this->getBind(), $options['fetch_sql'], $options['master'], $options['fetch_class']); + $resultSet = $this->query($sql, $this->getBind(), $options['fetch_sql'], $options['master'], $options['fetch_class']); if (is_string($resultSet)) { // 返回SQL @@ -1337,9 +1364,9 @@ class Query if ($resultSet) { // 数据列表读取后的处理 - if (!empty($options['model'])) { + if (!empty($this->model)) { // 生成模型对象 - $model = $options['model']; + $model = $this->model; foreach ($resultSet as $key => $result) { /** @var Model $result */ $result = new $model($result); @@ -1397,7 +1424,7 @@ class Query // 生成查询SQL $sql = $this->builder()->select($options); // 执行查询 - $result = $this->connection->query($sql, $this->getBind(), $options['fetch_sql'], $options['master'], $options['fetch_class']); + $result = $this->query($sql, $this->getBind(), $options['fetch_sql'], $options['master'], $options['fetch_class']); if (is_string($result)) { // 返回SQL @@ -1418,9 +1445,10 @@ class Query // 数据处理 if (!empty($result[0])) { $data = $result[0]; - if (!empty($options['model'])) { + if (!empty($this->model)) { // 返回模型对象 - $data = new $options['model']($data); + $model = $this->model; + $data = new $model($data); $data->isUpdate(true, isset($options['where']['AND']) ? $options['where']['AND'] : null); // 关联查询 if (!empty($options['relation'])) { @@ -1517,7 +1545,7 @@ class Query // 生成删除SQL语句 $sql = $this->builder()->delete($options); // 执行操作 - return $this->connection->execute($sql, $this->getBind(), $options['fetch_sql']); + return $this->execute($sql, $this->getBind(), $options['fetch_sql']); } /** diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index a43122b1..a319f9c8 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -22,7 +22,7 @@ class Handle { protected $ignoreReport = [ - '\\think\\exception\\HttpException' + '\\think\\exception\\HttpException', ]; /** @@ -40,15 +40,15 @@ class Handle 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'message' => $exception->getMessage(), - 'code' => $this->getCode($exception) + 'code' => $this->getCode($exception), ]; - $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; + $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; } else { $data = [ 'code' => $exception->getCode(), 'message' => $exception->getMessage(), ]; - $log = "[{$data['code']}]{$data['message']}"; + $log = "[{$data['code']}]{$data['message']}"; } Log::record($log, 'error'); @@ -130,7 +130,7 @@ class Handle 'Server/Request Data' => $_SERVER, 'Environment Variables' => $_ENV, 'ThinkPHP Constants' => $this->getConst(), - ] + ], ]; } else { // 部署模式仅显示 Code 和 Message @@ -151,7 +151,7 @@ class Handle // 获取并清空缓存 $content = ob_get_clean(); - $response = Response::instance()->data($content); + $response = Response::create('html')->data($content); if ($exception instanceof HttpException) { $statusCode = $exception->getStatusCode(); @@ -205,7 +205,6 @@ class Handle return $source; } - /** * 获取异常扩展信息 * 用于非调试模式html返回类型显示 @@ -229,4 +228,4 @@ class Handle { return get_defined_constants(true)['user']; } -} \ No newline at end of file +} diff --git a/library/think/response/Json.php b/library/think/response/Json.php new file mode 100644 index 00000000..963221bc --- /dev/null +++ b/library/think/response/Json.php @@ -0,0 +1,36 @@ + +// +---------------------------------------------------------------------- + +namespace think\response; + +use think\Response; + +class Json extends Response +{ + // 输出参数 + protected $options = [ + 'json_encode_param' => JSON_UNESCAPED_UNICODE, + ]; + + /** + * 处理数据 + * @access protected + * @param mixed $data 要处理的数据 + * @return mixed + */ + protected function output($data) + { + // 返回JSON数据格式到客户端 包含状态信息 + $data = json_encode($data, $this->options['json_encode_param']); + return $data; + } + +} diff --git a/library/think/response/Jsonp.php b/library/think/response/Jsonp.php new file mode 100644 index 00000000..8bfc8907 --- /dev/null +++ b/library/think/response/Jsonp.php @@ -0,0 +1,39 @@ + +// +---------------------------------------------------------------------- + +namespace think\response; + +use think\Response; + +class Jsonp extends Response +{ + // 输出参数 + protected $options = [ + 'var_jsonp_handler' => 'callback', + 'default_jsonp_handler' => 'jsonpReturn', + 'json_encode_param' => JSON_UNESCAPED_UNICODE, + ]; + + /** + * 处理数据 + * @access protected + * @param mixed $data 要处理的数据 + * @return mixed + */ + protected function output($data) + { + // 返回JSON数据格式到客户端 包含状态信息 + $handler = !empty($_GET[$this->options['var_jsonp_handler']]) ? $_GET[$this->options['var_jsonp_handler']] : $this->options['default_jsonp_handler']; + $data = $handler . '(' . json_encode($data, $this->options['json_encode_param']) . ');'; + return $data; + } + +} diff --git a/library/think/response/Redirect.php b/library/think/response/Redirect.php new file mode 100644 index 00000000..2cb90745 --- /dev/null +++ b/library/think/response/Redirect.php @@ -0,0 +1,40 @@ + +// +---------------------------------------------------------------------- + +namespace think\response; + +use think\Response; +use think\Url; + +class Redirect extends Response +{ + + protected $options = [ + 'http_response_code' => 301, + 'http_url_params' => [], + ]; + + /** + * 处理数据 + * @access protected + * @param mixed $data 要处理的数据 + * @return mixed + */ + protected function output($data) + { + $this->isExit = true; + $url = preg_match('/^(https?:|\/)/', $data) ? $data : Url::build($data, $this->options['http_url_params']); + $this->header['Location'] = $url; + $this->header['status'] = $this->options['http_response_code']; + return; + } + +} diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index 8c2e4b38..d7c3b83f 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -50,7 +50,7 @@ trait Jump $result = View::instance(Config::get('template'), Config::get('view_replace_str')) ->fetch(Config::get('dispatch_success_tmpl'), $result); } - Response::instance()->send($result, $type); + return Response::create($type)->data($result); } /** @@ -83,7 +83,7 @@ trait Jump $result = View::instance(Config::get('template'), Config::get('view_replace_str')) ->fetch(Config::get('dispatch_error_tmpl'), $result); } - Response::instance()->send($result, $type); + return Response::create($type)->data($result); } /** @@ -97,7 +97,7 @@ trait Jump */ public function result($data, $code = 0, $msg = '', $type = '') { - return Response::instance()->result($data, $code, $msg, $type); + return Response::create($type)->result($data, $code, $msg); } /** @@ -109,7 +109,7 @@ trait Jump */ public function redirect($url, $params = []) { - Response::instance()->redirect($url, $params); + Response::create()->isExit(true)->redirect($url, $params); } } diff --git a/tests/thinkphp/library/think/responseTest.php b/tests/thinkphp/library/think/responseTest.php index 2bba1845..6aaee446 100644 --- a/tests/thinkphp/library/think/responseTest.php +++ b/tests/thinkphp/library/think/responseTest.php @@ -70,7 +70,7 @@ class responseTest extends \PHPUnit_Framework_TestCase { Config::set('default_ajax_return', $this->default_ajax_return); Config::set('default_return_type', $this->default_return_type); - Response::instance()->type(Config::get('default_return_type')); // 会影响其他测试 + Response::create(Config::get('default_return_type')); // 会影响其他测试 } /** @@ -83,16 +83,11 @@ class responseTest extends \PHPUnit_Framework_TestCase $dataArr["key"] = "value"; //$dataArr->key = "val"; - $response = Response::instance(); - $result = $response->send($dataArr, "", true); - $this->assertArrayHasKey("key", $result); - - $result = $response->send($dataArr, "json", true); + $response = Response::create(); + $result = $response->type('json')->send($dataArr); $this->assertEquals('{"key":"value"}', $result); - - $handler = "callback"; - $_GET[Config::get('var_jsonp_handler')] = $handler; - $result = $response->send($dataArr, "jsonp", true); + $_GET['callback'] = 'callback'; + $result = $response->type('jsonp', ['var_jsonp_handler' => 'callback'])->send($dataArr); $this->assertEquals('callback({"key":"value"});', $result); $response->transform(function () { @@ -100,7 +95,7 @@ class responseTest extends \PHPUnit_Framework_TestCase return "callbackreturndata"; }); - $result = $response->send($dataArr, "", true); + $result = $response->send($dataArr); $this->assertEquals("callbackreturndata", $result); $_GET[Config::get('var_jsonp_handler')] = ""; } @@ -111,13 +106,13 @@ class responseTest extends \PHPUnit_Framework_TestCase */ public function testtransform() { - $response = Response::instance(); + $response = Response::create(); $response->transform(function () { return "callbackreturndata"; }); $dataArr = []; - $result = $response->send($dataArr, "", true); + $result = $response->send($dataArr); $this->assertEquals("callbackreturndata", $result); $response->transform(null); @@ -130,7 +125,7 @@ class responseTest extends \PHPUnit_Framework_TestCase public function testType() { $type = "json"; - Response::instance()->type($type); + Response::create($type); } /** @@ -139,45 +134,12 @@ class responseTest extends \PHPUnit_Framework_TestCase */ public function testData() { - $data = "data"; - $response = Response::instance(); + $data = "data"; + $response = Response::create(); $response->data($data); $response->data(null); } - /** - * @covers think\Response::isExit - * @todo Implement testIsExit(). - */ - public function testIsExit() - { - $isExit = true; - $response = Response::instance(); - $response->isExit($isExit); - - $result = $response->isExit(); - $this->assertTrue($isExit, $result); - $response->isExit(false); - } - - /** - * @covers think\Response::result - * @todo Implement testResult(). - */ - public function testResult() - { - $data = "data"; - $code = "1001"; - $msg = "the msg"; - $type = "json"; - $result = Response::instance()->result($data, $code, $msg, $type); - - $this->assertEquals($code, $result["code"]); - $this->assertEquals($msg, $result["msg"]); - $this->assertEquals($data, $result["data"]); - $this->assertEquals($_SERVER['REQUEST_TIME'], $result["time"]); - } - /** * @#runInSeparateProcess * @covers think\Response::redirect From 30a6bd7e8ab4ff1fed7fece1879aabe44894880c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 16 May 2016 15:16:47 +0800 Subject: [PATCH 030/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BResponse=E7=B1=BB=20?= =?UTF-8?q?=E6=94=B9=E8=BF=9Bview=E5=8A=A9=E6=89=8B=E5=87=BD=E6=95=B0=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20think\response\Html=20=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 30 +++++++--- library/think/Response.php | 9 +++ library/think/View.php | 15 +++-- library/think/response/Html.php | 85 +++++++++++++++++++++++++++++ library/think/response/Redirect.php | 17 ++++-- library/traits/controller/Jump.php | 7 ++- 6 files changed, 141 insertions(+), 22 deletions(-) create mode 100644 library/think/response/Html.php diff --git a/helper.php b/helper.php index 8fe6851f..5756dc0f 100644 --- a/helper.php +++ b/helper.php @@ -340,14 +340,14 @@ function trace($log = '[think]', $level = 'log') * 渲染模板输出 * @param string $template 模板文件 * @param array $vars 模板变量 + * @param integer $code 状态码 * @param string $type 输出类型 * @return \think\Response */ -function view($template = '', $vars = [], $type = 'html') +function view($template = '', $vars = [], $code = 200) { - $data = View::instance(Config::get('template'), Config::get('view_replace_str'))->fetch($template, $vars); - $response = Response::create($type); - return $response->data($data); + $response = new \think\response\Html(); + return $response->data($template)->vars($vars)->code($code); } /** @@ -386,10 +386,26 @@ function response($type = '', $options = []) /** * 获取\think\response\Json对象实例 - * @param array $options 参数 + * @param mixed $data 返回的数据 + * @param integer $code 状态码 + * @param array $options 参数状 * @return \think\response\Json */ -function json($options = []) +function json($data = [], $code = 200, $options = []) { - return new \think\response\Json($options); + $response = new \think\response\Json($options); + return $response->data($data)->code($code); +} + +/** + * 获取\think\response\Redirect对象实例 + * @param mixed $url 重定向地址 支持Url::build方法的地址 + * @param integer $code 状态码 + * @param array $params 额外参数 + * @return \think\response\Redirect + */ +function redirect($url = [], $code = 200, $params = []) +{ + $response = new \think\response\Redirect(); + return $response->data($url)->code($code)->params($params); } diff --git a/library/think/Response.php b/library/think/Response.php index aa1dbbd5..d173603c 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -297,4 +297,13 @@ class Response { return !empty($name) ? $this->header[$name] : $this->header; } + + /** + * 获取数据 + * @return mixed + */ + public function getData() + { + return $this->data; + } } diff --git a/library/think/View.php b/library/think/View.php index 31ccd22d..2cd90226 100644 --- a/library/think/View.php +++ b/library/think/View.php @@ -95,12 +95,13 @@ class View * 解析和获取模板内容 用于输出 * @param string $template 模板文件名或者内容 * @param array $vars 模板输出变量 + * @param array $replace 替换内容 * @param array $config 模板参数 - * @param bool $renderContent 是否渲染内容 + * @param bool $renderContent 是否渲染内容 * @return string * @throws Exception */ - public function fetch($template = '', $vars = [], $config = [], $renderContent = false) + public function fetch($template = '', $vars = [], $replace = [], $config = [], $renderContent = false) { // 模板变量 $vars = array_merge($this->data, $vars); @@ -118,8 +119,9 @@ class View // 内容过滤标签 APP_HOOK && Hook::listen('view_filter', $content); // 允许用户自定义模板的字符串替换 - if (!empty($this->replace)) { - $content = strtr($content, $this->replace); + $replace = array_merge($this->replace, $replace); + if (!empty($replace)) { + $content = strtr($content, $replace); } return $content; } @@ -146,12 +148,13 @@ class View * @access public * @param string $content 内容 * @param array $vars 模板输出变量 + * @param array $replace 替换内容 * @param array $config 模板参数 * @return mixed */ - public function display($content, $vars = [], $config = []) + public function display($content, $vars = [], $replace = [], $config = []) { - return $this->fetch($content, $vars, $config, true); + return $this->fetch($content, $vars, $replace, $config, true); } /** diff --git a/library/think/response/Html.php b/library/think/response/Html.php new file mode 100644 index 00000000..a2dca3dd --- /dev/null +++ b/library/think/response/Html.php @@ -0,0 +1,85 @@ + +// +---------------------------------------------------------------------- + +namespace think\response; + +use think\Config; +use think\Response; +use think\View; + +class Html extends Response +{ + // 输出参数 + protected $options = []; + protected $vars = []; + protected $replace = []; + + /** + * 处理数据 + * @access protected + * @param mixed $data 要处理的数据 + * @return mixed + */ + protected function output($data) + { + // 返回JSON数据格式到客户端 包含状态信息 + return View::instance(Config::get('template'), Config::get('view_replace_str')) + ->fetch($data, $this->vars, $this->replace); + } + + /** + * 视图变量赋值 + * @access protected + * @param array $vars 模板变量 + * @return $this + */ + public function vars($vars = []) + { + $this->vars = $vars; + return $this; + } + + /** + * 模板变量赋值 + * @access public + * @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 替换内容 + * @return $this + */ + public function replace($content, $replace = '') + { + if (is_array($content)) { + $this->replace = array_merge($this->replace, $content); + } else { + $this->replace[$content] = $replace; + } + return $this; + } + +} diff --git a/library/think/response/Redirect.php b/library/think/response/Redirect.php index 2cb90745..87f7b842 100644 --- a/library/think/response/Redirect.php +++ b/library/think/response/Redirect.php @@ -17,10 +17,10 @@ use think\Url; class Redirect extends Response { - protected $options = [ - 'http_response_code' => 301, - 'http_url_params' => [], - ]; + protected $options = []; + + // URL参数 + protected $params = []; /** * 处理数据 @@ -31,10 +31,15 @@ class Redirect extends Response protected function output($data) { $this->isExit = true; - $url = preg_match('/^(https?:|\/)/', $data) ? $data : Url::build($data, $this->options['http_url_params']); + $url = preg_match('/^(https?:|\/)/', $data) ? $data : Url::build($data, $this->params); $this->header['Location'] = $url; - $this->header['status'] = $this->options['http_response_code']; + $this->header['status'] = isset($this->header['status']) ? $this->header['status'] : 301; return; } + public function params($params = []) + { + $this->params = $params; + return $this; + } } diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index d7c3b83f..01721673 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -104,12 +104,13 @@ trait Jump * URL重定向 * @access protected * @param string $url 跳转的URL表达式 - * @param array|int $params 其它URL参数或http code + * @param integer $code http code + * @param array $params 其它URL参数 * @return void */ - public function redirect($url, $params = []) + public function redirect($url, $code = 301, $params = []) { - Response::create()->isExit(true)->redirect($url, $params); + Response::create('redirect')->data($url)->code($code)->params($params); } } From a4a14b3bf154e69493a01dd71755c0e4dd04d23a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 16 May 2016 16:39:17 +0800 Subject: [PATCH 031/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Query=E7=B1=BB=20?= =?UTF-8?q?=E6=94=B9=E8=BF=9BResponse=E7=B1=BB=20=E6=94=B9=E8=BF=9B?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 2 +- library/think/Controller.php | 5 +-- library/think/Response.php | 58 +++++++++++++++++------------- library/think/db/Query.php | 10 ++++++ library/think/exception/Handle.php | 9 +---- library/think/response/Html.php | 29 ++++++++++++--- library/think/response/Json.php | 2 +- library/think/response/Jsonp.php | 1 + library/traits/controller/Jump.php | 2 +- 9 files changed, 76 insertions(+), 42 deletions(-) diff --git a/helper.php b/helper.php index 5756dc0f..1fccc242 100644 --- a/helper.php +++ b/helper.php @@ -347,7 +347,7 @@ function trace($log = '[think]', $level = 'log') function view($template = '', $vars = [], $code = 200) { $response = new \think\response\Html(); - return $response->data($template)->vars($vars)->code($code); + return $response->data($template)->render(true)->vars($vars)->code($code); } /** diff --git a/library/think/Controller.php b/library/think/Controller.php index c58360ea..ce5c0311 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -86,12 +86,13 @@ class Controller * @access public * @param string $template 模板文件名 * @param array $vars 模板输出变量 + * @param array $replace 模板替换 * @param array $config 模板参数 * @return mixed */ - public function fetch($template = '', $vars = [], $config = []) + public function fetch($template = '', $vars = [], $replace = [], $config = []) { - return $this->view->fetch($template, $vars, $config); + return $this->view->fetch($template, $vars, $replace, $config = []); } /** diff --git a/library/think/Response.php b/library/think/Response.php index d173603c..dec4f224 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -21,8 +21,10 @@ class Response protected $data; // 是否exit protected $isExit = false; - // contentType - protected $contentType = [ + // 当前的contentType + protected $contentType; + // 可用的输出类型 + protected static $contentTypes = [ 'json' => 'application/json', 'xml' => 'text/xml', 'html' => 'text/html', @@ -57,12 +59,36 @@ class Response { $type = strtolower($type ?: (IS_AJAX ? 'json' : 'html')); if (!isset(self::$instance[$type])) { - self::$instance[$type] = new static($options); - self::$instance[$type]->type($type, $options); + + $class = '\\think\\response\\' . ucfirst($type); + $response = class_exists($class) ? new $class($options) : new static($options); + + if (isset(self::$contentTypes[$type])) { + $response->contentType(self::$contentTypes[$type]); + } + + self::$instance[$type] = $response; } return self::$instance[$type]; } + /** + * 输出类型设置 + * @access public + * @param string $type 输出内容的格式类型 + * @param array $options 参数 + * @return $this + */ + public function type($type, $options = []) + { + $type = strtolower($type); + if (isset(self::$instance[$type])) { + return self::$instance[$type]; + } else { + return self::create($type, $options); + } + } + /** * 发送数据到客户端 * @access public @@ -73,6 +99,10 @@ class Response { $data = $data ?: $this->data; + if (isset($this->contentType)) { + $this->contentType($this->contentType); + } + if (is_callable($this->transform)) { $data = call_user_func_array($this->transform, [$data]); } @@ -146,26 +176,6 @@ class Response return $this; } - /** - * 输出类型设置 - * @access public - * @param string $type 输出内容的格式类型 - * @param array $options 参数 - * @return $this - */ - public function type($type, $options = []) - { - $type = strtolower($type); - if (!isset(self::$instance[$type])) { - $class = '\\think\\response\\' . ucfirst($type); - self::$instance[$type] = class_exists($class) ? new $class($options) : $this; - } - if (isset($this->contentType[$type])) { - self::$instance[$type]->contentType($this->contentType[$type]); - } - return self::$instance[$type]; - } - /** * 输出是否exit设置 * @access public diff --git a/library/think/db/Query.php b/library/think/db/Query.php index c23b242c..1c8e1cf7 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -112,6 +112,16 @@ class Query return $this->connection->execute($sql, $bind, $fetch, $getLastInsID); } + /** + * 获取最近插入的ID + * @access public + * @return string + */ + public function getLastInsID() + { + return $this->connection->getLastInsID(); + } + /** * 获取当前的builder实例对象 * @access protected diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index a319f9c8..371d8239 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -144,14 +144,7 @@ class Handle // 不显示详细错误信息 $data['message'] = Config::get('error_message'); } - ob_start(); - ob_implicit_flush(0); - extract($data); - include Config::get('exception_tmpl'); - // 获取并清空缓存 - $content = ob_get_clean(); - - $response = Response::create('html')->data($content); + $response = Response::create('html')->render(true)->data(Config::get('exception_tmpl'))->vars($data); if ($exception instanceof HttpException) { $statusCode = $exception->getStatusCode(); diff --git a/library/think/response/Html.php b/library/think/response/Html.php index a2dca3dd..8b0c90eb 100644 --- a/library/think/response/Html.php +++ b/library/think/response/Html.php @@ -18,9 +18,11 @@ use think\View; class Html extends Response { // 输出参数 - protected $options = []; - protected $vars = []; - protected $replace = []; + protected $options = []; + protected $vars = []; + protected $replace = []; + protected $contentType = 'text/html'; + protected $render = false; /** * 处理数据 @@ -31,8 +33,25 @@ class Html extends Response protected function output($data) { // 返回JSON数据格式到客户端 包含状态信息 - return View::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch($data, $this->vars, $this->replace); + if ($this->render) { + // 渲染模板输出 + return View::instance(Config::get('template'), Config::get('view_replace_str')) + ->fetch($data, $this->vars, $this->replace, [], false, false); + } else { + return $data; + } + } + + /** + * 是否需要进行视图渲染 + * @access protected + * @param bool $render 是否渲染 + * @return $this + */ + public function render($render = true) + { + $this->render = $render; + return $this; } /** diff --git a/library/think/response/Json.php b/library/think/response/Json.php index 963221bc..23b68ea6 100644 --- a/library/think/response/Json.php +++ b/library/think/response/Json.php @@ -19,7 +19,7 @@ class Json extends Response protected $options = [ 'json_encode_param' => JSON_UNESCAPED_UNICODE, ]; - + protected $contentType = 'application/json'; /** * 处理数据 * @access protected diff --git a/library/think/response/Jsonp.php b/library/think/response/Jsonp.php index 8bfc8907..e07efbf4 100644 --- a/library/think/response/Jsonp.php +++ b/library/think/response/Jsonp.php @@ -21,6 +21,7 @@ class Jsonp extends Response 'default_jsonp_handler' => 'jsonpReturn', 'json_encode_param' => JSON_UNESCAPED_UNICODE, ]; + protected $contentType = 'application/json'; /** * 处理数据 diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index 01721673..8cb072fc 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -110,7 +110,7 @@ trait Jump */ public function redirect($url, $code = 301, $params = []) { - Response::create('redirect')->data($url)->code($code)->params($params); + return Response::create('redirect')->data($url)->code($code)->params($params); } } From 882c3bff5a0e95bc5e8d594204e32110e5e2d488 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Mon, 16 May 2016 17:06:21 +0800 Subject: [PATCH 032/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/exception/Handle.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index 371d8239..a319f9c8 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -144,7 +144,14 @@ class Handle // 不显示详细错误信息 $data['message'] = Config::get('error_message'); } - $response = Response::create('html')->render(true)->data(Config::get('exception_tmpl'))->vars($data); + ob_start(); + ob_implicit_flush(0); + extract($data); + include Config::get('exception_tmpl'); + // 获取并清空缓存 + $content = ob_get_clean(); + + $response = Response::create('html')->data($content); if ($exception instanceof HttpException) { $statusCode = $exception->getStatusCode(); From 4870d743ace4dd4a392c3f01fd79ab057f161713 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Mon, 16 May 2016 17:11:35 +0800 Subject: [PATCH 033/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E7=9A=84=E4=B8=80=E5=A4=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tpl/think_exception.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tpl/think_exception.tpl b/tpl/think_exception.tpl index 8b7e1f3d..db69fb54 100644 --- a/tpl/think_exception.tpl +++ b/tpl/think_exception.tpl @@ -211,7 +211,7 @@ isset($value['class']) ? parse_class($value['class']) : '', isset($value['type']) ? $value['type'] : '', $value['function'], - parse_args($value['args']) + isset($value['args'])?parse_args($value['args']):'' ); } From c7c94258d08f31672e562a9882d363ff1e319068 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 16 May 2016 18:10:46 +0800 Subject: [PATCH 034/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BResponse=E7=B1=BB=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0think\response\View=E7=B1=BB=20=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E6=B8=B2=E6=9F=93=E6=A8=A1=E6=9D=BF=E5=93=8D=E5=BA=94?= =?UTF-8?q?=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 31 ++++++----- library/think/App.php | 16 +++++- library/think/Response.php | 53 ++++--------------- library/think/controller/Rest.php | 9 +++- library/think/exception/Handle.php | 2 +- library/think/response/Jsonp.php | 2 +- library/think/response/{Html.php => View.php} | 28 ++-------- library/traits/controller/Jump.php | 44 +++++++++++---- tests/thinkphp/library/think/responseTest.php | 50 ++--------------- 9 files changed, 92 insertions(+), 143 deletions(-) rename library/think/response/{Html.php => View.php} (75%) diff --git a/helper.php b/helper.php index 1fccc242..0c8e590b 100644 --- a/helper.php +++ b/helper.php @@ -336,20 +336,6 @@ function trace($log = '[think]', $level = 'log') } } -/** - * 渲染模板输出 - * @param string $template 模板文件 - * @param array $vars 模板变量 - * @param integer $code 状态码 - * @param string $type 输出类型 - * @return \think\Response - */ -function view($template = '', $vars = [], $code = 200) -{ - $response = new \think\response\Html(); - return $response->data($template)->render(true)->vars($vars)->code($code); -} - /** * 路由注册 * @param string $rule 路由规则 @@ -379,9 +365,22 @@ function request() * @param array $options 参数 * @return \think\Response */ -function response($type = '', $options = []) +function response($data = [], $type = '', $options = []) { - return Response::create($type, $options); + return new Response($data, $type, $options); +} + +/** + * 渲染模板输出 + * @param string $template 模板文件 + * @param array $vars 模板变量 + * @param integer $code 状态码 + * @return \think\response\View + */ +function view($template = '', $vars = [], $code = 200) +{ + $response = new \think\response\View(); + return $response->data($template)->vars($vars)->code($code); } /** diff --git a/library/think/App.php b/library/think/App.php index 965951e9..35184fb5 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -13,6 +13,8 @@ namespace think; use think\exception\HttpResponseException; use think\Response; +use think\response\Json; +use think\response\Jsonp; /** * App 应用管理 @@ -117,8 +119,20 @@ class App // 监听app_end APP_HOOK && Hook::listen('app_end', $data); $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); + switch ($type) { + case 'json': + $response = new Json($data); + break; + case 'jsonp': + $response = new Jsonp($data); + break; + case 'html': + default: + $response = new Response($data, $type); + break; + } // 自动响应输出 - return Response::create($type)->send($data); + return $response->send(); } } } diff --git a/library/think/Response.php b/library/think/Response.php index dec4f224..bb524ce7 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -19,12 +19,13 @@ class Response protected $transform; // 输出数据 protected $data; + protected $type; // 是否exit protected $isExit = false; // 当前的contentType protected $contentType; // 可用的输出类型 - protected static $contentTypes = [ + protected $contentTypes = [ 'json' => 'application/json', 'xml' => 'text/xml', 'html' => 'text/html', @@ -43,52 +44,18 @@ class Response * @access public * @param array $options 参数 */ - public function __construct($options = []) + public function __construct($data = [], $type = '', $options = []) { + $this->data = $data; + $this->type = strtolower($type ?: (IS_AJAX ? 'json' : 'html')); + + if (isset($this->contentTypes[$this->type])) { + $this->contentType($this->contentTypes[$this->type]); + } + $this->options = array_merge($this->options, $options); } - /** - * 创建一个response对象 - * @access public - * @param string $type 输出类型 - * @param array $options 参数 - * @return \think\Response - */ - public static function create($type = '', $options = []) - { - $type = strtolower($type ?: (IS_AJAX ? 'json' : 'html')); - if (!isset(self::$instance[$type])) { - - $class = '\\think\\response\\' . ucfirst($type); - $response = class_exists($class) ? new $class($options) : new static($options); - - if (isset(self::$contentTypes[$type])) { - $response->contentType(self::$contentTypes[$type]); - } - - self::$instance[$type] = $response; - } - return self::$instance[$type]; - } - - /** - * 输出类型设置 - * @access public - * @param string $type 输出内容的格式类型 - * @param array $options 参数 - * @return $this - */ - public function type($type, $options = []) - { - $type = strtolower($type); - if (isset(self::$instance[$type])) { - return self::$instance[$type]; - } else { - return self::create($type, $options); - } - } - /** * 发送数据到客户端 * @access public diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index c7be9b07..b08c6997 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -12,6 +12,7 @@ namespace think\controller; use think\Response; +use think\response\Json; abstract class Rest { @@ -90,9 +91,13 @@ abstract class Rest * @param integer $code HTTP状态 * @return void */ - protected function response($data, $type = '', $code = 200) + protected function response($data, $type = 'json', $code = 200) { - return Response::create($type)->data($data)->code($code); + if('json'==$type){ + return new Json($data)->code($code); + }else{ + return new Response($data,$type)->code($code); + } } /** diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index a319f9c8..8c9c3632 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -151,7 +151,7 @@ class Handle // 获取并清空缓存 $content = ob_get_clean(); - $response = Response::create('html')->data($content); + $response = new Response($content, 'html'); if ($exception instanceof HttpException) { $statusCode = $exception->getStatusCode(); diff --git a/library/think/response/Jsonp.php b/library/think/response/Jsonp.php index e07efbf4..85445c97 100644 --- a/library/think/response/Jsonp.php +++ b/library/think/response/Jsonp.php @@ -21,7 +21,7 @@ class Jsonp extends Response 'default_jsonp_handler' => 'jsonpReturn', 'json_encode_param' => JSON_UNESCAPED_UNICODE, ]; - protected $contentType = 'application/json'; + protected $contentType = 'application/javascript'; /** * 处理数据 diff --git a/library/think/response/Html.php b/library/think/response/View.php similarity index 75% rename from library/think/response/Html.php rename to library/think/response/View.php index 8b0c90eb..e92cd052 100644 --- a/library/think/response/Html.php +++ b/library/think/response/View.php @@ -13,16 +13,15 @@ namespace think\response; use think\Config; use think\Response; -use think\View; +use think\View as ViewTemplate; -class Html extends Response +class View extends Response { // 输出参数 protected $options = []; protected $vars = []; protected $replace = []; protected $contentType = 'text/html'; - protected $render = false; /** * 处理数据 @@ -32,26 +31,9 @@ class Html extends Response */ protected function output($data) { - // 返回JSON数据格式到客户端 包含状态信息 - if ($this->render) { - // 渲染模板输出 - return View::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch($data, $this->vars, $this->replace, [], false, false); - } else { - return $data; - } - } - - /** - * 是否需要进行视图渲染 - * @access protected - * @param bool $render 是否渲染 - * @return $this - */ - public function render($render = true) - { - $this->render = $render; - return $this; + // 渲染模板输出 + return ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) + ->fetch($data, $this->vars, $this->replace); } /** diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index 8cb072fc..51711892 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -15,8 +15,12 @@ namespace traits\controller; use think\Config; +use think\exception\HttpResponseException; use think\Response; -use think\View; +use think\response\Json; +use think\response\Jsonp; +use think\response\Redirect; +use think\View as ViewTemplate; trait Jump { @@ -46,11 +50,20 @@ trait Jump $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); - if ('html' == $type) { - $result = View::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch(Config::get('dispatch_success_tmpl'), $result); + switch ($type) { + case 'html': + $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) + ->fetch(Config::get('dispatch_success_tmpl'), $result); + $response = new Response($result, $type); + break; + case 'json': + $response = new Json($result); + break; + case 'jsonp': + $response = new Jsonp($result); + break; } - return Response::create($type)->data($result); + return $response; } /** @@ -79,11 +92,20 @@ trait Jump $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); - if ('html' == $type) { - $result = View::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch(Config::get('dispatch_error_tmpl'), $result); + switch ($type) { + case 'html': + $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) + ->fetch(Config::get('dispatch_error_tmpl'), $result); + $response = new Response($result, $type); + break; + case 'json': + $response = new Json($result); + break; + case 'jsonp': + $response = new Jsonp($result); + break; } - return Response::create($type)->data($result); + throw new HttpResponseException($response); } /** @@ -97,7 +119,7 @@ trait Jump */ public function result($data, $code = 0, $msg = '', $type = '') { - return Response::create($type)->result($data, $code, $msg); + return (new Response([], $type))->result($data, $code, $msg); } /** @@ -110,7 +132,7 @@ trait Jump */ public function redirect($url, $code = 301, $params = []) { - return Response::create('redirect')->data($url)->code($code)->params($params); + return (new Redirect($url))->code($code)->params($params); } } diff --git a/tests/thinkphp/library/think/responseTest.php b/tests/thinkphp/library/think/responseTest.php index 6aaee446..3154ea61 100644 --- a/tests/thinkphp/library/think/responseTest.php +++ b/tests/thinkphp/library/think/responseTest.php @@ -70,7 +70,6 @@ class responseTest extends \PHPUnit_Framework_TestCase { Config::set('default_ajax_return', $this->default_ajax_return); Config::set('default_return_type', $this->default_return_type); - Response::create(Config::get('default_return_type')); // 会影响其他测试 } /** @@ -83,63 +82,24 @@ class responseTest extends \PHPUnit_Framework_TestCase $dataArr["key"] = "value"; //$dataArr->key = "val"; - $response = Response::create(); - $result = $response->type('json')->send($dataArr); + $response = new \think\response\Json(); + $result = $response->send($dataArr); $this->assertEquals('{"key":"value"}', $result); $_GET['callback'] = 'callback'; - $result = $response->type('jsonp', ['var_jsonp_handler' => 'callback'])->send($dataArr); + $response = new \think\response\Jsonp(); + $result = $response->options(['var_jsonp_handler' => 'callback'])->send($dataArr); $this->assertEquals('callback({"key":"value"});', $result); + $response = new Response(); $response->transform(function () { return "callbackreturndata"; }); - $result = $response->send($dataArr); $this->assertEquals("callbackreturndata", $result); $_GET[Config::get('var_jsonp_handler')] = ""; } - /** - * @covers think\Response::transform - * @todo Implement testtransform(). - */ - public function testtransform() - { - $response = Response::create(); - $response->transform(function () { - - return "callbackreturndata"; - }); - $dataArr = []; - $result = $response->send($dataArr); - $this->assertEquals("callbackreturndata", $result); - - $response->transform(null); - } - - /** - * @covers think\Response::type - * @todo Implement testType(). - */ - public function testType() - { - $type = "json"; - Response::create($type); - } - - /** - * @covers think\Response::data - * @todo Implement testData(). - */ - public function testData() - { - $data = "data"; - $response = Response::create(); - $response->data($data); - $response->data(null); - } - /** * @#runInSeparateProcess * @covers think\Response::redirect From 9074c8a532dd8da1de5e53dbc16dd875d1680718 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 16 May 2016 22:08:06 +0800 Subject: [PATCH 035/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0think\response\Xml=20?= =?UTF-8?q?=E7=B1=BB=E5=92=8Cxml=E5=8A=A9=E6=89=8B=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 15 +++++- library/think/App.php | 20 ++----- library/think/response/Xml.php | 95 ++++++++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 16 deletions(-) create mode 100644 library/think/response/Xml.php diff --git a/helper.php b/helper.php index 0c8e590b..e57e6555 100644 --- a/helper.php +++ b/helper.php @@ -387,7 +387,7 @@ function view($template = '', $vars = [], $code = 200) * 获取\think\response\Json对象实例 * @param mixed $data 返回的数据 * @param integer $code 状态码 - * @param array $options 参数状 + * @param array $options 参数 * @return \think\response\Json */ function json($data = [], $code = 200, $options = []) @@ -396,6 +396,19 @@ function json($data = [], $code = 200, $options = []) return $response->data($data)->code($code); } +/** + * 获取\think\response\Xml对象实例 + * @param mixed $data 返回的数据 + * @param integer $code 状态码 + * @param array $options 参数 + * @return \think\response\Xml + */ +function xml($data = [], $code = 200, $options = []) +{ + $response = new \think\response\Xml($options); + return $response->data($data)->code($code); +} + /** * 获取\think\response\Redirect对象实例 * @param mixed $url 重定向地址 支持Url::build方法的地址 diff --git a/library/think/App.php b/library/think/App.php index 35184fb5..84d69872 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -13,8 +13,6 @@ namespace think; use think\exception\HttpResponseException; use think\Response; -use think\response\Json; -use think\response\Jsonp; /** * App 应用管理 @@ -119,20 +117,12 @@ class App // 监听app_end APP_HOOK && Hook::listen('app_end', $data); $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); - switch ($type) { - case 'json': - $response = new Json($data); - break; - case 'jsonp': - $response = new Jsonp($data); - break; - case 'html': - default: - $response = new Response($data, $type); - break; + if (in_array(strtolower($type), ['json', 'jsonp', 'xml'])) { + $class = '\\think\\response\\' . ucfirst($type); + } else { + $class = '\\think\\Response'; } - // 自动响应输出 - return $response->send(); + return (new $class($data, $type))->send(); } } } diff --git a/library/think/response/Xml.php b/library/think/response/Xml.php new file mode 100644 index 00000000..3a2c59bd --- /dev/null +++ b/library/think/response/Xml.php @@ -0,0 +1,95 @@ + +// +---------------------------------------------------------------------- + +namespace think\response; + +use think\Response; + +class Xml extends Response +{ + // 输出参数 + protected $options = [ + // 根节点名 + 'root_node' => 'think', + // 根节点属性 + 'root_attr' => '', + //数字索引的子节点名 + 'item_node' => 'item', + // 数字索引子节点key转换的属性名 + 'item_key' => 'id', + // 数据编码 + 'encoding' => 'utf-8', + ]; + + protected $contentType = 'text/xml'; + + /** + * 处理数据 + * @access protected + * @param mixed $data 要处理的数据 + * @return mixed + */ + protected function output($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 数据编码 + * @return string + */ + protected function xmlEncode($data, $root, $item, $attr, $id, $encoding) + { + if (is_array($attr)) { + $array = []; + foreach ($attr as $key => $value) { + $array[] = "{$key}=\"{$value}\""; + } + $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转换为的属性名 + * @return string + */ + protected function dataToXml($data, $item, $id) + { + $xml = $attr = ''; + foreach ($data as $key => $val) { + if (is_numeric($key)) { + $id && $attr = " {$id}=\"{$key}\""; + $key = $item; + } + $xml .= "<{$key}{$attr}>"; + $xml .= (is_array($val) || is_object($val)) ? $this->dataToXml($val, $item, $id) : $val; + $xml .= ""; + } + return $xml; + } +} From f13596e4f60cb12aa15b4c14b9973e822cc33f1f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 08:25:47 +0800 Subject: [PATCH 036/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0param=20has=20only=20except=E6=96=B9=E6=B3=95?= =?UTF-8?q?=20=E5=8E=BB=E6=8E=89=20get=20post=20delete=20put=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 149 +++++++++++++++++++++++--------------- 1 file changed, 90 insertions(+), 59 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 7d0b2290..a7ca0c98 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -56,10 +56,10 @@ class Request */ protected $dispatch = []; - protected $get = []; - protected $post = []; - protected $put = []; - protected $delete = []; + /** + * @var array 请求参数 + */ + protected $param = []; protected $file = []; protected $cookie = []; protected $server = []; @@ -154,20 +154,20 @@ class Request if (!isset($info['path'])) { $info['path'] = '/'; } - $options = []; - $options[strtolower($method)] = $params; - $queryString = ''; + $options = []; + $options['param'] = $params; + $queryString = ''; if (isset($info['query'])) { parse_str(html_entity_decode($info['query']), $query); - if (isset($options['get'])) { - $options['get'] = array_replace($query, $options['get']); - $queryString = http_build_query($query, '', '&'); + if (!empty($options['param'])) { + $options['param'] = array_replace($query, $options['param']); + $queryString = http_build_query($query, '', '&'); } else { - $options['get'] = $query; - $queryString = $info['query']; + $options['param'] = $query; + $queryString = $info['query']; } - } elseif (isset($options['get'])) { - $queryString = http_build_query($options['get'], '', '&'); + } elseif (isset($options['param'])) { + $queryString = http_build_query($options['param'], '', '&'); } $server['REQUEST_URI'] = $info['path'] . ('' !== $queryString ? '?' . $queryString : ''); $server['QUERY_STRING'] = $queryString; @@ -350,61 +350,92 @@ class Request */ public function param($name = '') { - $method = $this->method(); - return $this->$method($name); - } - - /** - * 当前请求的get参数 - * @access public - * @param string $name 变量名 - * @return mixed - */ - public function get($name = '') - { - return Input::data($this->get ?: $_GET, $name); - } - - /** - * 当前请求的post参数 - * @access public - * @param string $name 变量名 - * @return mixed - */ - public function post($name = '') - { - return Input::data($this->post ?: $_POST, $name); - } - - /** - * 当前请求的put参数 - * @access public - * @param string $name 变量名 - * @return mixed - */ - public function put($name = '') - { - static $_PUT = null; - if (is_null($_PUT)) { - parse_str(file_get_contents('php://input'), $_PUT); + if (empty($this->param)) { + $method = $this->method(); + // 自动获取请求变量 + switch ($method) { + case 'POST': + $vars = Input::post(); + break; + case 'PUT': + $vars = Input::put(); + break; + case 'DELETE': + $vars = Input::delete(); + break; + default: + $vars = []; + } + // 当前请求参数和URL地址中的参数合并 + $this->param = array_merge(Input::get(), $vars); + } + if ($name) { + return isset($this->param[$name]) ? $this->param[$name] : null; + } else { + return $this->param; } - return Input::data($this->put ?: $_PUT, $name); } /** - * 当前请求的delete参数 + * 是否存在某个请求参数 * @access public * @param string $name 变量名 + * @param bool $checkEmpty 是否检测空值 * @return mixed */ - public function delete($name = '') + public function has($name, $checkEmpty = false) { - static $_DELETE = null; - if (is_null($_DELETE)) { - parse_str(file_get_contents('php://input'), $_DELETE); - $_DELETE = array_merge($_DELETE, $_GET); + if (empty($this->param)) { + $param = $this->param(); + } else { + $param = $this->param; } - return Input::data($this->delete ?: $_DELETE, $name); + if (isset($this->param[$name])) { + return ($checkEmpty && '' === $this->param[$name]) ? false : true; + } else { + return false; + } + } + + /** + * 获取指定的参数 + * @access public + * @param string|array $name 变量名 + * @return mixed + */ + public function only($name) + { + if (is_string($name)) { + return $this->param($name); + } else { + foreach ($name as $key) { + $item[$key] = $this->param($name); + } + return $item; + } + } + + /** + * 排除指定参数获取 + * @access public + * @param string|array $name 变量名 + * @return mixed + */ + public function except($name) + { + $param = $this->param(); + if (is_string($name)) { + if (isset($param[$name])) { + unset($param[$name]); + } + } else { + foreach ($param as $key => $val) { + if (in_array($key, $name)) { + unset($param[$key]); + } + } + } + return $param; } /** From 7be184a7a56a1e65ed46bf236c2fe41b5920dcdc Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 08:44:07 +0800 Subject: [PATCH 037/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3rest=E6=8E=A7?= =?UTF-8?q?=E5=88=B6=E5=99=A8=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/controller/Rest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index b08c6997..3a759eea 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -94,9 +94,9 @@ abstract class Rest protected function response($data, $type = 'json', $code = 200) { if('json'==$type){ - return new Json($data)->code($code); + return (new Json($data))->code($code); }else{ - return new Response($data,$type)->code($code); + return (new Response($data,$type))->code($code); } } From d1f9ab38e269a65c72ca8b6468fe1f49e0c041ad Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 10:06:30 +0800 Subject: [PATCH 038/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3traits\controller\Jum?= =?UTF-8?q?p?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/traits/controller/Jump.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index 51711892..d318efbb 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -50,18 +50,18 @@ trait Jump $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); - switch ($type) { - case 'html': - $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch(Config::get('dispatch_success_tmpl'), $result); - $response = new Response($result, $type); - break; + switch (strtolower($type)) { case 'json': $response = new Json($result); break; case 'jsonp': $response = new Jsonp($result); break; + case 'html': + $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) + ->fetch(Config::get('dispatch_success_tmpl'), $result); + default: + $response = new Response($result, $type); } return $response; } @@ -92,18 +92,18 @@ trait Jump $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); - switch ($type) { - case 'html': - $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch(Config::get('dispatch_error_tmpl'), $result); - $response = new Response($result, $type); - break; + switch (strtolower($type)) { case 'json': $response = new Json($result); break; case 'jsonp': $response = new Jsonp($result); break; + case 'html': + $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) + ->fetch(Config::get('dispatch_error_tmpl'), $result); + default: + $response = new Response($result, $type); } throw new HttpResponseException($response); } From 5e22d69e13b9214f50ea0cac0798c1976e5c9bf8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 10:13:14 +0800 Subject: [PATCH 039/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E7=9A=84param=E6=96=B9=E6=B3=95=E5=A2=9E=E5=8A=A0=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E5=80=BC=E5=8F=82=E6=95=B0=20=E4=BC=98=E5=8C=96except?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index a7ca0c98..29c42e25 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -346,9 +346,10 @@ class Request * 当前请求的参数 * @access public * @param string $name 变量名 + * @param mixed $default 默认值 * @return mixed */ - public function param($name = '') + public function param($name = '', $default = null) { if (empty($this->param)) { $method = $this->method(); @@ -370,7 +371,7 @@ class Request $this->param = array_merge(Input::get(), $vars); } if ($name) { - return isset($this->param[$name]) ? $this->param[$name] : null; + return isset($this->param[$name]) ? $this->param[$name] : $default; } else { return $this->param; } @@ -429,8 +430,8 @@ class Request unset($param[$name]); } } else { - foreach ($param as $key => $val) { - if (in_array($key, $name)) { + foreach ($name as $key) { + if (isset($param[$key])) { unset($param[$key]); } } From df96d049b9dc1a3af15a519941fe38b9c8ddbe73 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 10:23:40 +0800 Subject: [PATCH 040/670] =?UTF-8?q?=E4=BC=98=E5=8C=96Request=E7=B1=BB?= =?UTF-8?q?=E7=9A=84only=E5=92=8Cexcept=E6=96=B9=E6=B3=95=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E5=AD=97=E7=AC=A6=E4=B8=B2=E4=BC=A0=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 29c42e25..4be21392 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -406,14 +406,17 @@ class Request */ public function only($name) { + $param = $this->param(); if (is_string($name)) { - return $this->param($name); - } else { - foreach ($name as $key) { - $item[$key] = $this->param($name); - } - return $item; + $name = explode(',', $name); } + $item = []; + foreach ($name as $key) { + if (isset($param[$key])) { + $item[$key] = $param[$key]; + } + } + return $item; } /** @@ -426,14 +429,11 @@ class Request { $param = $this->param(); if (is_string($name)) { - if (isset($param[$name])) { - unset($param[$name]); - } - } else { - foreach ($name as $key) { - if (isset($param[$key])) { - unset($param[$key]); - } + $name = explode(',', $name); + } + foreach ($name as $key) { + if (isset($param[$key])) { + unset($param[$key]); } } return $param; From 92d999b48469c894eca9b1c0d27c7543c9c72430 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 11:17:24 +0800 Subject: [PATCH 041/670] =?UTF-8?q?response=E7=B1=BB=E5=A2=9E=E5=8A=A0crea?= =?UTF-8?q?te=E6=96=B9=E6=B3=95=20=E6=94=B9=E8=BF=9Bthink\response\redirec?= =?UTF-8?q?t=E7=B1=BB=20=E6=94=B9=E8=BF=9B=E5=8A=A9=E6=89=8B=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E5=92=8Ctraits\controller\Jump?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 28 ++++++++++----- library/think/App.php | 7 +--- library/think/Response.php | 55 ++++++++++++++++++----------- library/think/controller/Rest.php | 7 +--- library/think/response/Redirect.php | 9 ++--- library/traits/controller/Jump.php | 43 +++++++--------------- 6 files changed, 73 insertions(+), 76 deletions(-) diff --git a/helper.php b/helper.php index e57e6555..6ce323db 100644 --- a/helper.php +++ b/helper.php @@ -361,13 +361,14 @@ function request() /** * 创建Response对象实例 + * @param mixed $data 输出数据 * @param string $type 输出类型 * @param array $options 参数 * @return \think\Response */ function response($data = [], $type = '', $options = []) { - return new Response($data, $type, $options); + return Response::create($data, $type, $options); } /** @@ -379,8 +380,7 @@ function response($data = [], $type = '', $options = []) */ function view($template = '', $vars = [], $code = 200) { - $response = new \think\response\View(); - return $response->data($template)->vars($vars)->code($code); + return Response::create($template, 'view')->vars($vars)->code($code); } /** @@ -392,8 +392,19 @@ function view($template = '', $vars = [], $code = 200) */ function json($data = [], $code = 200, $options = []) { - $response = new \think\response\Json($options); - return $response->data($data)->code($code); + return Response::create($data, 'json', $options)->code($code); +} + +/** + * 获取\think\response\Jsonp对象实例 + * @param mixed $data 返回的数据 + * @param integer $code 状态码 + * @param array $options 参数 + * @return \think\response\Jsonp + */ +function jsonp($data = [], $code = 200, $options = []) +{ + return Response::create($data, 'jsonp', $options)->code($code); } /** @@ -405,8 +416,7 @@ function json($data = [], $code = 200, $options = []) */ function xml($data = [], $code = 200, $options = []) { - $response = new \think\response\Xml($options); - return $response->data($data)->code($code); + return Response::create($data, 'xml', $options)->code($code); } /** @@ -418,6 +428,6 @@ function xml($data = [], $code = 200, $options = []) */ function redirect($url = [], $code = 200, $params = []) { - $response = new \think\response\Redirect(); - return $response->data($url)->code($code)->params($params); + $response = Response::create($url, 'redirect')->code($code)->params($params); + throw new HttpResponseException($response); } diff --git a/library/think/App.php b/library/think/App.php index 84d69872..e463c1d5 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -117,12 +117,7 @@ class App // 监听app_end APP_HOOK && Hook::listen('app_end', $data); $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); - if (in_array(strtolower($type), ['json', 'jsonp', 'xml'])) { - $class = '\\think\\response\\' . ucfirst($type); - } else { - $class = '\\think\\Response'; - } - return (new $class($data, $type))->send(); + return Response::create($data, $type)->send(); } } } diff --git a/library/think/Response.php b/library/think/Response.php index bb524ce7..7ed9dde5 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -20,8 +20,6 @@ class Response // 输出数据 protected $data; protected $type; - // 是否exit - protected $isExit = false; // 当前的contentType protected $contentType; // 可用的输出类型 @@ -42,7 +40,9 @@ class Response /** * 架构函数 * @access public - * @param array $options 参数 + * @param mixed $data 输出数据 + * @param string $type 输出类型 + * @param array $options 输出参数 */ public function __construct($data = [], $type = '', $options = []) { @@ -56,6 +56,28 @@ class Response $this->options = array_merge($this->options, $options); } + /** + * 创建Response对象 + * @access public + * @param mixed $data 输出数据 + * @param string $type 输出类型 + * @param array $options 输出参数 + */ + public static function create($data = [], $type = '', $options = []) + { + $type = strtolower($type ?: (IS_AJAX ? 'json' : 'html')); + if (!isset(self::$instance[$type])) { + $class = '\\think\response\\' . ucfirst($type); + if (class_exists($class)) { + $response = new $class($data, $type, $options); + } else { + $response = new static($data, $type, $options); + } + self::$instance[$type] = $response; + } + return self::$instance[$type]; + } + /** * 发送数据到客户端 * @access public @@ -89,11 +111,7 @@ class Response } } echo $data; - if ($this->isExit) { - exit; - } else { - return $data; - } + return $data; } /** @@ -143,18 +161,6 @@ class Response return $this; } - /** - * 输出是否exit设置 - * @access public - * @param bool $exit 是否退出 - * @return $this - */ - public function isExit($exit) - { - $this->isExit = (boolean) $exit; - return $this; - } - /** * 返回封装后的API数据到客户端 * @access public @@ -283,4 +289,13 @@ class Response { return $this->data; } + + /** + * 获取输出类型 + * @return string + */ + public function getType() + { + return $this->type; + } } diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index 3a759eea..0a614e4a 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -12,7 +12,6 @@ namespace think\controller; use think\Response; -use think\response\Json; abstract class Rest { @@ -93,11 +92,7 @@ abstract class Rest */ protected function response($data, $type = 'json', $code = 200) { - if('json'==$type){ - return (new Json($data))->code($code); - }else{ - return (new Response($data,$type))->code($code); - } + return Response::create($data, $type)->code($code); } /** diff --git a/library/think/response/Redirect.php b/library/think/response/Redirect.php index 87f7b842..4deac9e9 100644 --- a/library/think/response/Redirect.php +++ b/library/think/response/Redirect.php @@ -30,10 +30,11 @@ class Redirect extends Response */ protected function output($data) { - $this->isExit = true; - $url = preg_match('/^(https?:|\/)/', $data) ? $data : Url::build($data, $this->params); - $this->header['Location'] = $url; - $this->header['status'] = isset($this->header['status']) ? $this->header['status'] : 301; + $this->isExit = true; + $url = preg_match('/^(https?:|\/)/', $data) ? $data : Url::build($data, $this->params); + $this->header['Location'] = $url; + $this->header['status'] = isset($this->header['status']) ? $this->header['status'] : 301; + $this->header['Cache-control'] = 'no-cache,must-revalidate'; return; } diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index d318efbb..fb469423 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -17,8 +17,6 @@ namespace traits\controller; use think\Config; use think\exception\HttpResponseException; use think\Response; -use think\response\Json; -use think\response\Jsonp; use think\response\Redirect; use think\View as ViewTemplate; @@ -49,21 +47,11 @@ trait Jump ]; $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); - - switch (strtolower($type)) { - case 'json': - $response = new Json($result); - break; - case 'jsonp': - $response = new Jsonp($result); - break; - case 'html': - $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch(Config::get('dispatch_success_tmpl'), $result); - default: - $response = new Response($result, $type); + if ('html' == strtolower($type)) { + $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) + ->fetch(Config::get('dispatch_success_tmpl'), $result); } - return $response; + return Response::create($result, $type); } /** @@ -91,20 +79,11 @@ trait Jump ]; $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); - - switch (strtolower($type)) { - case 'json': - $response = new Json($result); - break; - case 'jsonp': - $response = new Jsonp($result); - break; - case 'html': - $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) - ->fetch(Config::get('dispatch_error_tmpl'), $result); - default: - $response = new Response($result, $type); + if ('html' == strtolower($type)) { + $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) + ->fetch(Config::get('dispatch_error_tmpl'), $result); } + $response = Response::create($result, $type); throw new HttpResponseException($response); } @@ -119,7 +98,7 @@ trait Jump */ public function result($data, $code = 0, $msg = '', $type = '') { - return (new Response([], $type))->result($data, $code, $msg); + return Response::create([], $type)->result($data, $code, $msg); } /** @@ -132,7 +111,9 @@ trait Jump */ public function redirect($url, $code = 301, $params = []) { - return (new Redirect($url))->code($code)->params($params); + $response = new Redirect($url); + $response->code($code)->params($params); + throw new HttpResponseException($response); } } From de18afa9e6b8fc1504a43f8865d981f7c5285753 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 11:43:03 +0800 Subject: [PATCH 042/670] =?UTF-8?q?=E5=8A=A9=E6=89=8B=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E6=94=B9=E8=BF=9B=20App=E7=B1=BB=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 3 +-- library/think/App.php | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/helper.php b/helper.php index 6ce323db..0c6dc504 100644 --- a/helper.php +++ b/helper.php @@ -428,6 +428,5 @@ function xml($data = [], $code = 200, $options = []) */ function redirect($url = [], $code = 200, $params = []) { - $response = Response::create($url, 'redirect')->code($code)->params($params); - throw new HttpResponseException($response); + return Response::create($url, 'redirect')->code($code)->params($params); } diff --git a/library/think/App.php b/library/think/App.php index e463c1d5..8f53688a 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -82,7 +82,7 @@ class App switch ($dispatch['type']) { case 'redirect': // 执行重定向跳转 - header('Location: ' . $dispatch['url'], true, $dispatch['status']); + $data = Response::create($dispatch['url'], 'redirect')->code($dispatch['status']); break; case 'module': // 模块/控制器/操作 From cbc0597470a296ab9509757663559efa3742a92a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 11:54:21 +0800 Subject: [PATCH 043/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Request=E7=B1=BB?= =?UTF-8?q?=E7=9A=84has=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 4be21392..ef0edbfc 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -59,10 +59,11 @@ class Request /** * @var array 请求参数 */ - protected $param = []; - protected $file = []; - protected $cookie = []; - protected $server = []; + protected $param = []; + protected $session = []; + protected $file = []; + protected $cookie = []; + protected $server = []; /** * @var array 资源类型 @@ -391,8 +392,8 @@ class Request } else { $param = $this->param; } - if (isset($this->param[$name])) { - return ($checkEmpty && '' === $this->param[$name]) ? false : true; + if (isset($param[$name])) { + return ($checkEmpty && '' === $param[$name]) ? false : true; } else { return false; } From 9d5728c67f72194047cb1eabd619255af583d095 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 12:11:45 +0800 Subject: [PATCH 044/670] =?UTF-8?q?=E4=BC=98=E5=8C=96Response=E7=B1=BB?= =?UTF-8?q?=E7=9A=84send=E6=96=B9=E6=B3=95=20=E6=94=B9=E8=BF=9Bapp=5Fend?= =?UTF-8?q?=E7=9A=84=E7=9B=91=E5=90=AC=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 7 ++++--- library/think/Response.php | 4 ++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 8f53688a..2760b88a 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -109,13 +109,14 @@ class App } catch (HttpResponseException $exception) { $data = $exception->getResponse(); } - // 输出数据到客户端 + + // 监听app_end + APP_HOOK && Hook::listen('app_end', isset($data) ? $data : ''); if (isset($data)) { + // 输出数据到客户端 if ($data instanceof Response) { return $data->send(); } else { - // 监听app_end - APP_HOOK && Hook::listen('app_end', $data); $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); return Response::create($data, $type)->send(); } diff --git a/library/think/Response.php b/library/think/Response.php index 7ed9dde5..a0f4a5d1 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -111,6 +111,10 @@ class Response } } echo $data; + if (function_exists('fastcgi_finish_request')) { + // 提高页面响应 + fastcgi_finish_request(); + } return $data; } From 132a02ba36b06f99b03b69a4952a60c20530e2d5 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Tue, 17 May 2016 12:17:28 +0800 Subject: [PATCH 045/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=AE=B0=E5=BF=86?= =?UTF-8?q?=E8=B7=B3=E8=BD=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 2 +- library/think/Session.php | 1 - library/think/response/Redirect.php | 24 ++++++++++++++++++++++-- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/helper.php b/helper.php index 0c6dc504..0a3206fd 100644 --- a/helper.php +++ b/helper.php @@ -426,7 +426,7 @@ function xml($data = [], $code = 200, $options = []) * @param array $params 额外参数 * @return \think\response\Redirect */ -function redirect($url = [], $code = 200, $params = []) +function redirect($url = [], $code = 302, $params = []) { return Response::create($url, 'redirect')->code($code)->params($params); } diff --git a/library/think/Session.php b/library/think/Session.php index 1889cef5..35de1bfa 100644 --- a/library/think/Session.php +++ b/library/think/Session.php @@ -206,7 +206,6 @@ class Session * @param string $name session名称 * @param string|null $prefix * @return bool - * @internal param mixed $value session值 */ public static function has($name, $prefix = null) { diff --git a/library/think/response/Redirect.php b/library/think/response/Redirect.php index 4deac9e9..c60c007f 100644 --- a/library/think/response/Redirect.php +++ b/library/think/response/Redirect.php @@ -11,7 +11,9 @@ namespace think\response; +use think\Request; use think\Response; +use think\Session; use think\Url; class Redirect extends Response @@ -30,10 +32,9 @@ class Redirect extends Response */ protected function output($data) { - $this->isExit = true; $url = preg_match('/^(https?:|\/)/', $data) ? $data : Url::build($data, $this->params); $this->header['Location'] = $url; - $this->header['status'] = isset($this->header['status']) ? $this->header['status'] : 301; + $this->header['status'] = isset($this->header['status']) ? $this->header['status'] : 302; $this->header['Cache-control'] = 'no-cache,must-revalidate'; return; } @@ -43,4 +44,23 @@ class Redirect extends Response $this->params = $params; return $this; } + + /** + * 记住当前url后跳转 + */ + public function remember() + { + Session::set('redirect_url', Request::instance()->url()); + } + + /** + * 跳转到上次记住的url + */ + public function restore() + { + if (Session::has('redirect_url')) { + $this->data = Session::get('redirect_url'); + Session::delete('redirect_url'); + } + } } From 2b184efc473eb6e326c72a8fbb09ae554bcbb97a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 13:15:28 +0800 Subject: [PATCH 046/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3App=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 2760b88a..f4d1404c 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -100,9 +100,6 @@ class App // 规则闭包 $data = self::invokeFunction($dispatch['function'], $dispatch['params']); break; - case 'finish': - // 已经完成 不再继续执行 - break; default: throw new Exception('dispatch type not support', 10008); } @@ -111,16 +108,16 @@ class App } // 监听app_end - APP_HOOK && Hook::listen('app_end', isset($data) ? $data : ''); - if (isset($data)) { - // 输出数据到客户端 - if ($data instanceof Response) { - return $data->send(); - } else { - $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); - return Response::create($data, $type)->send(); - } + APP_HOOK && Hook::listen('app_end', $data); + + // 输出数据到客户端 + if ($data instanceof Response) { + return $data->send(); + } elseif (!is_null($data)) { + $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); + return Response::create($data, $type)->send(); } + } // 执行函数或者闭包方法 支持参数调用 From 92319c876c01ffe8ed6fc0cdc7b6c07df8442141 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 14:07:30 +0800 Subject: [PATCH 047/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Input=E7=B1=BB?= =?UTF-8?q?=E4=B8=80=E5=A4=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Input.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Input.php b/library/think/Input.php index 6ecd82de..880f2782 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -292,7 +292,7 @@ class Input static::typeCast($data, $type); } } else { - $data = $default; + $data = []; } return $data; } From 0acf217660f99d84ac222743f095ce01d674a5a5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 14:13:05 +0800 Subject: [PATCH 048/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/thinkphp/library/think/responseTest.php | 42 +++---------------- 1 file changed, 5 insertions(+), 37 deletions(-) diff --git a/tests/thinkphp/library/think/responseTest.php b/tests/thinkphp/library/think/responseTest.php index 3154ea61..07545696 100644 --- a/tests/thinkphp/library/think/responseTest.php +++ b/tests/thinkphp/library/think/responseTest.php @@ -78,16 +78,15 @@ class responseTest extends \PHPUnit_Framework_TestCase */ public function testSend() { - $dataArr = array(); + $dataArr = []; $dataArr["key"] = "value"; - //$dataArr->key = "val"; - $response = new \think\response\Json(); - $result = $response->send($dataArr); + $response = Response::create($dataArr, 'json'); + $result = $response->send(); $this->assertEquals('{"key":"value"}', $result); $_GET['callback'] = 'callback'; - $response = new \think\response\Jsonp(); - $result = $response->options(['var_jsonp_handler' => 'callback'])->send($dataArr); + $response = Response::create($dataArr, 'jsonp'); + $result = $response->options(['var_jsonp_handler' => 'callback'])->send(); $this->assertEquals('callback({"key":"value"});', $result); $response = new Response(); @@ -100,35 +99,4 @@ class responseTest extends \PHPUnit_Framework_TestCase $_GET[Config::get('var_jsonp_handler')] = ""; } - /** - * @#runInSeparateProcess - * @covers think\Response::redirect - * @todo Implement testRedirect(). - */ - public function testRedirect() - { - // $url = "http://www.testredirect.com"; - // $params = array(); - // $params[] = 301; - - // // FIXME 静态方法mock Url::build - // // echo "\r\n" . json_encode(xdebug_get_headers()) . "\r\n"; - // Response::redirect($url, $params); - - // $this->assertContains('Location: ' . $url, xdebug_get_headers()); - } - - /** - * @#runInSeparateProcess - * @covers think\Response::header - * @todo Implement testHeader(). - */ - public function testHeader() - { - // $name = "Location"; - // $url = "http://www.testheader.com/"; - // Response::header($name, $url); - // $this->assertContains($name . ': ' . $url, xdebug_get_headers()); - } - } From 3544809b1d162e180ab6447fdad577846b43d473 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 16:01:47 +0800 Subject: [PATCH 049/670] =?UTF-8?q?Route=E7=B1=BB=E6=94=B9=E8=BF=9B=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=9C=A8=E5=8C=B9=E9=85=8D=E5=88=B0=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E5=90=8E=20=E4=BD=BF=E7=94=A8after=5Fbehavior?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E8=B7=AF=E7=94=B1=E8=A7=84=E5=88=99=E9=87=8D?= =?UTF-8?q?=E5=AE=9A=E5=90=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 8 +++++--- library/think/Route.php | 17 ++++++++++++++--- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index f4d1404c..3c6440db 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -25,7 +25,7 @@ class App * 执行应用程序 * @access public * @param \think\Request $request Request对象 - * @return \think\Response + * @return mixed * @throws Exception */ public static function run($request) @@ -97,9 +97,12 @@ class App $data = self::invokeMethod($dispatch['method'], $dispatch['params']); break; case 'function': - // 规则闭包 + // 执行闭包 $data = self::invokeFunction($dispatch['function'], $dispatch['params']); break; + case 'response': + $data = $dispatch['response']; + break; default: throw new Exception('dispatch type not support', 10008); } @@ -117,7 +120,6 @@ class App $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); return Response::create($data, $type)->send(); } - } // 执行函数或者闭包方法 支持参数调用 diff --git a/library/think/Route.php b/library/think/Route.php index b2481ff1..f87cf841 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -510,6 +510,10 @@ class Route } if (isset($miss)) { // 未匹配所有路由的路由规则处理 + if ($miss instanceof \Closure) { + // 执行闭包 + return ['type' => 'function', 'function' => $miss, 'params' => []]; + } if (self::checkOption($miss['option'], $url)) { return self::parseRule('', $miss['route'], $url, []); } @@ -603,9 +607,16 @@ class Route // 匹配到路由规则 // 检测是否定义路由 if (!empty($option['after_behavior'])) { - $result = Hook::exec($option['after_behavior'], $route); - if (false === $result) { - return ['type' => 'finish']; + if ($option['after_behavior'] instanceof \Closure) { + $result = call_user_method_array($option['after_behavior'], [$route]); + } else { + $result = Hook::exec($option['after_behavior'], $route); + } + // 路由规则重定向 + if ($result instanceof Response) { + return ['type' => 'response', 'response' => $result, 'params' => $match]; + } elseif (is_array($result)) { + return $result; } } if ($route instanceof \Closure) { From 2072a395a6bbf36d12dc5da99adb1fed2e07acb6 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 16:08:09 +0800 Subject: [PATCH 050/670] =?UTF-8?q?App=E7=B1=BBmodule=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E6=94=B9=E4=B8=BApublic=20=E5=8F=AF=E4=BB=A5=E5=9C=A8=E9=97=AD?= =?UTF-8?q?=E5=8C=85=E4=B8=AD=E7=9B=B4=E6=8E=A5=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/App.php b/library/think/App.php index 3c6440db..db8d55fd 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -192,8 +192,11 @@ class App } // 执行 模块/控制器/操作 - private static function module($result, $config) + public static function module($result, $config) { + if (is_string($result)) { + $result = explode('/', $result); + } if (APP_MULTI_MODULE) { // 多模块部署 $module = strtolower($result[0] ?: $config['default_module']); From 5a01b29c302dda632bfa16be1abeb2510ad393fc Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 17:01:04 +0800 Subject: [PATCH 051/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Merge=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 83 ++++++++++++++++++++++++++++++++--- library/think/model/Merge.php | 21 +++++---- 2 files changed, 88 insertions(+), 16 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 1c8e1cf7..3ad257d4 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -32,9 +32,9 @@ class Query // 当前模型类名称 protected $model; // 当前数据表名称(含前缀) - protected $table; + protected $table = ''; // 当前数据表名称(不含前缀) - protected $name; + protected $name = ''; // 查询参数 protected $options = []; // 参数绑定 @@ -43,7 +43,7 @@ class Query /** * 架构函数 * @access public - * @param object|string $connection 数据库对象实例 + * @param \think\db\Connection|string $connection 数据库对象实例 * @throws Exception */ public function __construct($connection = '', $model = '') @@ -79,6 +79,16 @@ class Query } } + /** + * 获取当前的数据库Connection对象 + * @access public + * @return \think\db\Connection + */ + public function getConnection() + { + return $this->connection; + } + /** * 执行查询 返回数据集 * @access public @@ -122,6 +132,63 @@ class Query return $this->connection->getLastInsID(); } + /** + * 执行数据库事务 + * @access public + * @param callable $callback 数据操作方法回调 + * @return mixed + */ + public function transaction($callback) + { + return $this->connection->transaction($callback); + } + + /** + * 启动事务 + * @access public + * @param string $label 事务标识 + * @return bool|null + */ + public function startTrans($label = '') + { + return $this->connection->startTrans($label); + } + + /** + * 用于非自动提交状态下面的查询提交 + * @access public + * @param string $label 事务标识 + * @return boolean + * @throws PDOException + */ + public function commit($label = '') + { + return $this->connection->commit($label); + } + + /** + * 事务回滚 + * @access public + * @return boolean + * @throws PDOException + */ + public function rollback() + { + return $this->connection->rollback(); + } + + /** + * 批处理执行SQL语句 + * 批处理的指令都认为是execute操作 + * @access public + * @param array $sql SQL批处理指令 + * @return boolean + */ + public function batchQuery($sql = []) + { + return $this->connection->batchQuery($sql); + } + /** * 获取当前的builder实例对象 * @access protected @@ -962,14 +1029,16 @@ class Query /** * 得到当前的数据表 * @access public + * @param string $name * @return string */ - public function getTable() + public function getTable($name = '') { - if (empty($this->table)) { + if ($name || empty($this->table)) { + $name = $name ?: $this->name; $tableName = $this->connection->getConfig('prefix'); - if (isset($this->name)) { - $tableName .= Loader::parseName($this->name); + if ($name) { + $tableName .= Loader::parseName($name); } } else { $tableName = $this->table; diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 5384bb64..7cf43fb4 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -66,7 +66,7 @@ class Merge extends Model foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? self::db()->name($name)->getTable() : $model; + $table = is_int($key) ? self::db()->getTable($name) : $model; $query->join($table . ' ' . $name, $name . '.' . $class->fk . '=' . $master . '.' . $class->getPk()); $fields = self::getModelField($name, $table, $class->mapFields); $query->field($fields); @@ -182,10 +182,11 @@ class Merge extends Model // 写入附表数据 foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? self::db()->name($model)->getTable() : $model; + $table = is_int($key) ? self::db()->getTable($model) : $model; // 处理关联模型数据 - $data = $this->parseData($name, $this->data); - self::db()->table($table)->strict(false)->where($this->fk, $this->data[$this->getPk()])->update($data); + $data = $this->parseData($name, $this->data); + $query = clone self::db(); + $query->table($table)->strict(false)->where($this->fk, $this->data[$this->getPk()])->update($data); } // 新增回调 $this->trigger('after_update', $this); @@ -207,10 +208,11 @@ class Merge extends Model // 写入附表数据 foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? self::db()->name($model)->getTable() : $model; + $table = is_int($key) ? self::db()->getTable($model) : $model; // 处理关联模型数据 - $data = $this->parseData($name, $this->data, true); - self::db()->table($table)->strict(false)->insert($data); + $data = $this->parseData($name, $this->data, true); + $query = clone self::db(); + $query->table($table)->strict(false)->insert($data); } $result = $insertId; } @@ -244,8 +246,9 @@ class Merge extends Model // 删除关联数据 foreach (static::$relationModel as $key => $model) { - $table = is_int($key) ? self::db()->name($model)->getTable() : $model; - self::db()->table($table)->where($this->fk, $pk)->delete(); + $table = is_int($key) ? self::db()->getTable($model) : $model; + $query = clone self::db(); + $query->table($table)->where($this->fk, $pk)->delete(); } } $this->trigger('after_delete', $this); From f6efaba3e65398a8f2e296f1e5f460ceed14b9f1 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 17:13:07 +0800 Subject: [PATCH 052/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BInput=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Input.php | 58 ++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/library/think/Input.php b/library/think/Input.php index 880f2782..5d37fedf 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -261,39 +261,37 @@ class Input if (0 === strpos($name, '?')) { return self::has(substr($name, 1), $input); } - if (!empty($input)) { - $data = $input; - $name = (string) $name; - if ('' != $name) { - // 解析name - list($name, $type) = static::parseName($name); - // 按.拆分成多维数组进行判断 - foreach (explode('.', $name) as $val) { - if (isset($data[$val])) { - $data = $data[$val]; - } else { - // 无输入数据,返回默认值 - return $default; - } + + $data = $input; + $name = (string) $name; + if ('' != $name) { + // 解析name + list($name, $type) = static::parseName($name); + // 按.拆分成多维数组进行判断 + foreach (explode('.', $name) as $val) { + if (isset($data[$val])) { + $data = $data[$val]; + } else { + // 无输入数据,返回默认值 + return $default; } } - - // 解析过滤器 - $filters = static::parseFilter($filter, $merge); - // 为方便传参把默认值附加在过滤器后面 - $filters[] = $default; - if (is_array($data)) { - array_walk_recursive($data, 'self::filter', $filters); - } else { - self::filter($data, $name ?: 0, $filters); - } - if (isset($type) && $data !== $default) { - // 强制类型转换 - static::typeCast($data, $type); - } - } else { - $data = []; } + + // 解析过滤器 + $filters = static::parseFilter($filter, $merge); + // 为方便传参把默认值附加在过滤器后面 + $filters[] = $default; + if (is_array($data)) { + array_walk_recursive($data, 'self::filter', $filters); + } else { + self::filter($data, $name ?: 0, $filters); + } + if (isset($type) && $data !== $default) { + // 强制类型转换 + static::typeCast($data, $type); + } + return $data; } From baebe7899ebe2ff40cbf23c8c35f42173ef4c2f0 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 17:53:33 +0800 Subject: [PATCH 053/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRelation=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Relation.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index ab605761..a2673237 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -534,9 +534,7 @@ class Relation if (is_array($data)) { // 保存关联表数据 $model = new $this->model; - $model->save($data); - $relationFk = $model->getPk(); - $id = $model->$relationFk; + $id = $model->save($data); } elseif (is_int($data)) { // 根据关联表主键直接写入中间表 $id = $data; @@ -551,7 +549,8 @@ class Relation $pk = $this->parent->getPk(); $pivot[$this->localKey] = $this->parent->$pk; $pivot[$this->foreignKey] = $id; - return Db::table($this->middle)->insert($pivot); + $query = clone $this->parent->db(); + return $query->table($this->middle)->insert($pivot); } else { throw new Exception(' miss relation data'); } @@ -580,7 +579,8 @@ class Relation $pk = $this->parent->getPk(); $pivot[$this->localKey] = $this->parent->$pk; $pivot[$this->foreignKey] = is_array($id) ? ['in', $id] : $id; - Db::table($this->middle)->where($pivot)->delete(); + $query = clone $this->parent->db(); + $query->table($this->middle)->where($pivot)->delete(); // 删除关联表数据 if ($relationDel) { @@ -593,7 +593,7 @@ class Relation { if ($this->model) { $model = new $this->model; - $db = $model->db(); + $db = $model::db(); if (self::HAS_MANY == $this->type && isset($this->parent->{$this->localKey})) { // 关联查询带入关联条件 $db->where($this->foreignKey, $this->parent->{$this->localKey}); From 63521c1db3935c367b4d2e6817af6b3c9145ce4b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 18:19:13 +0800 Subject: [PATCH 054/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 7 ++++--- library/think/db/Connection.php | 5 +++-- library/think/model/Merge.php | 34 +++++++++++++++++---------------- 3 files changed, 25 insertions(+), 21 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index af278982..cb04724c 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -293,6 +293,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return false; } + $db = self::db(); if ($this->isUpdate) { // 自动更新 $this->autoCompleteData($this->update); @@ -320,7 +321,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } } - $result = self::db()->where($where)->update($data); + $result = $db->where($where)->update($data); // 更新回调 $this->trigger('after_update', $this); @@ -332,11 +333,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return false; } - $result = self::db()->insert($this->data); + $result = $db->insert($this->data); // 获取自动增长主键 if ($result && $getId) { - $insertId = self::db()->getLastInsID(); + $insertId = $db->getLastInsID(); $pk = $this->getPk(); if (is_string($pk) && $insertId) { $this->data[$pk] = $insertId; diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 71d84f3a..5b2ad454 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -506,13 +506,14 @@ abstract class Connection */ public function transaction($callback) { - $this->startTrans(NOW_TIME); + $label = microtime(true); + $this->startTrans($label); try { $result = null; if (is_callable($callback)) { $result = call_user_func_array($callback, []); } - $this->commit(NOW_TIME); + $this->commit($label); return $result; } catch (\PDOException $e) { $this->rollback(); diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 7cf43fb4..4b1cd0c8 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -166,7 +166,8 @@ class Merge extends Model // 处理模型数据 $data = $this->parseData($this->name, $this->data); - self::db()->startTrans(); + $db = self::db(); + $db->startTrans('merge_save_' . $this->name); try { if ($this->isUpdate) { // 自动写入 @@ -177,15 +178,15 @@ class Merge extends Model } // 写入主表数据 - $result = self::db()->strict(false)->update($data); + $result = $db->strict(false)->update($data); // 写入附表数据 foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? self::db()->getTable($model) : $model; + $table = is_int($key) ? $db->getTable($model) : $model; // 处理关联模型数据 $data = $this->parseData($name, $this->data); - $query = clone self::db(); + $query = clone $db; $query->table($table)->strict(false)->where($this->fk, $this->data[$this->getPk()])->update($data); } // 新增回调 @@ -199,19 +200,19 @@ class Merge extends Model } // 写入主表数据 - $result = self::db()->name($this->name)->strict(false)->insert($this->data); + $result = $db->name($this->name)->strict(false)->insert($this->data); if ($result) { - $insertId = self::db()->getLastInsID(); + $insertId = $db->getLastInsID(); // 写入外键数据 $this->data[$this->fk] = $insertId; // 写入附表数据 foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? self::db()->getTable($model) : $model; + $table = is_int($key) ? $db->getTable($model) : $model; // 处理关联模型数据 $data = $this->parseData($name, $this->data, true); - $query = clone self::db(); + $query = clone $db; $query->table($table)->strict(false)->insert($data); } $result = $insertId; @@ -219,10 +220,10 @@ class Merge extends Model // 新增回调 $this->trigger('after_insert', $this); } - self::db()->commit(); + $db->commit('merge_save_' . $this->name); return $result; } catch (\PDOException $e) { - self::db()->rollback(); + $db->rollback(); return false; } } @@ -237,25 +238,26 @@ class Merge extends Model if (false === $this->trigger('before_delete', $this)) { return false; } - self::db()->startTrans(); + $db = self::db(); + $db->startTrans('merge_delete_' . $this->name); try { - $result = self::db()->delete($this->data); + $result = $db->delete($this->data); if ($result) { // 获取主键数据 $pk = $this->data[$this->getPk()]; // 删除关联数据 foreach (static::$relationModel as $key => $model) { - $table = is_int($key) ? self::db()->getTable($model) : $model; - $query = clone self::db(); + $table = is_int($key) ? $db->getTable($model) : $model; + $query = clone $db; $query->table($table)->where($this->fk, $pk)->delete(); } } $this->trigger('after_delete', $this); - self::db()->commit(); + $db->commit('merge_delete_' . $this->name); return $result; } catch (\PDOException $e) { - self::db()->rollback(); + $db->rollback(); return false; } } From f9469f2cfca6d3a4ae7d9fc7cb94d1453929543b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 21:36:46 +0800 Subject: [PATCH 055/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= =?UTF-8?q?=E4=B8=80=E5=A4=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Route.php b/library/think/Route.php index f87cf841..53ff4580 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -608,7 +608,7 @@ class Route // 检测是否定义路由 if (!empty($option['after_behavior'])) { if ($option['after_behavior'] instanceof \Closure) { - $result = call_user_method_array($option['after_behavior'], [$route]); + $result = call_user_func_array($option['after_behavior'], [$route]); } else { $result = Hook::exec($option['after_behavior'], $route); } From cda738b03856d679cfae76885f776721f22cbc71 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 22:14:09 +0800 Subject: [PATCH 056/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84destroy=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E4=BC=A0=E5=85=A5=E6=95=B0=E7=BB=84=E5=88=A0=E9=99=A4=E6=9D=A1?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index cb04724c..03b52e46 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -639,7 +639,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public static function destroy($data) { $db = self::db(); - if ($data instanceof \Closure) { + if (is_array($data) && key($data) !== 0) { + $db->where($data); + $data = []; + } elseif ($data instanceof \Closure) { call_user_func_array($data, [ & $db]); $data = []; } From 28bf9b2726b547e5bafa817fe65c95769443a63b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 23:20:09 +0800 Subject: [PATCH 057/670] =?UTF-8?q?=E4=BC=98=E5=8C=96App=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 23 +++++++++-------------- library/think/Response.php | 3 ++- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index db8d55fd..ab069172 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -11,8 +11,16 @@ namespace think; +use think\Config; +use think\Exception; 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; /** * App 应用管理 @@ -137,20 +145,7 @@ class App { if (empty($vars)) { // 自动获取请求变量 - switch (REQUEST_METHOD) { - case 'POST': - $vars = array_merge($_GET, $_POST); - break; - case 'PUT': - static $_PUT = null; - if (is_null($_PUT)) { - parse_str(file_get_contents('php://input'), $_PUT); - } - $vars = array_merge($_GET, $_PUT); - break; - default: - $vars = $_GET; - } + $vars = Request::instance()->param(); } if (is_array($method)) { $class = is_object($method[0]) ? $method[0] : new $method[0]; diff --git a/library/think/Response.php b/library/think/Response.php index a0f4a5d1..d65d2a35 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -19,6 +19,7 @@ class Response protected $transform; // 输出数据 protected $data; + // 输出类型 protected $type; // 当前的contentType protected $contentType; @@ -67,7 +68,7 @@ class Response { $type = strtolower($type ?: (IS_AJAX ? 'json' : 'html')); if (!isset(self::$instance[$type])) { - $class = '\\think\response\\' . ucfirst($type); + $class = '\\think\\response\\' . ucfirst($type); if (class_exists($class)) { $response = new $class($data, $type, $options); } else { From 223db98e1d380d7f24c60b427e3ada168978eb9c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 23:28:49 +0800 Subject: [PATCH 058/670] =?UTF-8?q?=E4=BC=98=E5=8C=96App=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index ab069172..6f70640d 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -321,9 +321,9 @@ class App throw new Exception('url suffix deny'); } - $_SERVER['PATH_INFO'] = $request->path(); - $depr = $config['pathinfo_depr']; - $result = false; + $path = $request->path(); + $depr = $config['pathinfo_depr']; + $result = false; // 路由检测 if (APP_ROUTE_ON && !empty($config['url_route_on'])) { // 开启路由 @@ -332,7 +332,7 @@ class App Route::import($config['route']); } // 路由检测(根据路由定义返回不同的URL调度) - $result = Route::check($request, $_SERVER['PATH_INFO'], $depr, !IS_CLI ? $config['url_domain_deploy'] : false); + $result = Route::check($request, $path, $depr, !IS_CLI ? $config['url_domain_deploy'] : false); if (APP_ROUTE_MUST && false === $result && $config['url_route_must']) { // 路由无效 throw new Exception('route not define '); @@ -340,7 +340,7 @@ class App } if (false === $result) { // 路由无效默认分析为模块/控制器/操作/参数...方式URL - $result = Route::parseUrl($_SERVER['PATH_INFO'], $depr); + $result = Route::parseUrl($path, $depr); } //保证$_REQUEST正常取值 $_REQUEST = array_merge($_POST, $_GET, $_COOKIE); From 1fab955a5fc88677fe5e3c25c4770d420975ffeb Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 17 May 2016 23:37:29 +0800 Subject: [PATCH 059/670] =?UTF-8?q?=E6=9A=82=E6=97=B6=E8=BF=98=E5=8E=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 6f70640d..ab069172 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -321,9 +321,9 @@ class App throw new Exception('url suffix deny'); } - $path = $request->path(); - $depr = $config['pathinfo_depr']; - $result = false; + $_SERVER['PATH_INFO'] = $request->path(); + $depr = $config['pathinfo_depr']; + $result = false; // 路由检测 if (APP_ROUTE_ON && !empty($config['url_route_on'])) { // 开启路由 @@ -332,7 +332,7 @@ class App Route::import($config['route']); } // 路由检测(根据路由定义返回不同的URL调度) - $result = Route::check($request, $path, $depr, !IS_CLI ? $config['url_domain_deploy'] : false); + $result = Route::check($request, $_SERVER['PATH_INFO'], $depr, !IS_CLI ? $config['url_domain_deploy'] : false); if (APP_ROUTE_MUST && false === $result && $config['url_route_must']) { // 路由无效 throw new Exception('route not define '); @@ -340,7 +340,7 @@ class App } if (false === $result) { // 路由无效默认分析为模块/控制器/操作/参数...方式URL - $result = Route::parseUrl($path, $depr); + $result = Route::parseUrl($_SERVER['PATH_INFO'], $depr); } //保证$_REQUEST正常取值 $_REQUEST = array_merge($_POST, $_GET, $_COOKIE); From c0048e80ea5185be74bdea78f85b489ec57f2815 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 00:02:27 +0800 Subject: [PATCH 060/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 10 +++++----- tests/thinkphp/library/think/appTest.php | 6 ++---- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index ab069172..6f70640d 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -321,9 +321,9 @@ class App throw new Exception('url suffix deny'); } - $_SERVER['PATH_INFO'] = $request->path(); - $depr = $config['pathinfo_depr']; - $result = false; + $path = $request->path(); + $depr = $config['pathinfo_depr']; + $result = false; // 路由检测 if (APP_ROUTE_ON && !empty($config['url_route_on'])) { // 开启路由 @@ -332,7 +332,7 @@ class App Route::import($config['route']); } // 路由检测(根据路由定义返回不同的URL调度) - $result = Route::check($request, $_SERVER['PATH_INFO'], $depr, !IS_CLI ? $config['url_domain_deploy'] : false); + $result = Route::check($request, $path, $depr, !IS_CLI ? $config['url_domain_deploy'] : false); if (APP_ROUTE_MUST && false === $result && $config['url_route_must']) { // 路由无效 throw new Exception('route not define '); @@ -340,7 +340,7 @@ class App } if (false === $result) { // 路由无效默认分析为模块/控制器/操作/参数...方式URL - $result = Route::parseUrl($_SERVER['PATH_INFO'], $depr); + $result = Route::parseUrl($path, $depr); } //保证$_REQUEST正常取值 $_REQUEST = array_merge($_POST, $_GET, $_COOKIE); diff --git a/tests/thinkphp/library/think/appTest.php b/tests/thinkphp/library/think/appTest.php index 97640ab9..d959ff83 100644 --- a/tests/thinkphp/library/think/appTest.php +++ b/tests/thinkphp/library/think/appTest.php @@ -87,12 +87,10 @@ class appTest extends \PHPUnit_Framework_TestCase // 类method调度 public function testInvokeMethod() { - $_GET = ['thinkphp']; - $result = App::invokeMethod(['tests\thinkphp\library\think\AppInvokeMethodTestClass', 'run']); + $result = App::invokeMethod(['tests\thinkphp\library\think\AppInvokeMethodTestClass', 'run'], ['thinkphp']); $this->assertEquals('thinkphp', $result); - $_GET = ['thinkphp']; - $result = App::invokeMethod('tests\thinkphp\library\think\AppInvokeMethodTestClass::staticRun'); + $result = App::invokeMethod('tests\thinkphp\library\think\AppInvokeMethodTestClass::staticRun', ['thinkphp']); $this->assertEquals('thinkphp', $result); } } From 198ea76923f4c3b104f35a5f4f27a58208805f9c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 10:20:34 +0800 Subject: [PATCH 061/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- library/think/db/Query.php | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 03b52e46..befb147e 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -875,7 +875,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 设置当前数据表和模型名 if (!empty($class->table)) { - self::$links[$model]->table($class->table); + self::$links[$model]->setTable($class->table); } else { $name = !empty($class->name) ? $class->name : basename(str_replace('\\', '/', $model)); self::$links[$model]->name($name); diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 3ad257d4..cb6a0f8c 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -786,14 +786,26 @@ class Query } /** - * 指定数据表 + * 指定默认数据表 + * @access public + * @param string $table 表名 + * @return $this + */ + public function setTable($table) + { + $this->table = $table; + return $this; + } + + /** + * 指定当前操作的数据表 * @access public * @param string $table 表名 * @return $this */ public function table($table) { - $this->table = $table; + $this->options['table'] = $table; return $this; } From fdd41cd1c7076b569b05e8202b3074ed11f7e31b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 11:01:49 +0800 Subject: [PATCH 062/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getData=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- library/think/db/Query.php | 40 +++++++++++++++++++------------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index befb147e..9f0bd403 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -163,7 +163,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function getData($name = '') { - return isset($this->data[$name]) ? $this->data[$name] : $this->data; + return array_key_exists($name, $this->data) ? $this->data[$name] : $this->data; } /** diff --git a/library/think/db/Query.php b/library/think/db/Query.php index cb6a0f8c..c3a510c4 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -797,6 +797,26 @@ class Query return $this; } + /** + * 得到当前的数据表 + * @access public + * @param string $name + * @return string + */ + public function getTable($name = '') + { + if ($name || empty($this->table)) { + $name = $name ?: $this->name; + $tableName = $this->connection->getConfig('prefix'); + if ($name) { + $tableName .= Loader::parseName($name); + } + } else { + $tableName = $this->table; + } + return $tableName; + } + /** * 指定当前操作的数据表 * @access public @@ -1038,26 +1058,6 @@ class Query return $this; } - /** - * 得到当前的数据表 - * @access public - * @param string $name - * @return string - */ - public function getTable($name = '') - { - if ($name || empty($this->table)) { - $name = $name ?: $this->name; - $tableName = $this->connection->getConfig('prefix'); - if ($name) { - $tableName .= Loader::parseName($name); - } - } else { - $tableName = $this->table; - } - return $tableName; - } - /** * 获取数据表信息 * @access public From 5dc8cd481ec4f522db2d37ee4f04825d00923ddd Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 11:27:20 +0800 Subject: [PATCH 063/670] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E6=97=A0=E7=94=A8=E7=9A=84=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/convention.php b/convention.php index 10fa3218..d13b730c 100644 --- a/convention.php +++ b/convention.php @@ -15,12 +15,8 @@ return [ 'extra_file_list' => [THINK_PATH . 'helper' . EXT], // 默认输出类型 'default_return_type' => 'html', - // 默认语言 - 'default_lang' => 'zh-cn', - // response是否返回方式 - 'response_return' => false, - // 默认AJAX 数据返回格式,可选JSON XML ... - 'default_ajax_return' => 'JSON', + // 默认AJAX 数据返回格式,可选json xml ... + 'default_ajax_return' => 'json', // 默认JSONP格式返回的处理方法 'default_jsonp_handler' => 'jsonpReturn', // 默认JSONP处理方法 @@ -31,6 +27,8 @@ return [ 'lang_switch_on' => false, // 默认全局过滤方法 用逗号分隔多个 'default_filter' => '', + // 默认语言 + 'default_lang' => 'zh-cn', // 是否启用控制器类后缀 'use_controller_suffix' => false, From a00c4c51fe917eb11928a6f84e54ee2fcaccbd7a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 12:30:55 +0800 Subject: [PATCH 064/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Db.php | 10 +++---- library/think/Model.php | 2 -- library/think/db/Connection.php | 20 ++++++++------ library/think/db/Query.php | 49 +++++++++++++++++++++------------ 4 files changed, 47 insertions(+), 34 deletions(-) diff --git a/library/think/Db.php b/library/think/Db.php index d329b4e8..18e5874c 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -23,7 +23,7 @@ class Db // 自定义对象数据集 const RESULTSET_CLASS = 3; // 数据库连接实例 - private static $instances = []; + private static $instance = []; // 查询次数 public static $queryTimes = 0; // 执行次数 @@ -35,7 +35,7 @@ class Db * @access public * @param mixed $config 连接配置 * @param bool|string $name 连接标识 true 强制重新连接 - * @return db\Connection + * @return \think\db\Connection * @throws Exception */ public static function connect($config = [], $name = false) @@ -43,7 +43,7 @@ class Db if (false === $name) { $name = md5(serialize($config)); } - if (true === $name || !isset(self::$instances[$name])) { + if (true === $name || !isset(self::$instance[$name])) { // 解析连接参数 支持数组和字符串 $options = self::parseConfig($config); if (empty($options['type'])) { @@ -55,10 +55,10 @@ class Db if (true === $name) { return new $class($options); } else { - self::$instances[$name] = new $class($options); + self::$instance[$name] = new $class($options); } } - return self::$instances[$name]; + return self::$instance[$name]; } /** diff --git a/library/think/Model.php b/library/think/Model.php index 9f0bd403..9903370b 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -50,8 +50,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $hidden = []; // 数据信息 protected $data = []; - // 缓存数据 - protected $cache = []; // 记录改变字段 protected $change = []; diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 5b2ad454..22eebb89 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -595,22 +595,23 @@ abstract class Connection * 批处理执行SQL语句 * 批处理的指令都认为是execute操作 * @access public - * @param array $sql SQL批处理指令 + * @param array $sqlArray SQL批处理指令 * @return boolean */ - public function batchQuery($sql = []) + public function batchQuery($sqlArray = []) { - if (!is_array($sql)) { + if (!is_array($sqlArray)) { return false; } // 自动启动事务支持 - $this->startTrans(NOW_TIME); + $label = microtime(true); + $this->startTrans($label); try { - foreach ($sql as $_sql) { - $result = $this->execute($_sql); + foreach ($sqlArray as $sql) { + $result = $this->execute($sql); } // 提交事务 - $this->commit(NOW_TIME); + $this->commit($label); } catch (\PDOException $e) { $this->rollback(); return false; @@ -717,9 +718,10 @@ abstract class Connection } /** - * 数据库调试 记录当前SQL + * 数据库调试 记录当前SQL及分析性能 * @access protected * @param boolean $start 调试开始标记 true 开始 false 结束 + * @return void */ protected function debug($start) { @@ -782,7 +784,7 @@ abstract class Connection /** * 初始化数据库连接 * @access protected - * @param boolean $master 主服务器 + * @param boolean $master 是否主服务器 * @return void */ protected function initConnect($master = true) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index c3a510c4..d55c2161 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -44,6 +44,7 @@ class Query * 架构函数 * @access public * @param \think\db\Connection|string $connection 数据库对象实例 + * @param string $model 模型名 * @throws Exception */ public function __construct($connection = '', $model = '') @@ -786,7 +787,19 @@ class Query } /** - * 指定默认数据表 + * 指定默认的数据表名(不含前缀) + * @access public + * @param string $name + * @return $this + */ + public function name($name) + { + $this->name = $name; + return $this; + } + + /** + * 指定默认数据表名(含前缀) * @access public * @param string $table 表名 * @return $this @@ -1046,23 +1059,11 @@ class Query return $this; } - /** - * 设置当前name - * @access public - * @param string $name - * @return $this - */ - public function name($name) - { - $this->name = $name; - return $this; - } - /** * 获取数据表信息 * @access public - * @param string $fetch 获取信息类型 包括 fields type bind pk * @param string $tableName 数据表名 留空自动获取 + * @param string $fetch 获取信息类型 包括 fields type bind pk * @return mixed */ public function getTableInfo($tableName = '', $fetch = '') @@ -1113,7 +1114,7 @@ class Query * 获取当前模型对象的主键 * @access public * @param string $table 数据表名 - * @return mixed + * @return string|array */ public function getPk($table = '') { @@ -1138,6 +1139,12 @@ class Query return $this; } + /** + * 检测参数是否已经绑定 + * @access public + * @param string $key 参数名 + * @return bool + */ public function isBind($key) { return isset($this->bind[$key]); @@ -1155,6 +1162,12 @@ class Query return $this; } + /** + * 获取当前的查询参数 + * @access public + * @param string $name 参数名 + * @return mixed + */ public function getOptions($name = '') { return isset($this->options[$name]) ? $this->options[$name] : $this->options; @@ -1164,7 +1177,7 @@ class Query * 设置关联查询JOIN预查询 * @access public * @param string|array $with 关联方法名称 - * @return Db + * @return $this */ public function with($with) { @@ -1225,7 +1238,7 @@ class Query * 设置当前字段添加的表别名 * @access public * @param string $via - * @return Db + * @return $this */ public function via($via = '') { @@ -1237,7 +1250,7 @@ class Query * 设置关联查询 * @access public * @param string $relation 关联名称 - * @return Db + * @return $this */ public function relation($relation) { From 0e441d2b6943085a6e3aded5d7519687d104c69d Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 18 May 2016 14:48:45 +0800 Subject: [PATCH 065/670] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E9=87=8C=E5=8F=91?= =?UTF-8?q?=E7=94=9F=E5=BC=82=E5=B8=B8=E6=97=B6=E6=B8=85=E7=A9=BA=E4=B9=8B?= =?UTF-8?q?=E5=89=8D=E7=9A=84=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/exception/Handle.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index 8c9c3632..354c6596 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -42,13 +42,13 @@ class Handle 'message' => $exception->getMessage(), 'code' => $this->getCode($exception), ]; - $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; + $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; } else { $data = [ 'code' => $exception->getCode(), 'message' => $exception->getMessage(), ]; - $log = "[{$data['code']}]{$data['message']}"; + $log = "[{$data['code']}]{$data['message']}"; } Log::record($log, 'error'); @@ -144,6 +144,10 @@ class Handle // 不显示详细错误信息 $data['message'] = Config::get('error_message'); } + //保留一层 + while (ob_get_level() > 1) { + ob_end_clean(); + } ob_start(); ob_implicit_flush(0); extract($data); From 2dab11d3c48d5523765679d86b5926fb8940a921 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 15:19:23 +0800 Subject: [PATCH 066/670] =?UTF-8?q?File=E7=B1=BB=E5=A2=9E=E5=8A=A0rule?= =?UTF-8?q?=E5=92=8CisValid=E6=96=B9=E6=B3=95=EF=BC=8Cmove=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=94=AF=E6=8C=81=E8=87=AA=E5=8A=A8=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 73 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 6 deletions(-) diff --git a/library/think/File.php b/library/think/File.php index 89c7b248..e30a1c50 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -15,12 +15,13 @@ use SplFileObject; class File extends SplFileObject { - /** * 错误信息 * @var string */ private $error = ''; + // 文件上传命名规则 + protected $rule = 'date'; /** * 检查目录是否可写 @@ -51,24 +52,49 @@ class File extends SplFileObject return finfo_file($finfo, $this->getRealPath()); } + /** + * 设置文件的命名规则 + * @param string $rule 文件命名规则 + * @return $this + */ + public function rule($rule) + { + $this->rule = $rule; + return $this; + } + + /** + * 检测是否合法的上传文件 + * @return bool + */ + public function isValid() + { + return is_uploaded_file($this->getRealPath()); + } + /** * 移动文件 * @param string $path 保存路径 - * @param string $savename 保存的文件名 + * @param string|bool $savename 保存的文件名 默认自动生成 * @param boolean $replace 同名文件是否覆盖 * @return false|SplFileInfo false-失败 否则返回SplFileInfo实例 */ - public function move($path, $savename = '', $replace = true) + public function move($path, $savename = true, $replace = true) { - if (!is_uploaded_file($this->getRealPath())) { + // 检测合法性 + if (!$this->isValid()) { + $this->error = '非法上传文件'; return false; } - if (false === $this->checkPath($path)) { + // 文件保存命名规则 + $savename = $this->getSaveName($savename); + + // 检测目录 + if (false === $this->checkPath(dirname($path . $savname))) { return false; } - $savename = $savename ?: $this->getFilename(); /* 不覆盖同名文件 */ if (!$replace && is_file($path . $savename)) { $this->error = '存在同名文件' . $path . $savename; @@ -84,6 +110,41 @@ class File extends SplFileObject return new \SplFileInfo($path . $savename); } + /** + * 获取保存文件名 + * @param string|bool $savename 保存的文件名 默认自动生成 + * @return string + */ + protected function getSaveName($savename) + { + if (true === $savename) { + // 自动生成文件名 + if ($this->rule instanceof \Closure) { + $savename = call_user_func_array($this->rule, [$this->getFilename()]); + } else { + switch ($this->rule) { + case 'uniqid': + $savename = uniqid(); + break; + case 'md5': + $savename = md5($this->getFilename()); + break; + case 'date': + $savename = date('Y-m-d') . DS . md5(microtime(true)); + break; + default: + $savename = call_user_func($this->rule); + } + } + if (!strpos($savename, '.')) { + $savename .= '.' . $this->getExtension(); + } + } elseif ('' === $savename) { + $savename = $this->getFilename(); + } + return $savename; + } + /** * 获取错误信息 * @return mixed From c606b75ab861974dc100a88809c0cad2cee5ef02 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 15:31:10 +0800 Subject: [PATCH 067/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BMerge=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E7=B1=BB=E7=9A=84attachQuery=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Merge.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 4b1cd0c8..6f35b297 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -59,8 +59,8 @@ class Merge extends Model */ protected static function attachQuery($query) { - $master = basename(str_replace('\\', '/', get_called_class())); $class = new static(); + $master = $class->name; $fields = self::getModelField($master, '', $class->mapFields); $query->alias($master)->field($fields); From 690839ddc92fee514e600ea23a46249809efe579 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 15:40:07 +0800 Subject: [PATCH 068/670] =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=B8=8A=E4=BC=A0?= =?UTF-8?q?=E8=A7=84=E5=88=99=E6=94=AF=E6=8C=81=20sha1=20=E5=92=8C=20md5?= =?UTF-8?q?=20=E4=B8=80=E6=A0=B7=20=E9=87=87=E7=94=A8=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E6=95=A3=E5=88=97=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/library/think/File.php b/library/think/File.php index e30a1c50..3678321d 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -127,7 +127,12 @@ class File extends SplFileObject $savename = uniqid(); break; case 'md5': - $savename = md5($this->getFilename()); + $md5 = md5_file($this->getFilename()); + $savename = substr($md5, 0, 2) . DS . substr($md5, 2); + break; + case 'sha1': + $sha1 = sha1_file($this->getFilename()); + $savename = substr($sha1, 0, 2) . DS . substr($sha1, 2); break; case 'date': $savename = date('Y-m-d') . DS . md5(microtime(true)); From 2af19639cb7d788fa21db7ee14ef95c8ca0ef7d1 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 15:43:16 +0800 Subject: [PATCH 069/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BFile=E7=B1=BB=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E9=97=AD=E5=8C=85=E8=A7=84=E5=88=99=20?= =?UTF-8?q?=E5=8F=82=E6=95=B0=E4=B8=BA=E5=BD=93=E5=89=8D=E7=9A=84=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E5=AF=B9=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/File.php b/library/think/File.php index 3678321d..c772d8c7 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -120,18 +120,18 @@ class File extends SplFileObject if (true === $savename) { // 自动生成文件名 if ($this->rule instanceof \Closure) { - $savename = call_user_func_array($this->rule, [$this->getFilename()]); + $savename = call_user_func_array($this->rule, [$this]); } else { switch ($this->rule) { case 'uniqid': $savename = uniqid(); break; case 'md5': - $md5 = md5_file($this->getFilename()); + $md5 = md5_file($this->getRealPath()); $savename = substr($md5, 0, 2) . DS . substr($md5, 2); break; case 'sha1': - $sha1 = sha1_file($this->getFilename()); + $sha1 = sha1_file($this->getRealPath()); $savename = substr($sha1, 0, 2) . DS . substr($sha1, 2); break; case 'date': From e093a6661e6df3c6731d0cfcaad89f663265fc5a Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 18 May 2016 16:51:23 +0800 Subject: [PATCH 070/670] =?UTF-8?q?=E5=88=86=E9=A1=B5=E7=9A=84=E6=AF=8F?= =?UTF-8?q?=E9=A1=B5=E6=95=B0=E9=87=8F=E5=8F=AF=E4=BB=A5=E9=80=9A=E8=BF=87?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=85=A8=E5=B1=80=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 5 +++-- library/think/db/Query.php | 7 +++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/convention.php b/convention.php index d13b730c..55f2d50b 100644 --- a/convention.php +++ b/convention.php @@ -209,8 +209,9 @@ return [ ], //分页配置 'paginate' => [ - 'type' => 'bootstrap', - 'var_page' => 'page', + 'type' => 'bootstrap', + 'var_page' => 'page', + 'list_rows' => 15 ], ]; diff --git a/library/think/db/Query.php b/library/think/db/Query.php index d55c2161..59fd6393 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -744,7 +744,7 @@ class Query /** * 分页查询 - * @param int $listRows 每页数量 + * @param int|null $listRows 每页数量 * @param bool $simple 简洁模式 * @param array $config 配置参数 * page:当前页, @@ -752,15 +752,18 @@ class Query * query:url额外参数, * fragment:url锚点, * var_page:分页变量, + * list_rows:每页数量 * type:分页类名, * namespace:分页类命名空间 * @return \think\paginator\Collection * @throws DbException */ - public function paginate($listRows = 15, $simple = false, $config = []) + public function paginate($listRows = null, $simple = false, $config = []) { $config = array_merge(Config::get('paginate'), $config); + $listRows = $listRows ?: $config['list_rows']; + $class = (!empty($config['namespace']) ? $config['namespace'] : '\\think\\paginator\\driver\\') . ucwords($config['type']); $page = isset($config['page']) ? (int) $config['page'] : call_user_func([ From 811b22fe74a206853370fe8e93be01117ee2174f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 17:42:36 +0800 Subject: [PATCH 071/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=8A=A8=E6=80=81=E6=9F=A5=E8=AF=A2=E8=B0=83?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 6 +++--- library/think/model/Merge.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 9903370b..2179920d 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -859,10 +859,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 初始化数据库对象 - * @access public + * @access protected * @return \think\db\Query */ - public static function db() + protected static function db() { $model = get_called_class(); if (!isset(self::$links[$model])) { @@ -894,7 +894,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess call_user_func_array([$this, $method], $args); return $this; } else { - throw new Exception(__CLASS__ . ':' . $method . ' method not exist'); + return call_user_func_array([self::db(), $method], $args); } } diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 6f35b297..05918fac 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -66,7 +66,7 @@ class Merge extends Model foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? self::db()->getTable($name) : $model; + $table = is_int($key) ? $query->getTable($name) : $model; $query->join($table . ' ' . $name, $name . '.' . $class->fk . '=' . $master . '.' . $class->getPk()); $fields = self::getModelField($name, $table, $class->mapFields); $query->field($fields); From 4898e333b55000d12a089ec075902832f8cf9227 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 18:28:25 +0800 Subject: [PATCH 072/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 109 ++++++++++++++++++------------------- 1 file changed, 53 insertions(+), 56 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 59fd6393..f327f78d 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -90,6 +90,50 @@ class Query return $this->connection; } + /** + * 指定默认的数据表名(不含前缀) + * @access public + * @param string $name + * @return $this + */ + public function name($name) + { + $this->name = $name; + return $this; + } + + /** + * 指定默认数据表名(含前缀) + * @access public + * @param string $table 表名 + * @return $this + */ + public function setTable($table) + { + $this->table = $table; + return $this; + } + + /** + * 得到当前的数据表 + * @access public + * @param string $name + * @return string + */ + public function getTable($name = '') + { + if ($name || empty($this->table)) { + $name = $name ?: $this->name; + $tableName = $this->connection->getConfig('prefix'); + if ($name) { + $tableName .= Loader::parseName($name); + } + } else { + $tableName = $this->table; + } + return $tableName; + } + /** * 执行查询 返回数据集 * @access public @@ -760,13 +804,10 @@ class Query */ public function paginate($listRows = null, $simple = false, $config = []) { - $config = array_merge(Config::get('paginate'), $config); - + $config = array_merge(Config::get('paginate'), $config); $listRows = $listRows ?: $config['list_rows']; - - $class = (!empty($config['namespace']) ? $config['namespace'] : '\\think\\paginator\\driver\\') . ucwords($config['type']); - - $page = isset($config['page']) ? (int) $config['page'] : call_user_func([ + $class = (!empty($config['namespace']) ? $config['namespace'] : '\\think\\paginator\\driver\\') . ucwords($config['type']); + $page = isset($config['page']) ? (int) $config['page'] : call_user_func([ $class, 'getCurrentPage', ], $config['var_page']); @@ -777,62 +818,18 @@ class Query /** @var Paginator $paginator */ if (!$simple) { - $options = $this->getOptions(); - $total = $this->count(); - $results = $this->options($options)->page($page, $listRows)->select(); - $paginator = new $class($results, $listRows, $page, $simple, $total, $config); + $options = $this->getOptions(); + $total = $this->count(); + $results = $this->options($options)->page($page, $listRows)->select(); } else { - $results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select(); - $paginator = new $class($results, $listRows, $page, $simple, null, $config); + $results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select(); + $total = null; } + $paginator = new $class($results, $listRows, $page, $simple, $total, $config); return $paginator->items(); } - /** - * 指定默认的数据表名(不含前缀) - * @access public - * @param string $name - * @return $this - */ - public function name($name) - { - $this->name = $name; - return $this; - } - - /** - * 指定默认数据表名(含前缀) - * @access public - * @param string $table 表名 - * @return $this - */ - public function setTable($table) - { - $this->table = $table; - return $this; - } - - /** - * 得到当前的数据表 - * @access public - * @param string $name - * @return string - */ - public function getTable($name = '') - { - if ($name || empty($this->table)) { - $name = $name ?: $this->name; - $tableName = $this->connection->getConfig('prefix'); - if ($name) { - $tableName .= Loader::parseName($name); - } - } else { - $tableName = $this->table; - } - return $tableName; - } - /** * 指定当前操作的数据表 * @access public From 67500bc3c95f86e016f39893343266280c5a1182 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 18:46:09 +0800 Subject: [PATCH 073/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E8=87=AA=E5=8A=A8=E6=97=B6=E9=97=B4=E6=88=B3=E5=86=99?= =?UTF-8?q?=E5=85=A5=E8=AE=BE=E7=BD=AE=20=E6=97=B6=E9=97=B4=E6=88=B3?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=86=99=E5=85=A5=20=E5=92=8C=20=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E8=87=AA=E5=8A=A8=E5=AE=8C=E6=88=90=20=E5=88=86?= =?UTF-8?q?=E5=BC=80=20=EF=BC=8C=E5=B9=B6=E4=B8=94=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=8D=95=E7=8B=AC=E5=85=B3=E9=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 2179920d..b0a2e28b 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -59,11 +59,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $insert = []; // 更新自动完成列表 protected $update = []; - // 自动写入的时间戳字段列表 - protected $autoTimeField = ['create_time', 'update_time', 'delete_time']; + // 是否需要自动写入时间戳 + protected $autoWriteTimestamp = true; + // 创建时间字段 + protected $createTime = 'create_time'; + // 更新时间字段 + protected $updateTime = 'update_time'; + // 删除时间字段 + protected $deleteTime = 'delete_time'; // 时间字段取出后的默认时间格式 protected $dateFormat = 'Y-m-d H:i:s'; - // 字段类型或者格式转换 protected $type = []; // 是否为更新数据 @@ -286,6 +291,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 数据自动完成 $this->autoCompleteData($this->auto); + // 自动写入更新时间 + if ($this->autoWriteTimestamp) { + $this->__set($this->updateTime, null); + } + // 事件回调 if (false === $this->trigger('before_write', $this)) { return false; @@ -295,6 +305,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if ($this->isUpdate) { // 自动更新 $this->autoCompleteData($this->update); + // 事件回调 if (false === $this->trigger('before_update', $this)) { return false; @@ -327,6 +338,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 自动写入 $this->autoCompleteData($this->insert); + // 自动写入创建时间 + if ($this->autoWriteTimestamp) { + $this->__set($this->createTime, null); + } + if (false === $this->trigger('before_insert', $this)) { return false; } @@ -411,11 +427,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = null; } if (!in_array($field, $this->change)) { - if (in_array($field, $this->autoTimeField)) { - $this->__set($field, $value); - } else { - $this->__set($field, isset($this->data[$field]) ? $this->data[$field] : $value); - } + $this->__set($field, isset($this->data[$field]) ? $this->data[$field] : $value); } } } @@ -916,7 +928,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 获取字段类型信息并缓存 $this->fieldType = self::db()->getTableInfo('', 'type'); } - if (is_null($value) && in_array($name, $this->autoTimeField)) { + if (is_null($value) && $this->autoWriteTimestamp && in_array($name, [$this->createTime, $this->updateTime, $this->deleteTime])) { // 自动写入的时间戳字段 if (isset($this->type[$name])) { $type = $this->type[$name]; From b4d90ade7ae559fc98f61b735a9bab243300291a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 22:33:59 +0800 Subject: [PATCH 074/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84db=E6=96=B9=E6=B3=95=20=E5=B9=B6=E5=A2=9E=E5=8A=A0quer?= =?UTF-8?q?y=E5=B1=9E=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 78 ++++++++++++++++++-------------- library/think/model/Merge.php | 51 +++++++++++++-------- library/think/model/Relation.php | 2 +- 3 files changed, 75 insertions(+), 56 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index b0a2e28b..7d5455b8 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -34,6 +34,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $name; // 数据表名称 protected $table; + // 查询对象 + protected $query; // 回调事件 protected static $event = []; @@ -99,10 +101,14 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } else { $this->data = $data; } + if (empty($this->name)) { $this->name = basename(str_replace('\\', '/', get_class($this))); } + // 当前模型的查询对象 + $this->query = $this->db(); + // 执行初始化操作 $this->initialize(); } @@ -233,7 +239,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function getPk($table = '') { if (empty($this->pk)) { - $this->pk = self::db()->getTableInfo($table, 'pk'); + $this->pk = $this->query->getTableInfo($table, 'pk'); } return $this->pk; } @@ -301,7 +307,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return false; } - $db = self::db(); if ($this->isUpdate) { // 自动更新 $this->autoCompleteData($this->update); @@ -330,7 +335,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } } - $result = $db->where($where)->update($data); + $result = $this->query->where($where)->update($data); // 更新回调 $this->trigger('after_update', $this); @@ -347,11 +352,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return false; } - $result = $db->insert($this->data); + $result = $this->query->insert($this->data); // 获取自动增长主键 if ($result && $getId) { - $insertId = $db->getLastInsID(); + $insertId = $this->query->getLastInsID(); $pk = $this->getPk(); if (is_string($pk) && $insertId) { $this->data[$pk] = $insertId; @@ -443,7 +448,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return false; } - $result = self::db()->delete($this->data); + $result = $this->query->delete($this->data); $this->trigger('after_delete', $this); return $result; @@ -648,15 +653,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public static function destroy($data) { - $db = self::db(); + $model = new static(); + $query = $model->db(); if (is_array($data) && key($data) !== 0) { - $db->where($data); + $query->where($data); $data = []; } elseif ($data instanceof \Closure) { - call_user_func_array($data, [ & $db]); + call_user_func_array($data, [ & $query]); $data = []; } - $resultSet = $db->select($data); + $resultSet = $query->select($data); $result = false; if ($resultSet) { foreach ($resultSet as $data) { @@ -676,9 +682,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public static function scope($name, $params = []) { $model = new static(); - $class = self::db(); + $query = $model->db(); if ($name instanceof \Closure) { - call_user_func_array($name, [ & $class, $params]); + call_user_func_array($name, [ & $query, $params]); } elseif ($name instanceof Query) { return $name; } else { @@ -686,7 +692,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess foreach ($names as $scope) { $method = 'scope' . $scope; if (method_exists($model, $method)) { - $model->$method($class, $params); + $model->$method($query, $params); } } } @@ -704,10 +710,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public static function has($relation, $operator = '>=', $count = 1, $id = '*') { - $class = new static(); - $info = $class->$relation()->getRelationInfo(); + $model = new static(); + $info = $model->$relation()->getRelationInfo(); $table = $info['model']::getTable(); - return self::db()->alias('a') + return $model->db()->alias('a') ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey']) ->group('b.' . $info['foreignKey']) ->having('count(' . $id . ')' . $operator . $count); @@ -722,8 +728,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public static function hasWhere($relation, $where = []) { - $class = new static(); - $info = $class->$relation()->getRelationInfo(); + $model = new static(); + $info = $model->$relation()->getRelationInfo(); $table = $info['model']::getTable(); if (is_array($where)) { foreach ($where as $key => $val) { @@ -733,7 +739,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } } } - return self::db()->alias('a') + return $model->db()->alias('a') ->field('a.*') ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey']) ->where($where); @@ -870,28 +876,25 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } /** - * 初始化数据库对象 - * @access protected + * 获取当前模型的数据库查询对象 + * @access public * @return \think\db\Query */ - protected static function db() + public function db() { $model = get_called_class(); if (!isset(self::$links[$model])) { - $class = new static(); - // 设置当前模型 确保查询返回模型对象 - self::$links[$model] = Db::connect($class->connection)->model($model); + $query = Db::connect($this->connection)->model($model); // 设置当前数据表和模型名 - if (!empty($class->table)) { - self::$links[$model]->setTable($class->table); + if (!empty($this->table)) { + $query->setTable($this->table); } else { - $name = !empty($class->name) ? $class->name : basename(str_replace('\\', '/', $model)); - self::$links[$model]->name($name); + $query->name($this->name); } + self::$links[$model] = $query; } - // 返回当前模型的数据库查询对象 return self::$links[$model]; } @@ -901,18 +904,23 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (method_exists($this, 'scope' . $method)) { // 动态调用命名范围 $method = 'scope' . $method; - $class = self::db(); - array_unshift($args, $class); + array_unshift($args, $this->query); call_user_func_array([$this, $method], $args); return $this; } else { - return call_user_func_array([self::db(), $method], $args); + return call_user_func_array([$this->query, $method], $args); } } public static function __callStatic($method, $params) { - return call_user_func_array([self::db(), $method], $params); + $model = get_called_class(); + if (!isset(self::$links[$model])) { + $class = new static(); + self::$links[$model] = $class->db(); + } + $query = self::$links[$model]; + return call_user_func_array([$query, $method], $params); } /** @@ -926,7 +934,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess { if (is_null($this->fieldType)) { // 获取字段类型信息并缓存 - $this->fieldType = self::db()->getTableInfo('', 'type'); + $this->fieldType = $this->query->getTableInfo('', 'type'); } if (is_null($value) && $this->autoWriteTimestamp && in_array($name, [$this->createTime, $this->updateTime, $this->deleteTime])) { // 自动写入的时间戳字段 diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 05918fac..f21931a8 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -61,14 +61,14 @@ class Merge extends Model { $class = new static(); $master = $class->name; - $fields = self::getModelField($master, '', $class->mapFields); + $fields = self::getModelField($query, $master, '', $class->mapFields); $query->alias($master)->field($fields); foreach (static::$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($name, $table, $class->mapFields); + $fields = self::getModelField($query, $name, $table, $class->mapFields); $query->field($fields); } return $query; @@ -77,15 +77,16 @@ class Merge extends Model /** * 获取关联模型的字段 并解决混淆 * @access protected + * @param \think\db\Query $query 查询对象 * @param string $name 模型名称 * @param string $table 关联表名称 * @param array $map 字段映射 * @return array */ - protected static function getModelField($name, $table = '', $map = []) + protected static function getModelField($query, $name, $table = '', $map = []) { // 获取模型的字段信息 - $fields = self::db()->getTableInfo($table, 'fields'); + $fields = $query->getTableInfo($table, 'fields'); $array = []; foreach ($fields as $field) { if ($key = array_search($name . '.' . $field, $map)) { @@ -163,11 +164,16 @@ class Merge extends Model } // 数据自动完成 $this->autoCompleteData($this->auto); + + // 自动写入更新时间 + if ($this->autoWriteTimestamp) { + $this->__set($this->updateTime, null); + } + // 处理模型数据 $data = $this->parseData($this->name, $this->data); - $db = self::db(); - $db->startTrans('merge_save_' . $this->name); + $this->query->startTrans('merge_save_' . $this->name); try { if ($this->isUpdate) { // 自动写入 @@ -178,15 +184,15 @@ class Merge extends Model } // 写入主表数据 - $result = $db->strict(false)->update($data); + $result = $this->query->strict(false)->update($data); // 写入附表数据 foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? $db->getTable($model) : $model; + $table = is_int($key) ? $this->query->getTable($model) : $model; // 处理关联模型数据 $data = $this->parseData($name, $this->data); - $query = clone $db; + $query = clone $this->query; $query->table($table)->strict(false)->where($this->fk, $this->data[$this->getPk()])->update($data); } // 新增回调 @@ -195,6 +201,11 @@ class Merge extends Model // 自动写入 $this->autoCompleteData($this->insert); + // 自动写入创建时间 + if ($this->autoWriteTimestamp) { + $this->__set($this->createTime, null); + } + if (false === $this->trigger('before_insert', $this)) { return false; } @@ -209,10 +220,10 @@ class Merge extends Model // 写入附表数据 foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? $db->getTable($model) : $model; + $table = is_int($key) ? $this->query->getTable($model) : $model; // 处理关联模型数据 $data = $this->parseData($name, $this->data, true); - $query = clone $db; + $query = clone $this->query; $query->table($table)->strict(false)->insert($data); } $result = $insertId; @@ -220,10 +231,10 @@ class Merge extends Model // 新增回调 $this->trigger('after_insert', $this); } - $db->commit('merge_save_' . $this->name); + $this->query->commit('merge_save_' . $this->name); return $result; } catch (\PDOException $e) { - $db->rollback(); + $this->query->rollback(); return false; } } @@ -238,26 +249,26 @@ class Merge extends Model if (false === $this->trigger('before_delete', $this)) { return false; } - $db = self::db(); - $db->startTrans('merge_delete_' . $this->name); + + $this->query->startTrans('merge_delete_' . $this->name); try { - $result = $db->delete($this->data); + $result = $this->query->delete($this->data); if ($result) { // 获取主键数据 $pk = $this->data[$this->getPk()]; // 删除关联数据 foreach (static::$relationModel as $key => $model) { - $table = is_int($key) ? $db->getTable($model) : $model; - $query = clone $db; + $table = is_int($key) ? $this->query->getTable($model) : $model; + $query = clone $this->query; $query->table($table)->where($this->fk, $pk)->delete(); } } $this->trigger('after_delete', $this); - $db->commit('merge_delete_' . $this->name); + $this->query->commit('merge_delete_' . $this->name); return $result; } catch (\PDOException $e) { - $db->rollback(); + $this->query->rollback(); return false; } } diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index a2673237..65e066ab 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -593,7 +593,7 @@ class Relation { if ($this->model) { $model = new $this->model; - $db = $model::db(); + $db = $model->db(); if (self::HAS_MANY == $this->type && isset($this->parent->{$this->localKey})) { // 关联查询带入关联条件 $db->where($this->foreignKey, $this->parent->{$this->localKey}); From 7ff02c61cd1b427e757aa56eafe715c96375b566 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 18 May 2016 22:39:53 +0800 Subject: [PATCH 075/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 7d5455b8..11ad857b 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -893,6 +893,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } else { $query->name($this->name); } + self::$links[$model] = $query; } // 返回当前模型的数据库查询对象 @@ -916,8 +917,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess { $model = get_called_class(); if (!isset(self::$links[$model])) { - $class = new static(); - self::$links[$model] = $class->db(); + self::$links[$model] = (new static())->db(); } $query = self::$links[$model]; return call_user_func_array([$query, $method], $params); From 0fd61503a8e9b70689603652733958a06826464c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 10:48:50 +0800 Subject: [PATCH 076/670] =?UTF-8?q?=E5=8E=BB=E6=8E=89Model=E7=B1=BB?= =?UTF-8?q?=E7=9A=84query=E5=B1=9E=E6=80=A7=20=E9=81=BF=E5=85=8D=E5=BA=8F?= =?UTF-8?q?=E5=88=97=E5=8C=96=E5=87=BA=E9=97=AE=E9=A2=98=20=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E4=BD=BF=E7=94=A8$this->db()=20=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 27 +++++++++++++-------------- library/think/model/Merge.php | 30 ++++++++++++++++-------------- 2 files changed, 29 insertions(+), 28 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 11ad857b..184178a1 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -34,8 +34,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $name; // 数据表名称 protected $table; - // 查询对象 - protected $query; // 回调事件 protected static $event = []; @@ -102,12 +100,13 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->data = $data; } + // 当前类名 + $this->class = get_class($this); + if (empty($this->name)) { - $this->name = basename(str_replace('\\', '/', get_class($this))); + $this->name = basename(str_replace('\\', '/', $this->class)); } - // 当前模型的查询对象 - $this->query = $this->db(); // 执行初始化操作 $this->initialize(); } @@ -239,7 +238,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function getPk($table = '') { if (empty($this->pk)) { - $this->pk = $this->query->getTableInfo($table, 'pk'); + $this->pk = $this->db()->getTableInfo($table, 'pk'); } return $this->pk; } @@ -335,7 +334,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } } - $result = $this->query->where($where)->update($data); + $result = $this->db()->where($where)->update($data); // 更新回调 $this->trigger('after_update', $this); @@ -352,11 +351,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return false; } - $result = $this->query->insert($this->data); + $result = $this->db()->insert($this->data); // 获取自动增长主键 if ($result && $getId) { - $insertId = $this->query->getLastInsID(); + $insertId = $this->db()->getLastInsID(); $pk = $this->getPk(); if (is_string($pk) && $insertId) { $this->data[$pk] = $insertId; @@ -448,7 +447,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return false; } - $result = $this->query->delete($this->data); + $result = $this->db()->delete($this->data); $this->trigger('after_delete', $this); return $result; @@ -882,7 +881,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function db() { - $model = get_called_class(); + $model = $this->class; if (!isset(self::$links[$model])) { // 设置当前模型 确保查询返回模型对象 $query = Db::connect($this->connection)->model($model); @@ -905,11 +904,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (method_exists($this, 'scope' . $method)) { // 动态调用命名范围 $method = 'scope' . $method; - array_unshift($args, $this->query); + array_unshift($args, $this->db()); call_user_func_array([$this, $method], $args); return $this; } else { - return call_user_func_array([$this->query, $method], $args); + return call_user_func_array([$this->db(), $method], $args); } } @@ -934,7 +933,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess { if (is_null($this->fieldType)) { // 获取字段类型信息并缓存 - $this->fieldType = $this->query->getTableInfo('', 'type'); + $this->fieldType = $this->db()->getTableInfo('', 'type'); } if (is_null($value) && $this->autoWriteTimestamp && in_array($name, [$this->createTime, $this->updateTime, $this->deleteTime])) { // 自动写入的时间戳字段 diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index f21931a8..66b11c85 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -173,7 +173,8 @@ class Merge extends Model // 处理模型数据 $data = $this->parseData($this->name, $this->data); - $this->query->startTrans('merge_save_' . $this->name); + $db = $this->db(); + $db->startTrans('merge_save_' . $this->name); try { if ($this->isUpdate) { // 自动写入 @@ -184,15 +185,15 @@ class Merge extends Model } // 写入主表数据 - $result = $this->query->strict(false)->update($data); + $result = $db->strict(false)->update($data); // 写入附表数据 foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? $this->query->getTable($model) : $model; + $table = is_int($key) ? $db->getTable($model) : $model; // 处理关联模型数据 $data = $this->parseData($name, $this->data); - $query = clone $this->query; + $query = clone $db; $query->table($table)->strict(false)->where($this->fk, $this->data[$this->getPk()])->update($data); } // 新增回调 @@ -220,10 +221,10 @@ class Merge extends Model // 写入附表数据 foreach (static::$relationModel as $key => $model) { $name = is_int($key) ? $model : $key; - $table = is_int($key) ? $this->query->getTable($model) : $model; + $table = is_int($key) ? $db->getTable($model) : $model; // 处理关联模型数据 $data = $this->parseData($name, $this->data, true); - $query = clone $this->query; + $query = clone $db; $query->table($table)->strict(false)->insert($data); } $result = $insertId; @@ -231,10 +232,10 @@ class Merge extends Model // 新增回调 $this->trigger('after_insert', $this); } - $this->query->commit('merge_save_' . $this->name); + $db->commit('merge_save_' . $this->name); return $result; } catch (\PDOException $e) { - $this->query->rollback(); + $db->rollback(); return false; } } @@ -250,25 +251,26 @@ class Merge extends Model return false; } - $this->query->startTrans('merge_delete_' . $this->name); + $db = $this->query; + $db->startTrans('merge_delete_' . $this->name); try { - $result = $this->query->delete($this->data); + $result = $db->delete($this->data); if ($result) { // 获取主键数据 $pk = $this->data[$this->getPk()]; // 删除关联数据 foreach (static::$relationModel as $key => $model) { - $table = is_int($key) ? $this->query->getTable($model) : $model; - $query = clone $this->query; + $table = is_int($key) ? $db->getTable($model) : $model; + $query = clone $db; $query->table($table)->where($this->fk, $pk)->delete(); } } $this->trigger('after_delete', $this); - $this->query->commit('merge_delete_' . $this->name); + $db->commit('merge_delete_' . $this->name); return $result; } catch (\PDOException $e) { - $this->query->rollback(); + $db->rollback(); return false; } } From 323d3e94165fa0113bac2a4608f6a8f5acc03005 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 11:36:25 +0800 Subject: [PATCH 077/670] =?UTF-8?q?Model=E7=B1=BB=E5=A2=9E=E5=8A=A0append?= =?UTF-8?q?=E5=B1=9E=E6=80=A7=E5=92=8Cappend=E6=96=B9=E6=B3=95=20=E7=94=A8?= =?UTF-8?q?=E4=BA=8Etoarray=E5=92=8Ctojson=E6=96=B9=E6=B3=95=E8=BE=93?= =?UTF-8?q?=E5=87=BA=E7=9A=84=E6=97=B6=E5=80=99=20=E9=99=84=E5=8A=A0?= =?UTF-8?q?=E9=A2=9D=E5=A4=96=E7=9A=84=E5=B1=9E=E6=80=A7=EF=BC=8C=E8=AF=A5?= =?UTF-8?q?=E5=B1=9E=E6=80=A7=E7=9A=84=E5=80=BC=E5=BF=85=E9=A1=BB=E9=80=9A?= =?UTF-8?q?=E8=BF=87=E8=8E=B7=E5=8F=96=E5=99=A8=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/library/think/Model.php b/library/think/Model.php index 184178a1..f765c0c8 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -48,6 +48,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $field = []; // 隐藏属性 protected $hidden = []; + // 追加属性 + protected $append = []; // 数据信息 protected $data = []; // 记录改变字段 @@ -174,6 +176,18 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return array_key_exists($name, $this->data) ? $this->data[$name] : $this->data; } + /** + * 设置需要追加的输出属性 + * @access public + * @param array $append 属性列表 + * @return $this + */ + public function append($append = []) + { + $this->append = $append; + return $this; + } + /** * 设置需要隐藏的属性 * @access public @@ -194,6 +208,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function toArray() { $item = []; + if (!empty($this->append)) { + foreach ($this->append as $name) { + $item[$name] = $this->__get($name); + } + } foreach ($this->data as $key => $val) { // 如果是隐藏属性不输出 if (in_array($key, $this->hidden)) { From 9c1d65addb53f727f1daf6f170a5fcc1a50e18ee Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 11:44:04 +0800 Subject: [PATCH 078/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/library/think/Model.php b/library/think/Model.php index f765c0c8..c13c6785 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -34,6 +34,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $name; // 数据表名称 protected $table; + // 当前类名称 + protected $class; // 回调事件 protected static $event = []; From 34a6285ba22d02de6be6528679dd3477d077d90c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 11:57:40 +0800 Subject: [PATCH 079/670] =?UTF-8?q?=E5=8F=96=E6=B6=88File=E7=B1=BB?= =?UTF-8?q?=E7=9A=84uniqid=E8=A7=84=E5=88=99=20=E6=94=B9=E4=B8=BA=E8=87=AA?= =?UTF-8?q?=E5=B7=B1=E4=BC=A0=E5=85=A5=E5=8D=B3=E5=8F=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/library/think/File.php b/library/think/File.php index c772d8c7..c691603f 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -123,9 +123,6 @@ class File extends SplFileObject $savename = call_user_func_array($this->rule, [$this]); } else { switch ($this->rule) { - case 'uniqid': - $savename = uniqid(); - break; case 'md5': $md5 = md5_file($this->getRealPath()); $savename = substr($md5, 0, 2) . DS . substr($md5, 2); From e151d70f62fdc3b07769dabbf7873084394a15fd Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 12:38:11 +0800 Subject: [PATCH 080/670] =?UTF-8?q?query=E7=B1=BB=E5=A2=9E=E5=8A=A0sequenc?= =?UTF-8?q?e=E6=96=B9=E6=B3=95=20=E7=94=A8=E4=BA=8E=E8=AE=BE=E7=BD=AE=20?= =?UTF-8?q?=E8=87=AA=E5=A2=9E=E5=BA=8F=E5=88=97=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 5 +++-- library/think/db/Query.php | 14 +++++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 22eebb89..dfa9ca49 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -367,11 +367,12 @@ abstract class Connection * @param array $bind 参数绑定 * @param boolean $fetch 不执行只是获取SQL * @param boolean $getLastInsID 是否获取自增ID + * @param string $sequence 自增序列名 * @return int * @throws DbBindParamException * @throws PDOException */ - public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false) + public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) { $this->initConnect(true); if (!$this->linkID) { @@ -403,7 +404,7 @@ abstract class Connection $this->numRows = $this->PDOStatement->rowCount(); if (preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $sql)) { - $this->lastInsID = $this->linkID->lastInsertId(); + $this->lastInsID = $this->linkID->lastInsertId($sequence); if ($getLastInsID) { return $this->lastInsID; } diff --git a/library/think/db/Query.php b/library/think/db/Query.php index f327f78d..8bc4ea7b 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1059,6 +1059,18 @@ class Query return $this; } + /** + * 设置自增序列名 + * @access public + * @param string $sequence 自增序列名 + * @return $this + */ + public function sequence($sequence = null) + { + $this->options['sequence'] = $sequence; + return $this; + } + /** * 获取数据表信息 * @access public @@ -1312,7 +1324,7 @@ class Query // 生成SQL语句 $sql = $this->builder()->insert($data, $options, $replace); // 执行操作 - return $this->execute($sql, $this->getBind(), $options['fetch_sql'], $getLastInsID); + return $this->execute($sql, $this->getBind(), $options['fetch_sql'], $getLastInsID, isset($options['sequence']) ? $options['sequence'] : null); } /** From efb65117adf81799996806d547c1feb8f97fd4a0 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 13:32:11 +0800 Subject: [PATCH 081/670] =?UTF-8?q?=E5=8E=BB=E6=8E=89Loader::autoload?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E7=9A=84=E6=97=A5=E5=BF=97=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 1 - 1 file changed, 1 deletion(-) diff --git a/library/think/Loader.php b/library/think/Loader.php index 89548650..8527db0e 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -80,7 +80,6 @@ class Loader APP_DEBUG && self::$load[] = $filename; include $filename; } else { - Log::record('autoloader error : ' . $filename, 'notice'); return false; } } From e5de35ed43c65964cfd485f88062953827a809e8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 13:36:10 +0800 Subject: [PATCH 082/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BResponse=E7=B1=BBcrea?= =?UTF-8?q?te=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E5=AD=90=E7=B1=BB=E7=9A=84=E5=91=BD=E5=90=8D=E7=A9=BA?= =?UTF-8?q?=E9=97=B4=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Response.php b/library/think/Response.php index d65d2a35..634a2d99 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -68,7 +68,7 @@ class Response { $type = strtolower($type ?: (IS_AJAX ? 'json' : 'html')); if (!isset(self::$instance[$type])) { - $class = '\\think\\response\\' . ucfirst($type); + $class = (isset($options['namespace']) ? $options['namespace'] : '\\think\\response\\') . ucfirst($type); if (class_exists($class)) { $response = new $class($data, $type, $options); } else { From 45d2962eb304ca5456daa3e6327fe865eef21cf8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 14:33:40 +0800 Subject: [PATCH 083/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3File=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/File.php b/library/think/File.php index c691603f..58af987e 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -91,7 +91,7 @@ class File extends SplFileObject $savename = $this->getSaveName($savename); // 检测目录 - if (false === $this->checkPath(dirname($path . $savname))) { + if (false === $this->checkPath(dirname($path . $savename))) { return false; } From 048ba672074b76ff49e5a57443c2f38ea3016895 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Thu, 19 May 2016 14:38:31 +0800 Subject: [PATCH 084/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=88=86=E9=A1=B5?= =?UTF-8?q?=E7=B1=BB=E8=87=AA=E5=8A=A8=E8=8E=B7=E5=8F=96=E5=BD=93=E5=89=8D?= =?UTF-8?q?url?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Paginator.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/library/think/Paginator.php b/library/think/Paginator.php index e891798f..e7f2372f 100644 --- a/library/think/Paginator.php +++ b/library/think/Paginator.php @@ -137,8 +137,7 @@ abstract class Paginator */ public static function getCurrentPath() { - //TODO 待Request类完善后这里再完善 - return '/' . $_SERVER['PATH_INFO']; + return Request::instance()->url(); } public function total() From 7a0d387e10d6050d33b49ed9514de19b078aad25 Mon Sep 17 00:00:00 2001 From: gjianbo Date: Thu, 19 May 2016 15:02:21 +0800 Subject: [PATCH 085/670] Update Query.php --- library/think/db/Query.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 8bc4ea7b..4b0d2a54 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -158,13 +158,14 @@ class Query * @param array $bind 参数绑定 * @param boolean $fetch 不执行只是获取SQL * @param boolean $getLastInsID 是否获取自增ID + * @param boolean $sequence 自增序列名 * @return int * @throws DbBindParamException * @throws PDOException */ - public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false) + public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false,$sequence = null) { - return $this->connection->execute($sql, $bind, $fetch, $getLastInsID); + return $this->connection->execute($sql, $bind, $fetch, $getLastInsID,$sequence); } /** From cc084267a59630a028949ae2db7fef5e681bc0a5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 15:15:46 +0800 Subject: [PATCH 086/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3File=E7=B1=BB=20?= =?UTF-8?q?=E6=94=B9=E8=BF=9BInput=E7=B1=BB=E7=9A=84file=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 21 ++++++++++++++++++- library/think/Input.php | 46 +++++++++++++++++++++++------------------ 2 files changed, 46 insertions(+), 21 deletions(-) diff --git a/library/think/File.php b/library/think/File.php index 58af987e..f5e5470d 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -23,6 +23,25 @@ class File extends SplFileObject // 文件上传命名规则 protected $rule = 'date'; + // 上传文件信息 + protected $info; + + public function __construct($filename, $info = []) + { + parent::__construct($filename); + $this->info = $info; + } + + /** + * 获取上传文件的信息 + * @param string $name + * @return array|string + */ + public function getInfo($name = '') + { + return isset($this->info[$name]) ? $this->info[$name] : $this->info; + } + /** * 检查目录是否可写 * @param string $path 目录 @@ -139,7 +158,7 @@ class File extends SplFileObject } } if (!strpos($savename, '.')) { - $savename .= '.' . $this->getExtension(); + $savename .= '.' . pathinfo($this->getInfo('name'), PATHINFO_EXTENSION); } } elseif ('' === $savename) { $savename = $this->getFilename(); diff --git a/library/think/Input.php b/library/think/Input.php index 5d37fedf..848be817 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -216,32 +216,38 @@ class Input { $files = $files ?: (isset($_FILES) ? $_FILES : []); if (!empty($files)) { + // 处理上传文件 + $array = []; + $n = 0; + foreach ($files as $key => $file) { + if (is_array($file['name'])) { + $keys = array_keys($file); + $count = count($file['name']); + for ($i = 0; $i < $count; $i++) { + $array[$n]['key'] = $key; + foreach ($keys as $_key) { + $array[$n][$_key] = $file[$_key][$i]; + } + $n++; + } + } else { + $array = $files; + break; + } + } + if ('' === $name) { // 获取全部文件 - $file = []; - foreach ($files as $name => $val) { + $item = []; + foreach ($array as $key => $val) { if (empty($val['tmp_name'])) { continue; } - if (is_array($val['tmp_name'])) { - foreach ($val['tmp_name'] as $item) { - $file[] = new File($item); - } - } else { - $file[] = new File($val['tmp_name']); - } - } - return $file; - } elseif (!empty($files[$name]['tmp_name'])) { - if (is_array($files[$name]['tmp_name'])) { - $file = []; - foreach ($files[$name]['tmp_name'] as $item) { - $file[] = new File($item); - } - return $file; - } else { - return new File($files[$name]['tmp_name']); + $item[$key] = new File($val['tmp_name'], $val); } + return $item; + } elseif (isset($array[$name])) { + return new File($array[$name]['tmp_name'], $array[$name]); } } return null; From 7eed63c2ee5d1d8403e7baf352765c9966bceed0 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 16:01:47 +0800 Subject: [PATCH 087/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E7=9A=84url=E7=9B=B8=E5=85=B3=E6=96=B9=E6=B3=95=20=EF=BC=88?= =?UTF-8?q?=E4=BB=8D=E9=9C=80=E5=AE=8C=E5=96=84=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 71 ++++++++++++++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 8 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index ef0edbfc..1377cb0c 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -31,6 +31,11 @@ class Request */ protected $baseUrl; + /** + * @var string 基础路径 + */ + protected $basePath; + /** * @var string 根目录 */ @@ -179,7 +184,7 @@ class Request } /** - * 获取当前URL + * 获取当前完整URL 包括QUERY_STRING * @access public * @param string $url URL地址 * @return string @@ -188,23 +193,53 @@ class Request { if (!empty($url)) { $this->url = $url; + } elseif ($this->url) { + return $this->url; } else { - return $this->url ?: $_SERVER[Config::get('url_request_uri')]; + $url = $this->scheme() . '://' . $this->host(); + $url .= $_SERVER[Config::get('url_request_uri')]; + $this->url = $url; + return $url; } } /** - * 获取基础URL + * 获取当前URL 不含QUERY_STRING * @access public * @param string $url URL地址 * @return string */ - public function baseUrl($url = '') + public function baeUrl($url = '') { if (!empty($url)) { $this->baseUrl = $url; + } elseif ($this->baseUrl) { + return $this->baseUrl; } else { - return $this->baseUrl ?: rtrim($_SERVER['SCRIPT_NAME'], '/'); + $url = $this->scheme() . '://' . $this->host(); + $url .= $_SERVER['PHP_SELF']; + $this->baseUrl = $url; + return $url; + } + } + + /** + * 获取URL基础路径 SCRIPT_NAME + * @access public + * @param string $url URL地址 + * @return string + */ + public function basePath($url = '') + { + if (!empty($url)) { + $this->basePath = $url; + } elseif ($this->basePath) { + return $this->basePath; + } else { + $url = $this->scheme() . '://' . $this->host(); + $url .= rtrim($_SERVER['SCRIPT_NAME'], '/'); + $this->basePath = $url; + return $url; } } @@ -218,12 +253,12 @@ class Request { if (!empty($url)) { $this->root = $url; - } elseif ($this->root) { return $this->root; } else { - $_root = rtrim(dirname($this->baseUrl()), '/'); - return ('/' == $_root || '\\' == $_root) ? '' : $_root; + $_root = rtrim(dirname($this->baseUrl()), '/'); + $this->root = ('/' == $_root || '\\' == $_root) ? '' : $_root; + return $this->root; } } @@ -589,6 +624,26 @@ class Request return $_SERVER['SERVER_PORT']; } + /** + * 当前请求 SERVER_PROTOCOL + * @access public + * @return integer + */ + public function protocol() + { + return $_SERVER['SERVER_PROTOCOL']; + } + + /** + * 当前请求 REMOTE_PORT + * @access public + * @return integer + */ + public function remotePort() + { + return $_SERVER['REMOTE_PORT']; + } + /** * 获取当前请求的路由 * @access public From c006e281cb9f963c664e9a590efd76908ab16286 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 16:06:35 +0800 Subject: [PATCH 088/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index 1377cb0c..f7aff0db 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -209,7 +209,7 @@ class Request * @param string $url URL地址 * @return string */ - public function baeUrl($url = '') + public function baseUrl($url = '') { if (!empty($url)) { $this->baseUrl = $url; From 8f17ad6c886bcc4d2d994dad5c67b372fbdf2190 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Thu, 19 May 2016 16:07:31 +0800 Subject: [PATCH 089/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Paginator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Paginator.php b/library/think/Paginator.php index e7f2372f..37433d35 100644 --- a/library/think/Paginator.php +++ b/library/think/Paginator.php @@ -137,7 +137,7 @@ abstract class Paginator */ public static function getCurrentPath() { - return Request::instance()->url(); + return Request::instance()->baseUrl(); } public function total() From 9a8b8d8a8d044cbead8e4e5dfc9a5f575a823701 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 16:57:05 +0800 Subject: [PATCH 090/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=9A=84baseU?= =?UTF-8?q?rl=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index f7aff0db..50c8707d 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -216,10 +216,8 @@ class Request } elseif ($this->baseUrl) { return $this->baseUrl; } else { - $url = $this->scheme() . '://' . $this->host(); - $url .= $_SERVER['PHP_SELF']; - $this->baseUrl = $url; - return $url; + $this->baseUrl = rtrim($this->url(), '?' . $this->query()); + return $this->baseUrl; } } From 681d5d223b172b6d4ad5b20a4ae33a596e6c37ed Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Thu, 19 May 2016 18:41:32 +0800 Subject: [PATCH 091/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index c13c6785..149c9e09 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -616,10 +616,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 查找单条记录 * @access public - * @param mixed $data 主键值或者查询条件(闭包) - * @param string $with 关联预查询 - * @param bool $cache 是否缓存 - * @return \think\Model + * @param mixed $data 主键值或者查询条件(闭包) + * @param array|string $with 关联预查询 + * @param bool $cache 是否缓存 + * @return static + * @throws exception\DbException */ public static function get($data = '', $with = [], $cache = false) { @@ -630,10 +631,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 查找所有记录 * @access public - * @param mixed $data 主键列表或者查询条件(闭包) - * @param string $with 关联预查询 - * @param bool $cache 是否缓存 - * @return array|false|string + * @param mixed $data 主键列表或者查询条件(闭包) + * @param array|string $with 关联预查询 + * @param bool $cache 是否缓存 + * @return static[]|false + * @throws exception\DbException */ public static function all($data = [], $with = [], $cache = false) { From 40d4bfe4da2ac8381c950b9f00c5ab1be566a631 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 18:42:20 +0800 Subject: [PATCH 092/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BBbaseU?= =?UTF-8?q?rl=E5=92=8CbasePath=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 50c8707d..8f1b6d2b 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -234,10 +234,20 @@ class Request } elseif ($this->basePath) { return $this->basePath; } else { - $url = $this->scheme() . '://' . $this->host(); - $url .= rtrim($_SERVER['SCRIPT_NAME'], '/'); - $this->basePath = $url; - return $url; + $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'])); + } + $this->basePath = $this->scheme() . '://' . $this->host() . $url; + return $this->basePath; } } @@ -254,8 +264,7 @@ class Request } elseif ($this->root) { return $this->root; } else { - $_root = rtrim(dirname($this->baseUrl()), '/'); - $this->root = ('/' == $_root || '\\' == $_root) ? '' : $_root; + $this->root = rtrim(str_replace('\\', '/', dirname($this->basePath())), '/'); return $this->root; } } From 6c294b58fc15a5354ba26226746ff3e4c9f8e2bf Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 19 May 2016 22:14:56 +0800 Subject: [PATCH 093/670] =?UTF-8?q?Model=E7=B1=BBdestroy=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E6=88=90=E5=8A=9F=E5=88=A0=E9=99=A4=E7=9A=84?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 149c9e09..ca0cd63a 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -671,7 +671,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * 删除记录 * @access public * @param mixed $data 主键列表 支持闭包查询条件 - * @return integer + * @return integer 成功删除的记录数 */ public static function destroy($data) { @@ -685,13 +685,14 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $data = []; } $resultSet = $query->select($data); - $result = false; + $count = 0; if ($resultSet) { foreach ($resultSet as $data) { $result = $data->delete(); + $count += $result; } } - return $result; + return $count; } /** From 97e12c1a8ad475e0946d8e2db0254f4a202b2174 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 10:28:45 +0800 Subject: [PATCH 094/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BSocket=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/Socket.php | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/library/think/log/driver/Socket.php b/library/think/log/driver/Socket.php index 88c34033..cd27086c 100644 --- a/library/think/log/driver/Socket.php +++ b/library/think/log/driver/Socket.php @@ -40,7 +40,7 @@ class Socket 'big' => 'font-size:20px;color:red;', ]; - protected $_allowForceClientIds = []; //配置强制推送且被授权的client_id + protected $allowForceClientIds = []; //配置强制推送且被授权的client_id /** * 架构函数 @@ -52,10 +52,6 @@ class Socket if (!empty($config)) { $this->config = array_merge($this->config, $config); } - if (isset($this->config['allow_client_id'])) { - //兼容旧配置 - $this->allow_client_ids = array_merge($this->allow_client_ids, [$this->config['allow_client_id']]); - } } /** @@ -120,9 +116,9 @@ class Socket $client_id = ''; } - if (!empty($this->_allowForceClientIds)) { + if (!empty($this->allowForceClientIds)) { //强制推送到多个client_id - foreach ($this->_allowForceClientIds as $force_client_id) { + foreach ($this->allowForceClientIds as $force_client_id) { $client_id = $force_client_id; $this->sendToClient($tabid, $client_id, $logs, $force_client_id); } @@ -142,12 +138,12 @@ class Socket */ protected function sendToClient($tabid, $client_id, $logs, $force_client_id) { - $logs = array( + $logs = [ 'tabid' => $tabid, 'client_id' => $client_id, '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); @@ -167,8 +163,8 @@ class Socket $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']); - if (!$tabid && count($this->_allowForceClientIds)) { + $this->allowForceClientIds = array_intersect($allow_client_ids, $this->config['force_client_ids']); + if (!$tabid && count($this->allowForceClientIds)) { return true; } @@ -177,7 +173,7 @@ class Socket return false; } } else { - $this->_allowForceClientIds = $this->config['force_client_ids']; + $this->allowForceClientIds = $this->config['force_client_ids']; } return true; } From 6dd393bd711043393751e977064def2393362522 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 11:10:20 +0800 Subject: [PATCH 095/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84insertGetId=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E4=BC=A0=E5=85=A5=E8=87=AA=E5=A2=9E=E5=BA=8F=E5=88=97=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 4b0d2a54..bf52b988 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -163,9 +163,9 @@ class Query * @throws DbBindParamException * @throws PDOException */ - public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false,$sequence = null) + public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) { - return $this->connection->execute($sql, $bind, $fetch, $getLastInsID,$sequence); + return $this->connection->execute($sql, $bind, $fetch, $getLastInsID, $sequence); } /** @@ -1333,11 +1333,12 @@ class Query * @access public * @param mixed $data 数据 * @param boolean $replace 是否replace + * @param string $sequence 自增序列名 * @return integer */ - public function insertGetId(array $data, $replace = false) + public function insertGetId(array $data, $replace = false, $sequence = null) { - return $this->insert($data, $replace, true); + return $this->insert($data, $replace, true, $sequence); } /** From 952d18af1703916a49d3f7b67d3d37a89840c0bb Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 11:27:21 +0800 Subject: [PATCH 096/670] =?UTF-8?q?=E8=A7=86=E5=9B=BE=E9=A9=B1=E5=8A=A8?= =?UTF-8?q?=E7=B1=BB=E5=A2=9E=E5=8A=A0exists=E6=96=B9=E6=B3=95=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E5=88=A4=E6=96=AD=E6=A8=A1=E6=9D=BF=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E5=AD=98=E5=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/view/driver/Php.php | 21 ++++++++++++++++----- library/think/view/driver/Think.php | 21 ++++++++++++++++----- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index 0b6edbac..b22d4612 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -31,6 +31,21 @@ class Php $this->config = array_merge($this->config, $config); } + /** + * 检测是否存在模板文件 + * @access public + * @param string $template 模板文件或者模板规则 + * @return bool + */ + public function exists($template) + { + if (!is_file($template)) { + // 获取模板文件名 + $template = $this->parseTemplate($template); + } + return is_file($template); + } + /** * 渲染模板文件 * @access public @@ -40,12 +55,8 @@ class Php */ public function fetch($template, $data = []) { - if (!is_file($template)) { - // 获取模板文件名 - $template = $this->parseTemplate($template); - } // 模板不存在 抛出异常 - if (!is_file($template)) { + if (!$this->exists($template)) { throw new Exception('template file not exists:' . $template, 10700); } // 记录视图信息 diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 6867b855..9ee07b26 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -40,6 +40,21 @@ class Think $this->template = new Template($this->config); } + /** + * 检测是否存在模板文件 + * @access public + * @param string $template 模板文件或者模板规则 + * @return bool + */ + public function exists($template) + { + if (!is_file($template)) { + // 获取模板文件名 + $template = $this->parseTemplate($template); + } + return is_file($template); + } + /** * 渲染模板文件 * @access public @@ -50,12 +65,8 @@ class Think */ public function fetch($template, $data = [], $config = []) { - if (!is_file($template)) { - // 获取模板文件名 - $template = $this->parseTemplate($template); - } // 模板不存在 抛出异常 - if (!is_file($template)) { + if (!$this->exists($template)) { throw new Exception('template file not exists:' . $template, 10700); } // 记录视图信息 From 685d7ef3b7e9ec20759ae86b762126378ea66d86 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 12:01:38 +0800 Subject: [PATCH 097/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E8=A7=86=E5=9B=BE?= =?UTF-8?q?=E9=A9=B1=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/view/driver/Php.php | 3 ++- library/think/view/driver/Think.php | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index b22d4612..9b74d1df 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -56,7 +56,8 @@ class Php public function fetch($template, $data = []) { // 模板不存在 抛出异常 - if (!$this->exists($template)) { + $template = $this->exists($template); + if (!$template) { throw new Exception('template file not exists:' . $template, 10700); } // 记录视图信息 diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 9ee07b26..1b35ed41 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -52,7 +52,7 @@ class Think // 获取模板文件名 $template = $this->parseTemplate($template); } - return is_file($template); + return is_file($template) ? $template : false; } /** @@ -66,7 +66,8 @@ class Think public function fetch($template, $data = [], $config = []) { // 模板不存在 抛出异常 - if (!$this->exists($template)) { + $template = $this->exists($template); + if (!$template) { throw new Exception('template file not exists:' . $template, 10700); } // 记录视图信息 From 626d0a26746c6f4186d02d8186592bdcf1d87327 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 14:11:13 +0800 Subject: [PATCH 098/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E5=92=8CUrl?= =?UTF-8?q?=E7=B1=BB=20=E5=8E=BB=E6=8E=89base=5Furl=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 4 +-- library/think/Request.php | 73 ++++++++++++++++++++++++--------------- library/think/Url.php | 2 +- 3 files changed, 47 insertions(+), 32 deletions(-) diff --git a/convention.php b/convention.php index 55f2d50b..353fbc3a 100644 --- a/convention.php +++ b/convention.php @@ -63,8 +63,6 @@ return [ 'pathinfo_depr' => '/', // 获取当前页面地址的系统变量 默认为REQUEST_URI 'url_request_uri' => 'REQUEST_URI', - // 基础URL路径 - 'base_url' => $_SERVER["SCRIPT_NAME"], // URL伪静态后缀 'url_html_suffix' => '.html', // URL普通方式参数 用于自动生成 @@ -211,7 +209,7 @@ return [ 'paginate' => [ 'type' => 'bootstrap', 'var_page' => 'page', - 'list_rows' => 15 + 'list_rows' => 15, ], ]; diff --git a/library/think/Request.php b/library/think/Request.php index 8f1b6d2b..e7c29c72 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -21,6 +21,11 @@ class Request */ protected static $instance; + /** + * @var string 域名 + */ + protected $domain; + /** * @var string URL地址 */ @@ -32,9 +37,9 @@ class Request protected $baseUrl; /** - * @var string 基础路径 + * @var string 当前执行的文件 */ - protected $basePath; + protected $baseFile; /** * @var string 根目录 @@ -183,24 +188,39 @@ class Request return new self($options); } + /** + * 获取当前包含协议的域名 + * @access public + * @param string $url URL地址 + * @return string + */ + public function domain($domain = '') + { + if (!empty($domain)) { + $this->domain = $domain; + return; + } elseif (!$this->domain) { + $this->domain = $this->scheme() . '://' . $this->host(); + } + return $this->domain; + } + /** * 获取当前完整URL 包括QUERY_STRING * @access public * @param string $url URL地址 + * @param bool $domain 是否需要域名 * @return string */ public function url($url = '') { if (!empty($url)) { $this->url = $url; - } elseif ($this->url) { - return $this->url; - } else { - $url = $this->scheme() . '://' . $this->host(); - $url .= $_SERVER[Config::get('url_request_uri')]; - $this->url = $url; - return $url; + return; + } elseif (!$this->url) { + $this->url = $_SERVER[Config::get('url_request_uri')]; } + return true === $url ? $this->domain() . $this->url : $this->url; } /** @@ -213,27 +233,25 @@ class Request { if (!empty($url)) { $this->baseUrl = $url; - } elseif ($this->baseUrl) { - return $this->baseUrl; - } else { + return; + } elseif (!$this->baseUrl) { $this->baseUrl = rtrim($this->url(), '?' . $this->query()); - return $this->baseUrl; } + return true === $url ? $this->domain() . $this->baseUrl : $this->baseUrl; } /** - * 获取URL基础路径 SCRIPT_NAME + * 获取当前执行的文件 SCRIPT_NAME * @access public - * @param string $url URL地址 + * @param string $file 当前执行的文件 * @return string */ - public function basePath($url = '') + public function baseFile($file = '') { - if (!empty($url)) { - $this->basePath = $url; - } elseif ($this->basePath) { - return $this->basePath; - } else { + if (!empty($file)) { + $this->baseFile = $file; + return; + } elseif (!$this->baseFile) { $script_name = basename($_SERVER['SCRIPT_FILENAME']); if (basename($_SERVER['SCRIPT_NAME']) === $script_name) { $url = $_SERVER['SCRIPT_NAME']; @@ -246,9 +264,9 @@ class Request } elseif (isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['DOCUMENT_ROOT']) === 0) { $url = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME'])); } - $this->basePath = $this->scheme() . '://' . $this->host() . $url; - return $this->basePath; + $this->baseFile = $url; } + return true === $file ? $this->domain() . $this->baseFile : $this->baseFile; } /** @@ -261,12 +279,11 @@ class Request { if (!empty($url)) { $this->root = $url; - } elseif ($this->root) { - return $this->root; - } else { - $this->root = rtrim(str_replace('\\', '/', dirname($this->basePath())), '/'); - return $this->root; + return; + } elseif (!$this->root) { + $this->root = rtrim(str_replace('\\', '/', dirname($this->baseFile())), '/'); } + return true === $url ? $this->domain() . $this->root : $this->root; } /** diff --git a/library/think/Url.php b/library/think/Url.php index 2987dc44..bd895c25 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -107,7 +107,7 @@ class Url // 检测域名 $domain = self::parseDomain($url, $domain); // URL组装 - $url = $domain . Config::get('base_url') . '/' . ltrim($url, '/'); + $url = $domain . Request::instance()->root() . '/' . ltrim($url, '/'); return $url; } From 82eb899990dfd8be3090b3fcab647a8bacd0c0c6 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 14:26:32 +0800 Subject: [PATCH 099/670] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E5=90=8E=E7=BC=80?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E4=B8=BA=E4=B8=8D=E5=B8=A6=E7=82=B9=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 4 ++-- library/think/Template.php | 13 +++++++------ library/think/view/driver/Php.php | 4 ++-- library/think/view/driver/Think.php | 4 ++-- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/convention.php b/convention.php index 353fbc3a..fda103a3 100644 --- a/convention.php +++ b/convention.php @@ -64,7 +64,7 @@ return [ // 获取当前页面地址的系统变量 默认为REQUEST_URI 'url_request_uri' => 'REQUEST_URI', // URL伪静态后缀 - 'url_html_suffix' => '.html', + 'url_html_suffix' => 'html', // URL普通方式参数 用于自动生成 'url_common_param' => false, //url禁止访问的后缀 @@ -94,7 +94,7 @@ return [ // 模板路径 'view_path' => '', // 模板后缀 - 'view_suffix' => '.html', + 'view_suffix' => 'html', // 模板文件名分隔符 'view_depr' => DS, // 模板引擎普通标签开始标记 diff --git a/library/think/Template.php b/library/think/Template.php index 3124e755..eb721036 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -23,9 +23,9 @@ class Template // 引擎配置 protected $config = [ 'view_path' => '', // 模板路径 - 'view_suffix' => '.html', // 默认模板文件后缀 + 'view_suffix' => 'html', // 默认模板文件后缀 'view_depr' => DS, - 'cache_suffix' => '.php', // 默认模板缓存后缀 + 'cache_suffix' => 'php', // 默认模板缓存后缀 'tpl_deny_func_list' => 'echo,exit', // 模板引擎禁用函数 'tpl_deny_php' => false, // 默认模板引擎是否禁用PHP原生代码 'tpl_begin' => '{', // 模板引擎普通标签开始标记 @@ -179,7 +179,7 @@ class Template } $template = $this->parseTemplateFile($template); if ($template) { - $cacheFile = $this->config['cache_path'] . $this->config['cache_prefix'] . md5($template) . $this->config['cache_suffix']; + $cacheFile = $this->config['cache_path'] . $this->config['cache_prefix'] . md5($template) . '.' . ltrim($this->config['cache_suffix'], '.'); if (!$this->checkCache($cacheFile)) { // 缓存无效 重新模板编译 $content = file_get_contents($template); @@ -216,7 +216,7 @@ class Template if ($config) { $this->config($config); } - $cacheFile = $this->config['cache_path'] . $this->config['cache_prefix'] . md5($content) . $this->config['cache_suffix']; + $cacheFile = $this->config['cache_path'] . $this->config['cache_prefix'] . md5($content) . '.' . ltrim($this->config['cache_suffix'], '.'); if (!$this->checkCache($cacheFile)) { // 缓存无效 模板编译 $this->compiler($content, $cacheFile); @@ -1051,11 +1051,12 @@ class Template if (strpos($template, '@')) { // 跨模块调用模板 $template = str_replace(['/', ':'], $this->config['view_depr'], $template); - $template = APP_PATH . str_replace('@', '/' . basename($this->config['view_path']) . '/', $template) . $this->config['view_suffix']; + $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 . $this->config['view_suffix']; + $template = $this->config['view_path'] . $template; } + $template .= '.' . ltrim($this->config['view_suffix'], '.'); } if (is_file($template)) { // 记录模板文件的更新时间 diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index 9b74d1df..9ab33119 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -21,7 +21,7 @@ class Php // 模板起始路径 'view_path' => '', // 模板文件后缀 - 'view_suffix' => '.php', + 'view_suffix' => 'php', // 模板文件名分隔符 'view_depr' => DS, ]; @@ -109,7 +109,7 @@ class Php $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . $template; } } - return $path . $template . $this->config['view_suffix']; + return $path . $template . '.' . ltrim($this->config['view_suffix'], '.'); } } diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 1b35ed41..ac7a84b0 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -24,7 +24,7 @@ class Think // 模板起始路径 'view_path' => '', // 模板文件后缀 - 'view_suffix' => '.html', + 'view_suffix' => 'html', // 模板文件名分隔符 'view_depr' => DS, // 是否开启模板编译缓存,设为false则每次都会重新编译 @@ -114,7 +114,7 @@ class Think $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . $template; } } - return $path . $template . $this->config['view_suffix']; + return $path . $template . '.' . ltrim($this->config['view_suffix'], '.'); } public function __call($method, $params) From 92496f65a141160995f4eb50fcfb551feb99e035 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 14:47:20 +0800 Subject: [PATCH 100/670] =?UTF-8?q?Query=E7=B1=BB=E5=A2=9E=E5=8A=A0getlast?= =?UTF-8?q?sql=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 +- library/think/db/Query.php | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index e7c29c72..a261594e 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -270,7 +270,7 @@ class Request } /** - * 获取URL访问根目录 + * 获取URL访问根地址 * @access public * @param string $url URL地址 * @return string diff --git a/library/think/db/Query.php b/library/think/db/Query.php index bf52b988..476bf7bc 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -178,6 +178,16 @@ class Query return $this->connection->getLastInsID(); } + /** + * 获取最近一次查询的sql语句 + * @access public + * @return string + */ + public function getLastSql() + { + return $this->connection->queryStr; + } + /** * 执行数据库事务 * @access public From d4993fa37c1cadd5a47d0f2ebe45fe3143e75d14 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 15:52:32 +0800 Subject: [PATCH 101/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Model=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AE=B5=E7=B1=BB=E5=9E=8B=E8=8E=B7=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index ca0cd63a..e51c44f4 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -955,7 +955,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function __set($name, $value) { - if (is_null($this->fieldType)) { + if (empty($this->fieldType)) { // 获取字段类型信息并缓存 $this->fieldType = $this->db()->getTableInfo('', 'type'); } From 1ad2f7af3132f093474a77027ed01dbb9341e80b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 16:14:22 +0800 Subject: [PATCH 102/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index a261594e..20e93e3b 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -218,7 +218,11 @@ class Request $this->url = $url; return; } elseif (!$this->url) { - $this->url = $_SERVER[Config::get('url_request_uri')]; + if (IS_CLI) { + $this->url = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : ''; + } else { + $this->url = $_SERVER[Config::get('url_request_uri')]; + } } return true === $url ? $this->domain() . $this->url : $this->url; } @@ -252,17 +256,20 @@ class Request $this->baseFile = $file; return; } elseif (!$this->baseFile) { - $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'])); + $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'])); + } } $this->baseFile = $url; } From b67e98ad2b2db16aa22e25454ec55eebf4c5ca96 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 16:28:25 +0800 Subject: [PATCH 103/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E7=9A=84root=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index 20e93e3b..d80e5983 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -288,7 +288,11 @@ class Request $this->root = $url; return; } elseif (!$this->root) { - $this->root = rtrim(str_replace('\\', '/', dirname($this->baseFile())), '/'); + $file = $this->baseFile(); + if (0 !== strpos($this->url(), $file)) { + $file = str_replace('\\', '/', dirname($file)); + } + $this->root = rtrim($file, '/'); } return true === $url ? $this->domain() . $this->root : $this->root; } From 34c80c1116effe13e78077c6d48b4d6b7fb0f826 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 16:30:28 +0800 Subject: [PATCH 104/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index d80e5983..3787d11a 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -289,7 +289,7 @@ class Request return; } elseif (!$this->root) { $file = $this->baseFile(); - if (0 !== strpos($this->url(), $file)) { + if ($file && 0 !== strpos($this->url(), $file)) { $file = str_replace('\\', '/', dirname($file)); } $this->root = rtrim($file, '/'); From 5f053e4aa7c1f3b5ece08caaa4696208c1049a55 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 16:43:34 +0800 Subject: [PATCH 105/670] =?UTF-8?q?Hook=E7=B1=BB=E7=9A=84=E8=A1=8C?= =?UTF-8?q?=E4=B8=BA=E6=B7=BB=E5=8A=A0=E6=94=AF=E6=8C=81=20=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1=E5=92=8C=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Hook.php | 14 ++++++++++---- library/think/Request.php | 2 +- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/library/think/Hook.php b/library/think/Hook.php index f5e55af4..9746f487 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -114,7 +114,7 @@ class Hook /** * 执行某个行为 - * @param string $class 行为类名称 + * @param mixed $class 要执行的行为 * @param string $tag 方法名(标签名) * @param Mixed $params 传人的参数 * @return mixed @@ -122,9 +122,15 @@ class Hook public static function exec($class, $tag = '', &$params = null) { if ($class instanceof \Closure) { - return $class($params); + $result = call_user_func_array($class, $params); + } elseif (is_object($class)) { + $result = call_user_func_array([$class, $tag], $params); + } elseif (is_array($class)) { + $result = call_user_func_array($class, $params); + } else { + $obj = new $class(); + $result = ($tag && is_callable([$obj, $tag])) ? $obj->$tag($params) : $obj->run($params); } - $obj = new $class(); - return ($tag && is_callable([$obj, $tag])) ? $obj->$tag($params) : $obj->run($params); + return $result; } } diff --git a/library/think/Request.php b/library/think/Request.php index 3787d11a..8427a4a5 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -42,7 +42,7 @@ class Request protected $baseFile; /** - * @var string 根目录 + * @var string 访问的ROOT地址 */ protected $root; From d9416c7e2d405341c5d810e118a9ac5d00fa438e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 16:49:28 +0800 Subject: [PATCH 106/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Hook.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/library/think/Hook.php b/library/think/Hook.php index 9746f487..7f5de18c 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -122,11 +122,9 @@ class Hook public static function exec($class, $tag = '', &$params = null) { if ($class instanceof \Closure) { - $result = call_user_func_array($class, $params); + $result = call_user_func_array($class, [$params]); } elseif (is_object($class)) { - $result = call_user_func_array([$class, $tag], $params); - } elseif (is_array($class)) { - $result = call_user_func_array($class, $params); + $result = call_user_func_array([$class, $tag], [$params]); } else { $obj = new $class(); $result = ($tag && is_callable([$obj, $tag])) ? $obj->$tag($params) : $obj->run($params); From a24a2155eb9f66fe7e585bba275170d2b7e67c7c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 16:59:26 +0800 Subject: [PATCH 107/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Hook=E7=B1=BB=20?= =?UTF-8?q?=E6=94=B9=E8=BF=9BTemplate=E5=AF=B9=E4=BA=8E=E5=B8=83=E5=B1=80?= =?UTF-8?q?=E7=9A=84=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Hook.php | 4 ++-- library/think/Template.php | 2 ++ tpl/dispatch_jump.tpl | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/library/think/Hook.php b/library/think/Hook.php index 7f5de18c..0ac83e85 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -122,9 +122,9 @@ class Hook public static function exec($class, $tag = '', &$params = null) { if ($class instanceof \Closure) { - $result = call_user_func_array($class, [$params]); + $result = call_user_func_array($class, [ & $params]); } elseif (is_object($class)) { - $result = call_user_func_array([$class, $tag], [$params]); + $result = call_user_func_array([$class, $tag], [ & $params]); } else { $obj = new $class(); $result = ($tag && is_callable([$obj, $tag])) ? $obj->$tag($params) : $obj->run($params); diff --git a/library/think/Template.php b/library/think/Template.php index eb721036..844448f4 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -329,6 +329,8 @@ class Template $content = str_replace($this->config['layout_item'], $content, file_get_contents($layoutFile)); } } + } else { + $content = str_replace('{__NOLAYOUT__}', '', $content); } // 模板解析 diff --git a/tpl/dispatch_jump.tpl b/tpl/dispatch_jump.tpl index 9b568fa1..18ee01bd 100644 --- a/tpl/dispatch_jump.tpl +++ b/tpl/dispatch_jump.tpl @@ -1,4 +1,4 @@ - +{__NOLAYOUT__} From 36a3bdc8752554778fe2a63738d58ea6cd8d8ca4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 17:13:27 +0800 Subject: [PATCH 108/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BHook=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E6=97=A5=E5=BF=97=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Hook.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/library/think/Hook.php b/library/think/Hook.php index 0ac83e85..8e6b846c 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -101,7 +101,12 @@ class Hook if (APP_DEBUG) { Debug::remark('behavior_end', 'time'); - Log::record('[ BEHAVIOR ] Run ' . ($name instanceof \Closure ? 'Closure' : $name) . ' @' . $tag . ' [ RunTime:' . Debug::getRangeTime('behavior_start', 'behavior_end') . 's ]', 'info'); + if ($name instanceof \Closure) { + $name = 'Closure'; + } elseif (is_object($name)) { + $name = get_class($name); + } + Log::record('[ BEHAVIOR ] Run ' . $name . ' @' . $tag . ' [ RunTime:' . Debug::getRangeTime('behavior_start', 'behavior_end') . 's ]', 'info'); } if (false === $result) { // 如果返回false 则中断行为执行 From 26270b2ca9daff4b9cec81c82572ae3c9e15dc00 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 18:03:36 +0800 Subject: [PATCH 109/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB?= =?UTF-8?q?=EF=BC=8C=E6=94=AF=E6=8C=81=E5=88=86=E7=BB=84=E5=90=8D=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/library/think/Route.php b/library/think/Route.php index 53ff4580..125d024b 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -468,7 +468,14 @@ class Route if (!empty($val['routes'])) { // 分组路由 - if (0 !== strpos($url, $rule)) { + if ($pos = strpos($rule, ':')) { + $str = substr($rule, 0, $pos); + } elseif ($pos = strpos($rule, '<')) { + $str = substr($rule, 0, $pos); + } else { + $str = $rule; + } + if (0 !== strpos($url, $str)) { continue; } // 匹配到路由分组 From 277e253e441c70fcf56ffdca755f504ee36abe83 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 19:13:11 +0800 Subject: [PATCH 110/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= =?UTF-8?q?=E4=B8=80=E5=A4=84BUG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 125d024b..2479cfd7 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -469,11 +469,15 @@ class Route if (!empty($val['routes'])) { // 分组路由 if ($pos = strpos($rule, ':')) { - $str = substr($rule, 0, $pos); + $str = substr($rule, 0, $pos); + $key1 = substr($rule, $pos) . '/'; } elseif ($pos = strpos($rule, '<')) { - $str = substr($rule, 0, $pos); + $str = substr($rule, 0, $pos); + $key1 = substr($rule, $pos) . '/'; } else { - $str = $rule; + $pos = strlen($rule) + 1; + $key1 = ''; + $str = $rule; } if (0 !== strpos($url, $str)) { continue; @@ -483,7 +487,9 @@ class Route if (is_numeric($key)) { $key = array_shift($route); } - $url1 = substr($url, strlen($rule) + 1); + $url1 = substr($url, $pos); + $key = $key1 . $key; + // 检查规则路由 if (is_array($route)) { $option1 = $route[1]; From b289af3070f79aa635b732505c121e9acc4f2a0d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 21:19:24 +0800 Subject: [PATCH 111/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRelation=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Relation.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index 65e066ab..6379c5bc 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -535,7 +535,7 @@ class Relation // 保存关联表数据 $model = new $this->model; $id = $model->save($data); - } elseif (is_int($data)) { + } elseif (is_numeric($data)) { // 根据关联表主键直接写入中间表 $id = $data; } elseif ($data instanceof Model) { @@ -567,7 +567,7 @@ class Relation { if (is_array($data)) { $id = $data; - } elseif (is_int($data)) { + } elseif (is_numeric($data)) { // 根据关联表主键直接写入中间表 $id = $data; } elseif ($data instanceof Model) { From e6d8a22c3b1822534b631e6ba12121389490dc4e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 21:44:40 +0800 Subject: [PATCH 112/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 2479cfd7..9d391d38 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -468,16 +468,10 @@ class Route if (!empty($val['routes'])) { // 分组路由 - if ($pos = strpos($rule, ':')) { - $str = substr($rule, 0, $pos); - $key1 = substr($rule, $pos) . '/'; - } elseif ($pos = strpos($rule, '<')) { - $str = substr($rule, 0, $pos); - $key1 = substr($rule, $pos) . '/'; + if ($pos = strpos($rule, ':') || $pos = strpos($rule, '<')) { + $str = substr($rule, 0, $pos); } else { - $pos = strlen($rule) + 1; - $key1 = ''; - $str = $rule; + $str = $rule; } if (0 !== strpos($url, $str)) { continue; @@ -487,9 +481,8 @@ class Route if (is_numeric($key)) { $key = array_shift($route); } - $url1 = substr($url, $pos); - $key = $key1 . $key; + $key = $rule . '/' . $key; // 检查规则路由 if (is_array($route)) { $option1 = $route[1]; @@ -501,7 +494,7 @@ class Route $route = $route[0]; $option = array_merge($option, $option1); } - $result = self::checkRule($key, $route, $url1, $pattern, $option); + $result = self::checkRule($key, $route, $url, $pattern, $option); if (false !== $result) { $request->route(['rule' => $key, 'route' => $route, 'pattern' => $pattern, 'option' => $option]); return $result; From f7e26259d0b8bb1e7406d75a6e1849891252609f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 23:30:26 +0800 Subject: [PATCH 113/670] =?UTF-8?q?Query=E7=B1=BB=E5=A2=9E=E5=8A=A0view?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E7=94=A8=E4=BA=8E=E8=A7=86=E5=9B=BE=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 81 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 476bf7bc..d481f7c5 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -631,6 +631,44 @@ class Query return $this; } + /** + * 指定JOIN查询字段 + * @access public + * @param string|array $table 数据表 + * @param array $field 查询字段 + * @param string|array $on JOIN条件 + * @param string $type JOIN类型 + * @return $this + */ + public function view($join, $field, $on = null, $type = 'INNER') + { + $this->options['view'] = true; + if (is_array($join)) { + foreach ($join as $key => $val) { + $this->view($key, $val[0], isset($val[1]) ? $val[1] : null, isset($val[2]) ? $val[2] : 'INNER'); + } + } else { + $fields = []; + $table = $this->getTable($join); + foreach ($field as $key => $val) { + if (is_numeric($key)) { + $fields[] = $join . '.' . $val; + $this->options['map'][$val] = $join . '.' . $val; + } else { + $fields[] = $join . '.' . $key . ' AS ' . $val; + $this->options['map'][$val] = $join . '.' . $key; + } + } + $this->field($fields); + if ($on) { + $this->join($table . ' ' . $join, $on, $type); + } else { + $this->table($table . ' ' . $join); + } + } + return $this; + } + /** * 指定查询条件 * @access public @@ -1692,6 +1730,49 @@ class Query if (!isset($options['where'])) { $options['where'] = []; + } elseif (isset($options['view'])) { + if (isset($options['where']['AND'])) { + foreach ($options['where']['AND'] as $key => $val) { + if (array_key_exists($key, $options['map'])) { + $options['where']['AND'][$options['map'][$key]] = $val; + unset($options['where']['AND'][$key]); + } + } + } + if (isset($options['where']['OR'])) { + foreach ($options['where']['OR'] as $key => $val) { + if (array_key_exists($key, $options['map'])) { + $options['where']['OR'][$options['map'][$key]] = $val; + unset($options['where']['OR'][$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]); + } + } else { + if (array_key_exists($val, $options['map'])) { + $options['order'][$options['map'][$val]] = 'asc'; + unset($options['order'][$key]); + } + } + } else { + if (array_key_exists($key, $options['map'])) { + $options['order'][$options['map'][$key]] = $val; + unset($options['order'][$key]); + } + } + } + } } // 表别名 From e1abc0844b7cb9a473842d198d316e2401387e29 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 20 May 2016 23:53:23 +0800 Subject: [PATCH 114/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BBuilder=E7=B1=BB?= =?UTF-8?q?=E5=AF=B9field=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=9A=84=E7=A9=BA?= =?UTF-8?q?=E6=A0=BC=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Builder.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index 23a5c8f4..8a10e2c8 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -85,7 +85,7 @@ abstract class Builder if ('*' == $options['field']) { $fields = array_keys($bind); } else { - $fields = is_array($options['field']) ? $options['field'] : explode(',', $options['field']); + $fields = is_array($options['field']) ? $options['field'] : array_map('trim', explode(',', $options['field'])); } $result = []; @@ -567,7 +567,7 @@ abstract class Builder if ('*' == $options['field']) { $fields = $this->query->getTableInfo($options['table'], 'fields'); } else { - $fields = is_array($options['field']) ? $options['field'] : explode(',', $options['field']); + $fields = is_array($options['field']) ? $options['field'] : array_map('trim', explode(',', $options['field'])); } foreach ($dataSet as &$data) { From 20052962679adf9553b4c14142206692babbfc12 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 21 May 2016 09:26:56 +0800 Subject: [PATCH 115/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3File=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/File.php b/library/think/File.php index f5e5470d..580cb7dd 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -161,7 +161,7 @@ class File extends SplFileObject $savename .= '.' . pathinfo($this->getInfo('name'), PATHINFO_EXTENSION); } } elseif ('' === $savename) { - $savename = $this->getFilename(); + $savename = $this->getInfo('name'); } return $savename; } From 25981119addd8df005331bed208d41157d0af353 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 21 May 2016 10:24:08 +0800 Subject: [PATCH 116/670] =?UTF-8?q?Query=E7=B1=BB=E7=9A=84view=E6=96=B9?= =?UTF-8?q?=E6=B3=95field=E5=8F=82=E6=95=B0=E6=94=AF=E6=8C=81=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index d481f7c5..0d09d17b 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -635,7 +635,7 @@ class Query * 指定JOIN查询字段 * @access public * @param string|array $table 数据表 - * @param array $field 查询字段 + * @param string|array $field 查询字段 * @param string|array $on JOIN条件 * @param string $type JOIN类型 * @return $this @@ -650,6 +650,9 @@ class Query } else { $fields = []; $table = $this->getTable($join); + if (is_string($field)) { + $field = explode(',', $field); + } foreach ($field as $key => $val) { if (is_numeric($key)) { $fields[] = $join . '.' . $val; From f3aceca2b06f8f1016955e213ba8bb14589cedd2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 21 May 2016 11:38:18 +0800 Subject: [PATCH 117/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84field=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Builder.php | 4 ++-- library/think/db/Query.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index 8a10e2c8..933c3b5d 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -85,7 +85,7 @@ abstract class Builder if ('*' == $options['field']) { $fields = array_keys($bind); } else { - $fields = is_array($options['field']) ? $options['field'] : array_map('trim', explode(',', $options['field'])); + $fields = $options['field']; } $result = []; @@ -567,7 +567,7 @@ abstract class Builder if ('*' == $options['field']) { $fields = $this->query->getTableInfo($options['table'], 'fields'); } else { - $fields = is_array($options['field']) ? $options['field'] : array_map('trim', explode(',', $options['field'])); + $fields = $options['field']; } foreach ($dataSet as &$data) { diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 0d09d17b..8c3fe9bf 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -602,12 +602,12 @@ class Query return $this; } if (is_string($field)) { - $field = explode(',', $field); + $field = array_map('trim', explode(',', $field)); } if (true === $field) { // 获取全部字段 $fields = $this->getTableInfo($tableName, 'fields'); - $field = $fields ?: '*'; + $field = $fields ?: ['*']; } elseif ($except) { // 字段排除 $fields = $this->getTableInfo($tableName, 'fields'); From 3bcb764973daa99b14f576b614ae91e039c51c1b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 21 May 2016 14:42:37 +0800 Subject: [PATCH 118/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Builder=E7=B1=BB?= =?UTF-8?q?=E7=9A=84selectinsert=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Builder.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index 933c3b5d..91485f86 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -612,8 +612,7 @@ abstract class Builder } $fields = array_map([$this, 'parseKey'], $fields); - $sql = 'INSERT INTO ' . $this->parseTable($table) . ' (' . implode(',', $fields) . ') '; - $sql .= $this->buildSelectSql($options); + $sql = 'INSERT INTO ' . $this->parseTable($table) . ' (' . implode(',', $fields) . ') ' . $this->select($options); return $sql; } From 744cdaebff3223b4cb01f952a7eb58bfc15ad11b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 21 May 2016 15:21:12 +0800 Subject: [PATCH 119/670] =?UTF-8?q?=E5=8F=96=E6=B6=88=20url=5Fmodule=5Fmap?= =?UTF-8?q?=20=E9=85=8D=E7=BD=AE=E5=8F=82=E6=95=B0=20=E6=94=B9=E8=BF=9BRed?= =?UTF-8?q?is=20session=E9=A9=B1=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 2 -- library/think/session/driver/Redis.php | 20 ++++++++++---------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/convention.php b/convention.php index fda103a3..09fff046 100644 --- a/convention.php +++ b/convention.php @@ -73,8 +73,6 @@ return [ 'url_route_on' => true, // 是否强制使用路由 'url_route_must' => false, - // URL模块映射 - 'url_module_map' => [], // 域名部署 'url_domain_deploy' => false, // 域名根,如.thinkphp.cn diff --git a/library/think/session/driver/Redis.php b/library/think/session/driver/Redis.php index b07289dd..96389fe0 100644 --- a/library/think/session/driver/Redis.php +++ b/library/think/session/driver/Redis.php @@ -18,13 +18,13 @@ class Redis extends SessionHandler { protected $handler = null; protected $config = [ - 'host' => '127.0.0.1', // redis主机 - 'port' => 6379, // redis端口 - 'password' => '', // 密码 - 'expire' => 3600, // 有效期(秒) - 'timeout' => 0, // 超时时间(秒) - 'persistent' => true, // 是否长连接 - 'session_name' => '', // sessionkey前缀 + 'host' => '127.0.0.1', // redis主机 + 'port' => 6379, // redis端口 + 'password' => '', // 密码 + 'expire' => 3600, // 有效期(秒) + 'timeout' => 0, // 超时时间(秒) + 'persistent' => true, // 是否长连接 + 'session_name' => '', // sessionkey前缀 ]; public function __construct($config = []) @@ -45,11 +45,11 @@ class Redis extends SessionHandler throw new Exception('_NOT_SUPPERT_:redis'); } $this->handler = new \Redis; - + // 建立连接 $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']); } @@ -100,7 +100,7 @@ class Redis extends SessionHandler */ public function destroy($sessID) { - return $this->handler->delete($this->config['session_name'] . $sessID); + return $this->handler->delete($this->config['session_name'] . $sessID) ? true : false; } /** From 60f6d10e1636e297817e0608540f6f3b78804a95 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 21 May 2016 17:16:02 +0800 Subject: [PATCH 120/670] =?UTF-8?q?=E5=AE=8C=E5=96=84Error=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Error.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/library/think/Error.php b/library/think/Error.php index 3807abcc..a1541282 100644 --- a/library/think/Error.php +++ b/library/think/Error.php @@ -11,10 +11,10 @@ namespace think; +use think\console\Output as ConsoleOutput; use think\exception\ErrorException; use think\exception\Handle; use think\exception\ThrowableError; -use think\console\Output as ConsoleOutput; class Error { @@ -24,7 +24,7 @@ class Error */ public static function register() { - error_reporting(-1); + error_reporting(E_ALL); set_error_handler([__CLASS__, 'appError']); set_exception_handler([__CLASS__, 'appException']); register_shutdown_function([__CLASS__, 'appShutdown']); @@ -97,7 +97,6 @@ class Error return in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE]); } - /** * Get an instance of the exception handler. * From 90c5dc79ed4e5e51a7e5c7a70cb0814c1e5fc927 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 21 May 2016 17:25:53 +0800 Subject: [PATCH 121/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Query=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getLastSql=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 8c3fe9bf..9ed1cbd8 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -185,7 +185,7 @@ class Query */ public function getLastSql() { - return $this->connection->queryStr; + return $this->connection->getLastSql(); } /** From dd8fb56b1002a442488541ef7c5ecde467561552 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 21 May 2016 23:11:21 +0800 Subject: [PATCH 122/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E8=A7=86=E5=9B=BE?= =?UTF-8?q?=E9=A9=B1=E5=8A=A8=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/view/driver/Php.php | 7 +++++-- library/think/view/driver/Think.php | 9 ++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index 9ab33119..3063bc02 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -55,9 +55,12 @@ class Php */ public function fetch($template, $data = []) { + if (!is_file($template)) { + // 获取模板文件名 + $template = $this->parseTemplate($template); + } // 模板不存在 抛出异常 - $template = $this->exists($template); - if (!$template) { + if (!is_file($template)) { throw new Exception('template file not exists:' . $template, 10700); } // 记录视图信息 diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index ac7a84b0..8eb85e26 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -52,7 +52,7 @@ class Think // 获取模板文件名 $template = $this->parseTemplate($template); } - return is_file($template) ? $template : false; + return is_file($template); } /** @@ -65,9 +65,12 @@ class Think */ public function fetch($template, $data = [], $config = []) { + if (!is_file($template)) { + // 获取模板文件名 + $template = $this->parseTemplate($template); + } // 模板不存在 抛出异常 - $template = $this->exists($template); - if (!$template) { + if (!is_file($template)) { throw new Exception('template file not exists:' . $template, 10700); } // 记录视图信息 From 10d62d854c0ce8969aa15cd57db438eef84079cd Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 21 May 2016 23:15:49 +0800 Subject: [PATCH 123/670] =?UTF-8?q?=E5=8E=BB=E9=99=A4error=5Fpage=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/convention.php b/convention.php index 09fff046..d0a4933b 100644 --- a/convention.php +++ b/convention.php @@ -120,8 +120,6 @@ return [ // 错误显示信息,非调试模式有效 'error_message' => '页面错误!请稍后再试~', - // 错误定向页面 - 'error_page' => '', // 显示错误信息 'show_error_msg' => false, From 988671e991b41dd045a9eb784233f0405ffbb261 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 22 May 2016 11:50:29 +0800 Subject: [PATCH 124/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0controller=5Fauto=5Fs?= =?UTF-8?q?earch=E9=85=8D=E7=BD=AE=E5=8F=82=E6=95=B0=E7=94=A8=E4=BA=8E?= =?UTF-8?q?=E8=AE=BE=E7=BD=AEURL=E8=A7=A3=E6=9E=90=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=90=9C=E7=B4=A2=E6=8E=A7=E5=88=B6=E5=99=A8?= =?UTF-8?q?=20=E6=94=B9=E8=BF=9BRoute=E7=B1=BB=E7=9A=84parseRoute=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 2 ++ library/think/App.php | 4 ++-- library/think/Route.php | 50 ++++++++++++++++++++++++++++------------- 3 files changed, 39 insertions(+), 17 deletions(-) diff --git a/convention.php b/convention.php index d0a4933b..10858064 100644 --- a/convention.php +++ b/convention.php @@ -50,6 +50,8 @@ return [ 'empty_controller' => 'Error', // 操作方法后缀 'action_suffix' => '', + // 自动搜索控制器 + 'controller_auto_search' => false, // +---------------------------------------------------------------------- // | URL设置 diff --git a/library/think/App.php b/library/think/App.php index 6f70640d..cb0306f3 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -339,8 +339,8 @@ class App } } if (false === $result) { - // 路由无效默认分析为模块/控制器/操作/参数...方式URL - $result = Route::parseUrl($path, $depr); + // 路由无效 解析模块/控制器/操作/参数... 支持控制器自动搜索 + $result = Route::parseUrl($path, $depr, $config['controller_auto_search']); } //保证$_REQUEST正常取值 $_REQUEST = array_merge($_POST, $_GET, $_COOKIE); diff --git a/library/think/Route.php b/library/think/Route.php index 9d391d38..dbcefaf7 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -651,7 +651,7 @@ class Route } // 解析模块的URL地址 [模块/控制器/操作?]参数1=值1&参数2=值2... - public static function parseUrl($url, $depr = '/') + public static function parseUrl($url, $depr = '/', $autoSearch = false) { if (isset(self::$bind['module'])) { // 如果有模块/控制器绑定 @@ -661,7 +661,9 @@ class Route if ('/' != $depr) { $url = str_replace($depr, '/', $url); } - $result = self::parseRoute($url, true); + + $result = self::parseRoute($url, $autoSearch, true); + if (!empty($result['var'])) { $_GET = array_merge($result['var'], $_GET); } @@ -670,18 +672,18 @@ class Route // 解析规范的路由地址 // 地址格式 [模块/控制器/操作?]参数1=值1&参数2=值2... - private static function parseRoute($url, $reverse = false) + private static function parseRoute($url, $autoSearch = false, $reverse = false) { $url = trim($url, '/'); $var = []; if (false !== strpos($url, '?')) { // [模块/控制器/操作?]参数1=值1&参数2=值2... $info = parse_url($url); - $path = explode('/', $info['path'], APP_MULTI_MODULE ? 4 : 3); + $path = $info['path']; parse_str($info['query'], $var); } elseif (strpos($url, '/')) { // [模块/控制器/操作] - $path = explode('/', $url, APP_MULTI_MODULE ? 4 : 3); + $path = explode('/', $url); } elseif (false !== strpos($url, '=')) { // 参数1=值1&参数2=值2... parse_str($url, $var); @@ -690,17 +692,33 @@ class Route } $route = [null, null, null]; if (isset($path)) { - // 解析path额外的参数 - if (!empty($path[APP_MULTI_MODULE ? 3 : 2])) { - preg_replace_callback('/([^\/]+)\/([^\/]+)/', function ($match) use (&$var) { - $var[strtolower($match[1])] = strip_tags($match[2]); - }, array_pop($path)); - } - // 解析[模块/控制器/操作] if ($reverse) { - $module = APP_MULTI_MODULE ? array_shift($path) : null; - $controller = !empty($path) ? array_shift($path) : null; - $action = !empty($path) ? array_shift($path) : null; + // 解析模块 + $module = APP_MULTI_MODULE ? array_shift($path) : null; + if ($autoSearch) { + // 自动搜索控制器 + $dir = APP_PATH . ($module ? $module . DS : '') . CONTROLLER_LAYER; + foreach ($path as $val) { + $item[] = array_shift($path); + if (is_file($dir . DS . $val . EXT)) { + break; + } else { + $dir .= DS . $val; + } + } + $controller = implode('.', $item); + } else { + // 解析控制器 + $controller = !empty($path) ? array_shift($path) : null; + } + // 解析操作 + $action = !empty($path) ? array_shift($path) : null; + // 解析额外参数 + if (!empty($path)) { + preg_replace_callback('/([^\/]+)\/([^\/]+)/', function ($match) use (&$var) { + $var[strtolower($match[1])] = strip_tags($match[2]); + }, implode('/', $path)); + } } else { $action = array_pop($path); $controller = !empty($path) ? array_pop($path) : null; @@ -713,6 +731,8 @@ class Route $action = 0 !== strpos($action, self::$methodPrefix[REQUEST_METHOD]) ? self::$methodPrefix[REQUEST_METHOD] . $action : $action; } } + + // 封装路由 $route = [$module, $controller, $action]; } return ['route' => $route, 'var' => $var]; From 990f34c24c586cffefb819c1020600b657041bed Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 22 May 2016 11:52:46 +0800 Subject: [PATCH 125/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= =?UTF-8?q?=E4=B8=80=E5=A4=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/Route.php b/library/think/Route.php index dbcefaf7..5bee29d8 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -697,7 +697,8 @@ class Route $module = APP_MULTI_MODULE ? array_shift($path) : null; if ($autoSearch) { // 自动搜索控制器 - $dir = APP_PATH . ($module ? $module . DS : '') . CONTROLLER_LAYER; + $dir = APP_PATH . ($module ? $module . DS : '') . CONTROLLER_LAYER; + $item = []; foreach ($path as $val) { $item[] = array_shift($path); if (is_file($dir . DS . $val . EXT)) { From 97acdbe0a548cdc36c2d5f192fd5c4ec9984c179 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 22 May 2016 11:59:52 +0800 Subject: [PATCH 126/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BBparseRo?= =?UTF-8?q?ute=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Route.php b/library/think/Route.php index 5bee29d8..609b4ae6 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -679,7 +679,7 @@ class Route if (false !== strpos($url, '?')) { // [模块/控制器/操作?]参数1=值1&参数2=值2... $info = parse_url($url); - $path = $info['path']; + $path = explode('/', $info['path']); parse_str($info['query'], $var); } elseif (strpos($url, '/')) { // [模块/控制器/操作] From f4182cf38f6b3b977dcb7799accd8371802b8cb2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 22 May 2016 13:41:16 +0800 Subject: [PATCH 127/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BMerge=E7=9A=84save?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Merge.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 66b11c85..11548ae6 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -170,9 +170,6 @@ class Merge extends Model $this->__set($this->updateTime, null); } - // 处理模型数据 - $data = $this->parseData($this->name, $this->data); - $db = $this->db(); $db->startTrans('merge_save_' . $this->name); try { @@ -184,6 +181,8 @@ class Merge extends Model return false; } + // 处理模型数据 + $data = $this->parseData($this->name, $this->data); // 写入主表数据 $result = $db->strict(false)->update($data); @@ -211,8 +210,10 @@ class Merge extends Model return false; } + // 处理模型数据 + $data = $this->parseData($this->name, $this->data); // 写入主表数据 - $result = $db->name($this->name)->strict(false)->insert($this->data); + $result = $db->name($this->name)->strict(false)->insert($data); if ($result) { $insertId = $db->getLastInsID(); // 写入外键数据 From 37525f0a4d37517e82e08d7e759a162ff9950277 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 22 May 2016 14:49:45 +0800 Subject: [PATCH 128/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 8427a4a5..ef9ba1f2 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -214,7 +214,7 @@ class Request */ public function url($url = '') { - if (!empty($url)) { + if (is_string($url) && !empty($url)) { $this->url = $url; return; } elseif (!$this->url) { @@ -235,7 +235,7 @@ class Request */ public function baseUrl($url = '') { - if (!empty($url)) { + if (is_string($url) && !empty($url)) { $this->baseUrl = $url; return; } elseif (!$this->baseUrl) { @@ -252,7 +252,7 @@ class Request */ public function baseFile($file = '') { - if (!empty($file)) { + if (is_string($file) && !empty($file)) { $this->baseFile = $file; return; } elseif (!$this->baseFile) { @@ -284,7 +284,7 @@ class Request */ public function root($url = '') { - if (!empty($url)) { + if (is_string($url) && !empty($url)) { $this->root = $url; return; } elseif (!$this->root) { @@ -371,14 +371,15 @@ class Request */ public function type() { - if (!isset($_SERVER['HTTP_ACCEPT'])) { + $accept = isset($this->server['HTTP_ACCEPT']) ? $this->server['HTTP_ACCEPT'] : $_SERVER['HTTP_ACCEPT']; + if (empty($accept)) { return false; } foreach ($this->mimeType as $key => $val) { $array = explode(',', $val); foreach ($array as $k => $v) { - if (stristr($_SERVER['HTTP_ACCEPT'], $v)) { + if (stristr($accept, $v)) { return $key; } } @@ -396,7 +397,6 @@ class Request public function mimeType($type, $val = '') { if (is_array($type)) { - $this->mimeType = array_merge($this->mimeType, $type); } else { $this->mimeType[$type] = $val; @@ -410,7 +410,8 @@ class Request */ public function method() { - return IS_CLI ? 'GET' : $_SERVER['REQUEST_METHOD']; + $method = isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']; + return IS_CLI ? 'GET' : $method; } /** @@ -564,9 +565,12 @@ class Request */ public function isSsl() { - if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) { + $server = array_merge($_SERVER, $this->server); + if (isset($server['HTTPS']) && ('1' == $server['HTTPS'] || 'on' == strtolower($server['HTTPS']))) { return true; - } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) { + } elseif (isset($server['REQUEST_SCHEME']) && 'https' == $server['REQUEST_SCHEME']) { + return true; + } elseif (isset($server['SERVER_PORT']) && ('443' == $server['SERVER_PORT'])) { return true; } return false; @@ -626,7 +630,7 @@ class Request */ public function scheme() { - return $_SERVER['REQUEST_SCHEME']; + return $this->isSsl() ? 'https' : 'http'; } /** @@ -636,7 +640,7 @@ class Request */ public function query() { - return $_SERVER['QUERY_STRING']; + return $this->server('QUERY_STRING'); } /** @@ -646,7 +650,7 @@ class Request */ public function host() { - return $_SERVER['SERVER_NAME']; + return $this->server('SERVER_NAME'); } /** @@ -656,7 +660,7 @@ class Request */ public function port() { - return $_SERVER['SERVER_PORT']; + return $this->server('SERVER_PORT'); } /** @@ -666,7 +670,7 @@ class Request */ public function protocol() { - return $_SERVER['SERVER_PROTOCOL']; + return $this->server('SERVER_PROTOCOL'); } /** @@ -676,7 +680,7 @@ class Request */ public function remotePort() { - return $_SERVER['REMOTE_PORT']; + return $this->server('REMOTE_PORT'); } /** From 2106cdceaf1824333dd958a0e082aa64dbd8e5b7 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 22 May 2016 15:38:45 +0800 Subject: [PATCH 129/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BResponse=E7=B1=BB?= =?UTF-8?q?=E7=9A=84send=E6=96=B9=E6=B3=95=20=E6=94=B9=E8=BF=9BInput?= =?UTF-8?q?=E7=B1=BB=E7=9A=84=E8=87=AA=E5=8A=A8=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Input.php | 6 +++++- library/think/Response.php | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/library/think/Input.php b/library/think/Input.php index 848be817..a6445b2d 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -465,7 +465,11 @@ class Input // 字符串 case 's': default: - $data = (string) $data; + if (is_scalar($data)) { + $data = (string) $data; + } else { + throw new Exception('变量类型不允许:' . gettype($data)); + } } } } diff --git a/library/think/Response.php b/library/think/Response.php index 634a2d99..8c35f87b 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -111,7 +111,12 @@ class Response header($name . ':' . $val); } } - echo $data; + if (is_scalar($data)) { + echo $data; + } else { + throw new Exception('不支持的数据类型输出:' . gettype($data)); + } + if (function_exists('fastcgi_finish_request')) { // 提高页面响应 fastcgi_finish_request(); From 071745876255223a4c8015373499418826d8ddcb Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 08:30:17 +0800 Subject: [PATCH 130/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Response=E7=B1=BBsend?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Response.php b/library/think/Response.php index 8c35f87b..be0146aa 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -113,7 +113,7 @@ class Response } if (is_scalar($data)) { echo $data; - } else { + } elseif (!is_null($data)) { throw new Exception('不支持的数据类型输出:' . gettype($data)); } From 80e87d1d795efc6dab3d4bac451f3bcc1dce731a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 10:10:28 +0800 Subject: [PATCH 131/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E5=99=A8=E8=87=AA=E5=8A=A8=E6=90=9C=E7=B4=A2=E7=9A=84=E5=90=8E?= =?UTF-8?q?=E7=BC=80=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 609b4ae6..73bd8bff 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -697,11 +697,12 @@ class Route $module = APP_MULTI_MODULE ? array_shift($path) : null; if ($autoSearch) { // 自动搜索控制器 - $dir = APP_PATH . ($module ? $module . DS : '') . CONTROLLER_LAYER; - $item = []; + $dir = APP_PATH . ($module ? $module . DS : '') . CONTROLLER_LAYER; + $suffix = CLASS_APPEND_SUFFIX || Config::get('use_controller_suffix') ? ucfirst(CONTROLLER_LAYER) : ''; + $item = []; foreach ($path as $val) { $item[] = array_shift($path); - if (is_file($dir . DS . $val . EXT)) { + if (is_file($dir . DS . $val . $suffix . EXT)) { break; } else { $dir .= DS . $val; From 6172303c972b78175dafddca3d87155846f50e86 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 11:47:33 +0800 Subject: [PATCH 132/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20database.auto=5Fti?= =?UTF-8?q?mestamp=20=E9=85=8D=E7=BD=AE=E5=8F=82=E6=95=B0=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E9=85=8D=E7=BD=AE=E6=98=AF=E5=90=A6=E9=9C=80=E8=A6=81?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=86=99=E5=85=A5=E6=97=B6=E9=97=B4=E6=88=B3?= =?UTF-8?q?=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 34 ++++++++++++++++++--------------- library/think/Model.php | 6 +++++- library/think/db/Connection.php | 6 ++++-- library/think/db/Query.php | 17 ++++++++++++++--- 4 files changed, 42 insertions(+), 21 deletions(-) diff --git a/convention.php b/convention.php index 10858064..8e2f20a1 100644 --- a/convention.php +++ b/convention.php @@ -173,35 +173,39 @@ return [ 'database' => [ // 数据库类型 - 'type' => 'mysql', + 'type' => 'mysql', // 数据库连接DSN配置 - 'dsn' => '', + 'dsn' => '', // 服务器地址 - 'hostname' => 'localhost', + 'hostname' => 'localhost', // 数据库名 - '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, + // 自动写入时间戳字段 + 'auto_timestamp' => false, ], //分页配置 'paginate' => [ diff --git a/library/think/Model.php b/library/think/Model.php index e51c44f4..be01b26b 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -64,7 +64,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 更新自动完成列表 protected $update = []; // 是否需要自动写入时间戳 - protected $autoWriteTimestamp = true; + protected $autoWriteTimestamp; // 创建时间字段 protected $createTime = 'create_time'; // 更新时间字段 @@ -111,6 +111,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->name = basename(str_replace('\\', '/', $this->class)); } + if (is_null($this->autoWriteTimestamp)) { + $this->autoWriteTimestamp = $this->getConfig('auto_timestamp'); + } + // 执行初始化操作 $this->initialize(); } diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index dfa9ca49..e613e882 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -99,6 +99,8 @@ abstract class Connection 'fields_strict' => true, // 数据集返回类型 'resultset_type' => Db::RESULTSET_ARRAY, + // 自动写入时间戳字段 + 'auto_timestamp' => false, ]; // PDO连接参数 @@ -212,9 +214,9 @@ abstract class Connection * @param string $config 配置名称 * @return mixed */ - public function getConfig($config) + public function getConfig($config = '') { - return $this->config[$config]; + return $config ? $this->config[$config] : $this->config; } /** diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 9ed1cbd8..225500fb 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -124,7 +124,7 @@ class Query { if ($name || empty($this->table)) { $name = $name ?: $this->name; - $tableName = $this->connection->getConfig('prefix'); + $tableName = $this->getConfig('prefix'); if ($name) { $tableName .= Loader::parseName($name); } @@ -245,6 +245,17 @@ class Query return $this->connection->batchQuery($sql); } + /** + * 获取数据库的配置参数 + * @access public + * @param string $name 参数名称 + * @return boolean + */ + public function getConfig($name = '') + { + return $this->connection->getConfig($name); + } + /** * 获取当前的builder实例对象 * @access protected @@ -532,7 +543,7 @@ class Query } } } else { - $prefix = $this->connection->getConfig('prefix'); + $prefix = $this->getConfig('prefix'); // 传入的表名为数组 if (is_array($join)) { if (0 !== $key = key($join)) { @@ -1788,7 +1799,7 @@ class Query } if (!isset($options['strict'])) { - $options['strict'] = $this->connection->getConfig('fields_strict'); + $options['strict'] = $this->getConfig('fields_strict'); } foreach (['master', 'lock', 'fetch_class', 'fetch_sql', 'distinct'] as $name) { From 0556e391642001b397d71dcd6192e283c2d05dd9 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 11:56:39 +0800 Subject: [PATCH 133/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E6=88=B3=E5=86=99=E5=85=A5=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E5=8D=95=E7=8B=AC=E5=85=B3=E9=97=AD=E6=9F=90=E4=B8=AA?= =?UTF-8?q?=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 4 ++-- library/think/model/Merge.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index be01b26b..00f5a3f4 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -322,7 +322,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->autoCompleteData($this->auto); // 自动写入更新时间 - if ($this->autoWriteTimestamp) { + if ($this->autoWriteTimestamp && $this->updateTime) { $this->__set($this->updateTime, null); } @@ -368,7 +368,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->autoCompleteData($this->insert); // 自动写入创建时间 - if ($this->autoWriteTimestamp) { + if ($this->autoWriteTimestamp && $this->createTime) { $this->__set($this->createTime, null); } diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 11548ae6..f34d8d3a 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -166,7 +166,7 @@ class Merge extends Model $this->autoCompleteData($this->auto); // 自动写入更新时间 - if ($this->autoWriteTimestamp) { + if ($this->autoWriteTimestamp && $this->updateTime) { $this->__set($this->updateTime, null); } @@ -202,7 +202,7 @@ class Merge extends Model $this->autoCompleteData($this->insert); // 自动写入创建时间 - if ($this->autoWriteTimestamp) { + if ($this->autoWriteTimestamp && $this->createTime) { $this->__set($this->createTime, null); } From 5d2685cc85300a50343f08c269888df6f1c663d2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 12:26:57 +0800 Subject: [PATCH 134/670] =?UTF-8?q?Route=E6=B3=A8=E9=87=8A=E5=AE=8C?= =?UTF-8?q?=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 281 +++++++++++++++++++++++++++++++++++----- 1 file changed, 248 insertions(+), 33 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 73bd8bff..a9c86a3f 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -57,25 +57,50 @@ class Route private static $group; private static $option = []; - // 添加URL映射规则 + /** + * 注册或者获取URL映射规则 + * @access public + * @param string|array $map 映射名 + * @param string $route 路由地址 + * @return mixed + */ public static function map($map = '', $route = '') { return self::setting('map', $map, $route); } - // 添加变量规则 + /** + * 注册或者获取变量规则 + * @access public + * @param string|array $name 变量名 + * @param string $rule 变量规则 + * @return mixed + */ public static function pattern($name = '', $rule = '') { return self::setting('pattern', $name, $rule); } - // 添加子域名部署规则 + /** + * 注册或者获取子域名部署规则 + * @access public + * @param string|array $domain 子域名 + * @param mixed $rule 路由规则 + * @return mixed + */ public static function domain($domain = '', $rule = '') { return self::setting('domain', $domain, $rule); } - // 属性设置 + /** + * 设置属性 + * @access public + * @param string $var 属性名称 + * @param string|array $name 变量名称 + * @param mixed $value 变量值 + * @return mixed + */ private static function setting($var, $name = '', $value = '') { if (is_array($name)) { @@ -87,7 +112,13 @@ class Route } } - // 对路由进行绑定和获取绑定信息 + /** + * 设置和读取路由绑定 + * @access public + * @param string $type 请求类型 + * @param mixed $bind 绑定信息 + * @return mixed + */ public static function bind($type, $bind = '') { if ('' == $bind) { @@ -97,7 +128,13 @@ class Route } } - // 导入配置文件定义的路由规则 + /** + * 导入配置文件的路由规则 + * @access public + * @param array $rule 路由规则 + * @param string $type 请求类型 + * @return void + */ public static function import(array $rule, $type = '*') { // 检查域名部署 @@ -140,7 +177,17 @@ class Route } } - // 注册路由规则 + /** + * 注册路由规则 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param string $type 请求类型 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @param string $group 所属分组 + * @return void + */ public static function rule($rule, $route = '', $type = '*', $option = [], $pattern = [], $group = '') { $group = $group ?: self::$group; @@ -179,19 +226,38 @@ class Route } } - // 设置当前的路由分组 + /** + * 设置当前的路由分组 + * @access public + * @param array $option 路由参数 + * @return void + */ public static function setGroup($name) { self::$group = $name; } - // 设置当前的路由分组 + /** + * 设置当前的路由参数 + * @access public + * @param array $option 路由参数 + * @return void + */ public static function setOption($option) { self::$option = $option; } - // 路由分组 + /** + * 注册路由分组 + * @access public + * @param string|array $name 分组名称或者参数 + * @param array $routes 路由地址 + * @param array $option 路由参数 + * @param string $type 请求类型 + * @param array $pattern 变量规则 + * @return void + */ public static function group($name, $routes, $option = [], $type = '*', $pattern = []) { if (is_array($name)) { @@ -222,37 +288,90 @@ class Route } } - // 注册任意请求的路由规则 + /** + * 注册路由 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @param string $group 所属分组 + * @return void + */ public static function any($rule, $route = '', $option = [], $pattern = [], $group = '') { self::rule($rule, $route, '*', $option, $pattern, $group); } - // 注册get请求的路由规则 + /** + * 注册GET路由 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @param string $group 所属分组 + * @return void + */ public static function get($rule, $route = '', $option = [], $pattern = [], $group = '') { self::rule($rule, $route, 'GET', $option, $pattern, $group); } - // 注册post请求的路由规则 + /** + * 注册POST路由 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @param string $group 所属分组 + * @return void + */ public static function post($rule, $route = '', $option = [], $pattern = [], $group = '') { self::rule($rule, $route, 'POST', $option, $pattern, $group); } - // 注册put请求的路由规则 + /** + * 注册PUT路由 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @param string $group 所属分组 + * @return void + */ public static function put($rule, $route = '', $option = [], $pattern = [], $group = '') { self::rule($rule, $route, 'PUT', $option, $pattern, $group); } - // 注册delete请求的路由规则 + /** + * 注册DELETE路由 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @param string $group 所属分组 + * @return void + */ public static function delete($rule, $route = '', $option = [], $pattern = [], $group = '') { self::rule($rule, $route, 'DELETE', $option, $pattern, $group); } - // 注册资源路由 + /** + * 注册资源路由 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return void + */ public static function resource($rule, $route = '', $option = [], $pattern = []) { if (is_array($rule)) { @@ -287,7 +406,15 @@ class Route } } - // 注册别名路由 + /** + * 注册别名路由 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return void + */ public static function alias($rule, $route = '', $option = [], $pattern = []) { foreach (self::$methodPrefix as $type => $val) { @@ -295,7 +422,13 @@ class Route } } - // 设置不同请求类型下面的方法前缀 + /** + * 设置不同请求类型下面的方法前缀 + * @access public + * @param string $method 请求类型 + * @param string $prefix 类型前缀 + * @return void + */ public static function setMethodPrefix($method, $prefix = '') { if (is_array($method)) { @@ -305,7 +438,13 @@ class Route } } - // rest方法定义和修改 + /** + * rest方法定义和修改 + * @access public + * @param string $name 方法名称 + * @param array $resourece 资源 + * @return void + */ public static function rest($name, $resource = []) { if (is_array($name)) { @@ -315,13 +454,25 @@ class Route } } - // 注册未匹配路由规则后的处理 + /** + * 注册未匹配路由规则后的处理 + * @access public + * @param string $route 路由地址 + * @param string $method 请求类型 + * @param array $option 路由参数 + * @return void + */ public static function miss($route, $method = '*', $option = []) { self::rule('__miss__', $route, $method, $option, []); } - // 获取路由定义 + /** + * 获取路由定义 + * @access public + * @param string $method 请求类型 + * @return array + */ public static function getRules($method = '') { if ($method) { @@ -331,7 +482,11 @@ class Route } } - // 检测子域名部署 + /** + * 检测子域名部署 + * @access public + * @return void + */ public static function checkDomain() { // 域名规则 @@ -418,7 +573,15 @@ class Route } } - // 检测URL路由 + /** + * 检测URL路由 + * @access public + * @param \think\Request $request Request请求对象 + * @param string $url URL地址 + * @param string $depr URL分隔符 + * @param bool $checkDomain 是否检测域名规则 + * @return false|array + */ public static function check($request, $url, $depr = '/', $checkDomain = false) { // 检测域名部署 @@ -528,7 +691,13 @@ class Route return false; } - // 检测URL绑定 + /** + * 检测URL绑定 + * @access private + * @param string $url URL地址 + * @param array $rules 路由规则 + * @return false + */ private static function checkUrlBind(&$url, &$rules) { if (!empty(self::$bind['type'])) { @@ -567,7 +736,13 @@ class Route return false; } - // 路由参数有效性检查 + /** + * 路由参数有效性检查 + * @access private + * @param array $option 路由参数 + * @param string $url URL地址 + * @return bool + */ private static function checkOption($option, $url) { // 请求类型检测 @@ -584,7 +759,14 @@ class Route } /** - * 检查规则路由 + * 检测路由规则 + * @access private + * @param string $rule 路由规则 + * @param string $url URL地址 + * @param string $route 路由地址 + * @param array $pattern 变量规则 + * @param array $option 路由参数 + * @return array|false */ private static function checkRule($rule, $route, $url, $pattern, $option) { @@ -650,7 +832,14 @@ class Route } } - // 解析模块的URL地址 [模块/控制器/操作?]参数1=值1&参数2=值2... + /** + * 解析模块的URL地址 [模块/控制器/操作?]参数1=值1&参数2=值2... + * @access public + * @param string $url URL地址 + * @param string $depr URL分隔符 + * @param bool $autoSearch 是否自动深度搜索控制器 + * @return array + */ public static function parseUrl($url, $depr = '/', $autoSearch = false) { if (isset(self::$bind['module'])) { @@ -670,8 +859,14 @@ class Route return ['type' => 'module', 'module' => $result['route']]; } - // 解析规范的路由地址 - // 地址格式 [模块/控制器/操作?]参数1=值1&参数2=值2... + /** + * 解析规范的路由地址 地址格式 [模块/控制器/操作?]参数1=值1&参数2=值2... + * @access private + * @param string $url URL地址 + * @param bool $autoSearch 是否自动深度搜索控制器 + * @param bool $reverse 是否反转解析URL + * @return array + */ private static function parseRoute($url, $autoSearch = false, $reverse = false) { $url = trim($url, '/'); @@ -733,14 +928,20 @@ class Route $action = 0 !== strpos($action, self::$methodPrefix[REQUEST_METHOD]) ? self::$methodPrefix[REQUEST_METHOD] . $action : $action; } } - // 封装路由 $route = [$module, $controller, $action]; } return ['route' => $route, 'var' => $var]; } - // 检测URL和规则路由是否匹配 + /** + * 检测URL和规则路由是否匹配 + * @access private + * @param string $url URL地址 + * @param string $rule 路由规则 + * @param array $pattern 变量规则 + * @return array|false + */ private static function match($url, $rule, $pattern) { $m1 = explode('/', $url); @@ -790,7 +991,15 @@ class Route return $var; } - // 解析规则路由 + /** + * 解析规则路由 + * @access private + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param string $pathinfo URL地址 + * @param array $matches 匹配的变量 + * @return array + */ private static function parseRule($rule, $route, $pathinfo, $matches) { // 获取URL地址中的参数 @@ -843,7 +1052,13 @@ class Route return $result; } - // 解析URL地址中的参数到$_GET + /** + * 解析URL地址中的参数到$_GET + * @access private + * @param string $rule 路由规则 + * @param array $var 变量 + * @return void + */ private static function parseUrlParams($url, $var) { if ($url) { From 15df0ebf342a5bba54c40e304a4f4d913fa734e2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 14:33:28 +0800 Subject: [PATCH 135/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 2 +- library/think/Error.php | 1 - library/think/Loader.php | 1 + library/think/Model.php | 2 +- library/traits/controller/Jump.php | 2 +- 5 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/think/Controller.php b/library/think/Controller.php index ce5c0311..bfaf7da2 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -143,7 +143,7 @@ class Controller public function validate($data, $validate, $message = [], $callback = null) { if (is_array($validate)) { - $v = Loader::validate(Config::get('default_validate')); + $v = Loader::validate(); $v->rule($validate); } else { if (strpos($validate, '.')) { diff --git a/library/think/Error.php b/library/think/Error.php index a1541282..9de97c88 100644 --- a/library/think/Error.php +++ b/library/think/Error.php @@ -59,7 +59,6 @@ class Error * @param string $errfile 出错的文件 * @param integer $errline 出错行号 * @param array $errcontext - * @return bool true-禁止往下传播已处理过的异常 * @throws ErrorException */ public static function appError($errno, $errstr, $errfile = '', $errline = 0, $errcontext = []) diff --git a/library/think/Loader.php b/library/think/Loader.php index 8527db0e..4509c58b 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -332,6 +332,7 @@ class Loader */ public static function validate($name = '', $layer = '', $appendSuffix = false) { + $name = $name ?: Config::get('default_validate'); if (empty($name)) { return new Validate; } diff --git a/library/think/Model.php b/library/think/Model.php index 00f5a3f4..239ebb1b 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -520,7 +520,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (!empty($this->validate)) { $info = $this->validate; if (is_array($info)) { - $validate = Loader::validate(Config::get('default_validate')); + $validate = Loader::validate(); $validate->rule($info['rule']); $validate->message($info['msg']); } else { diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index fb469423..6d2b9967 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -2,7 +2,7 @@ /** * 用法: - * T('controller/Jump'); + * load_trait('controller/Jump'); * class index * { * use \traits\controller\Jump; From 1a772463965a16b60f915f4e54a21cf98429e784 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 14:43:05 +0800 Subject: [PATCH 136/670] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E6=94=B9=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tpl/think_exception.tpl | 1 + 1 file changed, 1 insertion(+) diff --git a/tpl/think_exception.tpl b/tpl/think_exception.tpl index db69fb54..2262fb91 100644 --- a/tpl/think_exception.tpl +++ b/tpl/think_exception.tpl @@ -146,6 +146,7 @@ .exception-var table td{ padding: 0 6px; vertical-align: top; + word-break: break-word; } .exception-var table td:first-child{ width: 12px; From c50741bfa3a0a178303f1d49737bc7750cba149c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 15:29:44 +0800 Subject: [PATCH 137/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 41 +++++++++++++++++++++++++++++----- library/think/Build.php | 43 +++++++++++++++++++++++++++++++----- library/think/Controller.php | 6 ++--- library/think/Cookie.php | 1 - 4 files changed, 76 insertions(+), 15 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index cb0306f3..3ad78006 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -130,7 +130,13 @@ class App } } - // 执行函数或者闭包方法 支持参数调用 + /** + * 执行函数或者闭包方法 支持参数调用 + * @access public + * @param string|array|\Closure $function 函数或者闭包 + * @param array $vars 变量 + * @return mixed + */ public static function invokeFunction($function, $vars = []) { $reflect = new \ReflectionFunction($function); @@ -140,7 +146,13 @@ class App return $reflect->invokeArgs($args); } - // 调用反射执行类的方法 支持参数绑定 + /** + * 调用反射执行类的方法 支持参数绑定 + * @access public + * @param string|array $method 方法 + * @param array $vars 变量 + * @return mixed + */ public static function invokeMethod($method, $vars = []) { if (empty($vars)) { @@ -160,7 +172,13 @@ class App return $reflect->invokeArgs(isset($class) ? $class : null, $args); } - // 绑定参数 + /** + * 绑定参数 + * @access public + * @param \ReflectionMethod $reflect 反射类 + * @param array $vars 变量 + * @return array + */ private static function bindParams($reflect, $vars) { $args = []; @@ -186,7 +204,13 @@ class App return $args; } - // 执行 模块/控制器/操作 + /** + * 执行模块 + * @access public + * @param array $result 模块/控制器/操作 + * @param array $config 配置参数 + * @return mixed + */ public static function module($result, $config) { if (is_string($result)) { @@ -254,7 +278,13 @@ class App return $data; } - // 初始化模块 + /** + * 初始化模块 + * @access public + * @param string $module 模块名 + * @param array $config 配置参数 + * @return void + */ private static function initModule($module, $config) { // 定位模块目录 @@ -308,6 +338,7 @@ class App * @access public * @param \think\Request $request * @param array $config + * @return array * @throws Exception */ public static function route($request, array $config) diff --git a/library/think/Build.php b/library/think/Build.php index 7b26a103..5cc2147e 100644 --- a/library/think/Build.php +++ b/library/think/Build.php @@ -13,7 +13,12 @@ namespace think; class Build { - // 根据传入的build资料创建目录和文件 + /** + * 根据传入的build资料创建目录和文件 + * @access protected + * @param array $build build列表 + * @return void + */ public static function run(array $build = []) { // 锁定 @@ -39,7 +44,12 @@ class Build unlink($lockfile); } - // 创建目录 + /** + * 创建目录 + * @access protected + * @param array $list 目录列表 + * @return void + */ protected static function buildDir($list) { foreach ($list as $dir) { @@ -50,7 +60,12 @@ class Build } } - // 创建文件 + /** + * 创建文件 + * @access protected + * @param array $list 文件列表 + * @return void + */ protected static function buildFile($list) { foreach ($list as $file) { @@ -64,7 +79,13 @@ class Build } } - // 创建模块 + /** + * 创建模块 + * @access public + * @param string $module 模块名 + * @param array $list build列表 + * @return void + */ public static function module($module = '', $list = []) { $module = APP_MULTI_MODULE ? $module : ''; @@ -138,7 +159,12 @@ class Build } } - // 创建模块的欢迎页面 + /** + * 创建模块的欢迎页面 + * @access public + * @param string $module 模块名 + * @return void + */ protected static function buildHello($module) { $filename = APP_PATH . ($module ? $module . DS : '') . CONTROLLER_LAYER . DS . 'Index' . (CLASS_APPEND_SUFFIX ? ucfirst(CONTROLLER_LAYER) : '') . EXT; @@ -152,7 +178,12 @@ class Build } } - // 创建模块的公共文件 + /** + * 创建模块的公共文件 + * @access public + * @param string $module 模块名 + * @return void + */ protected static function buildCommon($module) { $filename = APP_PATH . ($module ? $module . DS : '') . 'config.php'; diff --git a/library/think/Controller.php b/library/think/Controller.php index bfaf7da2..8dafcbbe 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -110,7 +110,7 @@ class Controller /** * 模板变量赋值 - * @access protected + * @access public * @param mixed $name 要显示的模板变量 * @param mixed $value 变量的值 * @return void @@ -122,7 +122,7 @@ class Controller /** * 初始化模板引擎 - * @access protected + * @access public * @param array|string $engine 引擎参数 * @return void */ @@ -133,7 +133,7 @@ class Controller /** * 验证数据 - * @access protected + * @access public * @param array $data 数据 * @param string|array $validate 验证器名或者验证规则数组 * @param array $message 提示信息 diff --git a/library/think/Cookie.php b/library/think/Cookie.php index 3ababc3b..167df72f 100644 --- a/library/think/Cookie.php +++ b/library/think/Cookie.php @@ -13,7 +13,6 @@ namespace think; class Cookie { - protected static $config = [ // cookie 名称前缀 'prefix' => '', From 9879f9e59e23918cceab3b228b000d18b51a65be Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 15:51:24 +0800 Subject: [PATCH 138/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BSession=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Session.php | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/library/think/Session.php b/library/think/Session.php index 35de1bfa..49ecb024 100644 --- a/library/think/Session.php +++ b/library/think/Session.php @@ -220,16 +220,6 @@ class Session } } - /** - * 暂停session - * @return void - */ - public static function pause() - { - // 暂停session - session_write_close(); - } - /** * 启动session * @return void @@ -246,7 +236,9 @@ class Session */ public static function destroy() { - $_SESSION = []; + if (!empty($_SESSION)) { + $_SESSION = []; + } session_unset(); session_destroy(); } @@ -259,4 +251,14 @@ class Session { session_regenerate_id(); } + + /** + * 暂停session + * @return void + */ + public static function pause() + { + // 暂停session + session_write_close(); + } } From c4123537efcb1ddfdfdd68690b45f680744b53f4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 16:03:37 +0800 Subject: [PATCH 139/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BCookie=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 20 ++++++++++++++++++++ library/think/Cookie.php | 3 +++ 2 files changed, 23 insertions(+) diff --git a/convention.php b/convention.php index 8e2f20a1..d958784b 100644 --- a/convention.php +++ b/convention.php @@ -167,6 +167,26 @@ return [ 'auto_start' => true, ], + // +---------------------------------------------------------------------- + // | Cookie设置 + // +---------------------------------------------------------------------- + 'cookie' => [ + // cookie 名称前缀 + 'prefix' => '', + // cookie 保存时间 + 'expire' => 0, + // cookie 保存路径 + 'path' => '/', + // cookie 有效域名 + 'domain' => '', + // cookie 启用安全传输 + 'secure' => false, + // httponly设置 + 'httponly' => '', + // 是否使用 setcookie + 'setcookie' => true, + ], + // +---------------------------------------------------------------------- // | 数据库设置 // +---------------------------------------------------------------------- diff --git a/library/think/Cookie.php b/library/think/Cookie.php index 167df72f..3ca1a0e6 100644 --- a/library/think/Cookie.php +++ b/library/think/Cookie.php @@ -37,6 +37,9 @@ class Cookie */ public static function init(array $config = []) { + if (empty($config)) { + $config = Config::get('session'); + } self::$config = array_merge(self::$config, array_change_key_case($config)); if (!empty(self::$config['httponly'])) { ini_set('session.cookie_httponly', 1); From c779219917c9f6449b60dbd5ef09d27a40dd9be2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 16:13:57 +0800 Subject: [PATCH 140/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Cookie.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Cookie.php b/library/think/Cookie.php index 3ca1a0e6..d21f3226 100644 --- a/library/think/Cookie.php +++ b/library/think/Cookie.php @@ -38,7 +38,7 @@ class Cookie public static function init(array $config = []) { if (empty($config)) { - $config = Config::get('session'); + $config = Config::get('cookie'); } self::$config = array_merge(self::$config, array_change_key_case($config)); if (!empty(self::$config['httponly'])) { From ca1764aa0037cf38e0f4d27c12f9df4d2b032058 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 16:15:24 +0800 Subject: [PATCH 141/670] =?UTF-8?q?=E4=BC=98=E5=8C=96App=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 3ad78006..6a5b669f 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -39,10 +39,7 @@ class App public static function run($request) { // 初始化应用(公共模块) - self::initModule(COMMON_MODULE, Config::get()); - - // 获取配置参数 - $config = Config::get(); + $config = self::initModule(COMMON_MODULE, Config::get()); // 注册根命名空间 if (!empty($config['root_namespace'])) { @@ -227,7 +224,7 @@ class App define('MODULE_PATH', APP_PATH . MODULE_NAME . DS); define('VIEW_PATH', MODULE_PATH . VIEW_LAYER . DS); // 初始化模块 - self::initModule(MODULE_NAME, $config); + $config = self::initModule(MODULE_NAME, $config); } else { throw new Exception('module [ ' . MODULE_NAME . ' ] not exists ', 10005); } @@ -239,21 +236,21 @@ class App } // 获取控制器名 - $controllerName = strip_tags($result[1] ?: Config::get('default_controller')); - defined('CONTROLLER_NAME') or define('CONTROLLER_NAME', Config::get('url_controller_convert') ? strtolower($controllerName) : $controllerName); + $controllerName = strip_tags($result[1] ?: $config['default_controller']); + defined('CONTROLLER_NAME') or define('CONTROLLER_NAME', $config['url_controller_convert'] ? strtolower($controllerName) : $controllerName); // 获取操作名 - $actionName = strip_tags($result[2] ?: Config::get('default_action')); - defined('ACTION_NAME') or define('ACTION_NAME', Config::get('url_action_convert') ? strtolower($actionName) : $actionName); + $actionName = strip_tags($result[2] ?: $config['default_action']); + defined('ACTION_NAME') or define('ACTION_NAME', $config['url_action_convert'] ? strtolower($actionName) : $actionName); // 执行操作 if (!preg_match('/^[A-Za-z](\/|\.|\w)*$/', CONTROLLER_NAME)) { // 安全检测 throw new Exception('illegal controller name:' . CONTROLLER_NAME, 10000); } - $instance = Loader::controller(CONTROLLER_NAME, '', Config::get('use_controller_suffix'), Config::get('empty_controller')); + $instance = Loader::controller(CONTROLLER_NAME, '', $config['use_controller_suffix'], $config['empty_controller']); // 获取当前操作名 - $action = ACTION_NAME . Config::get('action_suffix'); + $action = ACTION_NAME . $config['action_suffix']; try { // 操作方法开始监听 @@ -331,6 +328,7 @@ class App Lang::load($path . 'lang' . DS . LANG_SET . EXT); } } + return Config::get(); } /** From 61397cb1e4ad1accb523c6067b11fdcb73ed5442 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 16:41:09 +0800 Subject: [PATCH 142/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Btemplate=E7=B1=BB?= =?UTF-8?q?=E5=AF=B9=E6=A8=A1=E6=9D=BF=E6=96=87=E4=BB=B6=E7=9A=84=E8=A7=A3?= =?UTF-8?q?=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Template.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/Template.php b/library/think/Template.php index 844448f4..e5430707 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -1049,7 +1049,7 @@ class Template */ private function parseTemplateFile($template) { - if (false === strpos($template, '.')) { + if ('' == pathinfo($template, PATHINFO_EXTENSION)) { if (strpos($template, '@')) { // 跨模块调用模板 $template = str_replace(['/', ':'], $this->config['view_depr'], $template); @@ -1060,6 +1060,7 @@ class Template } $template .= '.' . ltrim($this->config['view_suffix'], '.'); } + if (is_file($template)) { // 记录模板文件的更新时间 $this->includeFile[$template] = filemtime($template); From ff30a2133eb31d041245df238d8e0d07892844d8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 17:10:24 +0800 Subject: [PATCH 143/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index 239ebb1b..f5c5b0fb 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -112,7 +112,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } if (is_null($this->autoWriteTimestamp)) { - $this->autoWriteTimestamp = $this->getConfig('auto_timestamp'); + $this->autoWriteTimestamp = $this->db()->getConfig('auto_timestamp'); } // 执行初始化操作 From 03f49b84611858ccd1c9a81d1ce5061ce50b5903 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 17:16:43 +0800 Subject: [PATCH 144/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRelation=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Relation.php | 66 +++++++++++++++++--------------- 1 file changed, 35 insertions(+), 31 deletions(-) diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index 6379c5bc..2c058096 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -72,41 +72,45 @@ class Relation $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->where($foreignKey, $this->parent->$localKey)->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->toArray() as $key => $val) { - if (strpos($key, '__')) { - list($name, $attr) = explode('__', $key, 2); - if ('pivot' == $name) { - $pivot[$attr] = $val; - unset($set->$key); + if ($relation instanceof Relation) { + // 判断关联类型执行查询 + 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->where($foreignKey, $this->parent->$localKey)->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->toArray() 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); } - $set->pivot = new Pivot($pivot, $this->middle); - } - break; - default: - // 直接返回 - $result = $relation; + break; + default: + // 直接返回 + $result = $relation; + } + return $result; + } else { + return $relation; } - return $result; } /** From 71d5e668d15ca487c76a363da741b47378d706dc Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 18:02:32 +0800 Subject: [PATCH 145/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Bwhere=E5=92=8Cwhereor?= =?UTF-8?q?=E9=97=AD=E5=8C=85=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Builder.php | 1 + library/think/db/Query.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index 91485f86..cfc38ffa 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -263,6 +263,7 @@ abstract class Builder } } } + $whereStr .= empty($whereStr) ? substr(implode(' ', $str), strlen($key) + 1) : implode(' ', $str); } return $whereStr; diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 225500fb..e463320e 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -727,7 +727,7 @@ class Query protected function parseWhereExp($operator, $field, $op, $condition, $param = []) { if ($field instanceof \Closure) { - call_user_func_array($field, [ & $this]); + $this->options['where'][$operator][] = $field; return; } From 87d544f331c4f79d5034e4928d1122d26290b12e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 23 May 2016 18:22:18 +0800 Subject: [PATCH 146/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BValidate=E7=B1=BB?= =?UTF-8?q?=E7=9A=84unique=E8=A7=84=E5=88=99=20=E6=94=AF=E6=8C=81=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E5=AD=97=E6=AE=B5=E5=92=8C=E6=95=B0=E6=8D=AE=E8=A1=A8?= =?UTF-8?q?=E5=AD=97=E6=AE=B5=20=E5=88=86=E5=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Validate.php | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/library/think/Validate.php b/library/think/Validate.php index 69b1778d..e9e532cc 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -696,29 +696,29 @@ class Validate if (is_string($rule)) { $rule = explode(',', $rule); } - $db = Db::name($rule[0]); - $field = isset($rule[1]) ? $rule[1] : $field; + $db = Db::name($rule[0]); + $key = isset($rule[1]) ? $rule[1] : $field; - if (strpos($field, '^')) { + if (strpos($key, '^')) { // 支持多个字段验证 - $fields = explode('^', $field); - foreach ($fields as $field) { - $map[$field] = $data[$field]; + $fields = explode('^', $key); + foreach ($fields as $key) { + $map[$key] = $data[$key]; } - } elseif (strpos($field, '=')) { - parse_str($field, $map); + } elseif (strpos($key, '=')) { + parse_str($key, $map); } else { - $map[$field] = $data[$field]; + $map[$key] = $data[$field]; } - $key = strval(isset($rule[3]) ? $rule[3] : $db->getPk()); + $pk = strval(isset($rule[3]) ? $rule[3] : $db->getPk()); if (isset($rule[2])) { - $map[$key] = ['neq', $rule[2]]; - } elseif (isset($data[$key])) { - $map[$key] = ['neq', $data[$key]]; + $map[$pk] = ['neq', $rule[2]]; + } elseif (isset($data[$pk])) { + $map[$pk] = ['neq', $data[$pk]]; } - if ($db->where($map)->field($key)->find()) { + if ($db->where($map)->field($pk)->find()) { return false; } return true; From 1f4cb837f050c94fc41ae747a3c47bc17034492a Mon Sep 17 00:00:00 2001 From: Moobusy Date: Mon, 23 May 2016 18:46:34 +0800 Subject: [PATCH 147/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E6=97=A0=E6=B3=95=E5=8C=BA=E5=88=86=20hello=20=E5=92=8C=20=20h?= =?UTF-8?q?ello/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正路由无法区分 hello 和 hello/,这应该是两个地址,一个是文件,一个是路径 --- library/think/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index ef9ba1f2..6e032c21 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -324,7 +324,7 @@ class Request } } } - $this->pathinfo = empty($_SERVER['PATH_INFO']) ? '/' : trim($_SERVER['PATH_INFO'], '/'); + $this->pathinfo = empty($_SERVER['PATH_INFO']) ? '/' : ltrim($_SERVER['PATH_INFO'], '/'); } return $this->pathinfo; } From 118800ed934ebd5d923e4eb579c78721be358f3c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 11:34:52 +0800 Subject: [PATCH 148/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84view=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E8=A1=A8=E5=AE=9A=E4=B9=89=E5=88=AB=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index e463320e..1674f42c 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -651,33 +651,39 @@ class Query * @param string $type JOIN类型 * @return $this */ - public function view($join, $field, $on = null, $type = 'INNER') + public function view($join, $field = null, $on = null, $type = 'INNER') { $this->options['view'] = true; - if (is_array($join)) { + if (is_array($join) && is_null($field)) { foreach ($join as $key => $val) { $this->view($key, $val[0], isset($val[1]) ? $val[1] : null, isset($val[2]) ? $val[2] : 'INNER'); } } else { $fields = []; - $table = $this->getTable($join); + if (is_array($join)) { + // 支持数据表别名 + list($join, $alias) = $join; + } else { + $alias = $join; + } + $table = $this->getTable($join); if (is_string($field)) { $field = explode(',', $field); } foreach ($field as $key => $val) { if (is_numeric($key)) { - $fields[] = $join . '.' . $val; - $this->options['map'][$val] = $join . '.' . $val; + $fields[] = $alias . '.' . $val; + $this->options['map'][$val] = $alias . '.' . $val; } else { - $fields[] = $join . '.' . $key . ' AS ' . $val; - $this->options['map'][$val] = $join . '.' . $key; + $fields[] = $alias . '.' . $key . ' AS ' . $val; + $this->options['map'][$val] = $alias . '.' . $key; } } $this->field($fields); if ($on) { - $this->join($table . ' ' . $join, $on, $type); + $this->join($table . ' ' . $alias, $on, $type); } else { - $this->table($table . ' ' . $join); + $this->table($table . ' ' . $alias); } } return $this; From 38f343f69fa5395408262ed3184f33a8deb32078 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 11:53:54 +0800 Subject: [PATCH 149/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E7=9A=84method=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 6e032c21..3aff5d89 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -410,8 +410,7 @@ class Request */ public function method() { - $method = isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']; - return IS_CLI ? 'GET' : $method; + return IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); } /** From 165c72e0aa2ccb44a055b22dda31743c86e756ce Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 12:29:51 +0800 Subject: [PATCH 150/670] =?UTF-8?q?=E5=85=B3=E8=81=94=E5=AE=9A=E4=B9=89?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=95=B0=E6=8D=AE=E8=A1=A8=E5=88=AB=E5=90=8D?= =?UTF-8?q?=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 20 ++++++++++++-------- library/think/db/Query.php | 8 +++++--- library/think/model/Relation.php | 31 +++++++++++++++++++++++++++---- 3 files changed, 44 insertions(+), 15 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index f5c5b0fb..80eb92ea 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -837,15 +837,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $model 模型名 * @param string $foreignKey 关联外键 * @param string $localKey 关联主键 + * @param array $alias 别名定义 * @return \think\db\Query|string */ - public function hasOne($model, $foreignKey = '', $localKey = '') + public function hasOne($model, $foreignKey = '', $localKey = '', $alias = []) { // 记录当前关联信息 $model = $this->parseModel($model); $localKey = $localKey ?: $this->getPk(); $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; - return $this->relation()->hasOne($model, $foreignKey, $localKey); + return $this->relation()->hasOne($model, $foreignKey, $localKey, $alias); } /** @@ -854,15 +855,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $model 模型名 * @param string $foreignKey 关联外键 * @param string $otherKey 关联主键 + * @param array $alias 别名定义 * @return \think\db\Query|string */ - public function belongsTo($model, $foreignKey = '', $otherKey = '') + public function belongsTo($model, $foreignKey = '', $otherKey = '', $alias = []) { // 记录当前关联信息 $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); + return $this->relation()->belongsTo($model, $foreignKey, $otherKey, $alias); } /** @@ -871,15 +873,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $model 模型名 * @param string $foreignKey 关联外键 * @param string $localKey 关联主键 + * @param array $alias 别名定义 * @return \think\db\Query|string */ - public function hasMany($model, $foreignKey = '', $localKey = '') + 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); + return $this->relation()->hasMany($model, $foreignKey, $localKey, $alias); } /** @@ -889,9 +892,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $table 中间表名 * @param string $foreignKey 关联外键 * @param string $localKey 当前模型关联键 + * @param array $alias 别名定义 * @return \think\db\Query|string */ - public function belongsToMany($model, $table = '', $foreignKey = '', $localKey = '') + public function belongsToMany($model, $table = '', $foreignKey = '', $localKey = '', $alias = []) { // 记录当前关联信息 $model = $this->parseModel($model); @@ -899,7 +903,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $table = $table ?: Db::name(Loader::parseName($this->name) . '_' . $name)->getTable(); $foreignKey = $foreignKey ?: $name . '_id'; $localKey = $localKey ?: Loader::parseName($this->name) . '_id'; - return $this->relation()->belongsToMany($model, $table, $foreignKey, $localKey); + return $this->relation()->belongsToMany($model, $table, $foreignKey, $localKey, $alias); } /** diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 1674f42c..bd1138ca 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1294,13 +1294,15 @@ class Query if (0 == $i) { $name = Loader::parseName(basename(str_replace('\\', '/', $currentModel))); $table = $this->getTable(); - $this->table($table)->alias($name)->field(true, false, $table, $name); + $alias = isset($info['alias'][$name]) ? $info['alias'][$name] : $name; + $this->table($table)->alias($alias)->field(true, false, $table, $alias); } // 预载入封装 $joinTable = $model->getTable(); $joinName = Loader::parseName(basename(str_replace('\\', '/', $info['model']))); - $this->via($joinName); - $this->join($joinTable . ' ' . $joinName, $name . '.' . $info['localKey'] . '=' . $joinName . '.' . $info['foreignKey'])->field(true, false, $joinTable, $joinName, $joinName . '__'); + $joinAlias = isset($info['alias'][$joinName]) ? $info['alias'][$joinName] : $joinName; + $this->via($joinAlias); + $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['localKey'] . '=' . $joinAlias . '.' . $info['foreignKey'])->field(true, false, $joinTable, $joinAlias, $joinName . '__'); if ($closure) { // 执行闭包查询 call_user_func_array($closure, [ & $this]); diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index 2c058096..c5965743 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -36,6 +36,8 @@ class Relation protected $foreignKey; // 关联键 protected $localKey; + // 数据表别名 + protected $alias; /** * 架构函数 @@ -61,6 +63,7 @@ class Relation 'middle' => $this->middle, 'foreignKey' => $this->foreignKey, 'localKey' => $this->localKey, + 'alias' => $this->alias, ]; return $name ? $info[$name] : $info; } @@ -371,20 +374,34 @@ class Relation return $data; } + /** + * 设置当前关联定义的数据表别名 + * @access public + * @param array $alias 别名定义 + * @return $this + */ + public function setAlias($alias) + { + $this->alias = $alias; + return $this; + } + /** * HAS ONE 关联定义 * @access public * @param string $model 模型名 * @param string $foreignKey 关联外键 * @param string $localKey 关联主键 + * @param array $alias 别名定义 * @return $this */ - public function hasOne($model, $foreignKey, $localKey) + public function hasOne($model, $foreignKey, $localKey, $alias) { $this->type = self::HAS_ONE; $this->model = $model; $this->foreignKey = $foreignKey; $this->localKey = $localKey; + $this->alias = $alias; // 返回关联的模型对象 return $this; @@ -396,15 +413,17 @@ class Relation * @param string $model 模型名 * @param string $foreignKey 关联外键 * @param string $otherKey 关联主键 + * @param array $alias 别名定义 * @return $this */ - public function belongsTo($model, $foreignKey, $otherKey) + public function belongsTo($model, $foreignKey, $otherKey, $alias) { // 记录当前关联信息 $this->type = self::BELONGS_TO; $this->model = $model; $this->foreignKey = $foreignKey; $this->localKey = $otherKey; + $this->alias = $alias; // 返回关联的模型对象 return $this; @@ -416,15 +435,17 @@ class Relation * @param string $model 模型名 * @param string $foreignKey 关联外键 * @param string $localKey 关联主键 + * @param array $alias 别名定义 * @return $this */ - public function hasMany($model, $foreignKey, $localKey) + public function hasMany($model, $foreignKey, $localKey, $alias) { // 记录当前关联信息 $this->type = self::HAS_MANY; $this->model = $model; $this->foreignKey = $foreignKey; $this->localKey = $localKey; + $this->alias = $alias; // 返回关联的模型对象 return $this; @@ -437,9 +458,10 @@ class Relation * @param string $table 中间表名 * @param string $foreignKey 关联模型外键 * @param string $localKey 当前模型关联键 + * @param array $alias 别名定义 * @return $this */ - public function belongsToMany($model, $table, $foreignKey, $localKey) + public function belongsToMany($model, $table, $foreignKey, $localKey, $alias) { // 记录当前关联信息 $this->type = self::BELONGS_TO_MANY; @@ -447,6 +469,7 @@ class Relation $this->foreignKey = $foreignKey; $this->localKey = $localKey; $this->middle = $table; + $this->alias = $alias; // 返回关联的模型对象 return $this; From 6e11fbc02564f9d3b1a935f1eaffb7f29cab0bd3 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 12:40:21 +0800 Subject: [PATCH 151/670] =?UTF-8?q?App=E7=B1=BB=E7=9A=84run=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E5=8F=82=E6=95=B0=E4=B8=BA=E5=8F=AF=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 6 ++++-- start.php | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 6a5b669f..6120a7b0 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -32,12 +32,14 @@ class App /** * 执行应用程序 * @access public - * @param \think\Request $request Request对象 + * @param null|\think\Request $request Request对象 * @return mixed * @throws Exception */ - public static function run($request) + public static function run($request = null) { + is_null($request) && $request = Request::instance(); + // 初始化应用(公共模块) $config = self::initModule(COMMON_MODULE, Config::get()); diff --git a/start.php b/start.php index 9ad4264e..5ad6f069 100644 --- a/start.php +++ b/start.php @@ -64,5 +64,5 @@ if (APP_HOOK && isset($mode['tags'])) { // 是否自动运行 if (APP_AUTO_RUN) { - App::run(Request::instance()); + App::run(); } From a3fae7c6dc93e61570eabc2242d8fefb9e737a41 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 16:35:57 +0800 Subject: [PATCH 152/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BAppe=E7=B1=BB=20Reque?= =?UTF-8?q?st=E5=92=8CRoute=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 9 ---- library/think/App.php | 19 +++++--- library/think/Request.php | 74 +++++++++++++++++++++++++++++-- library/think/Response.php | 4 ++ library/think/Route.php | 42 ++++++------------ library/think/controller/Rest.php | 2 +- 6 files changed, 103 insertions(+), 47 deletions(-) diff --git a/base.php b/base.php index 41bdd7dd..118d3ac6 100644 --- a/base.php +++ b/base.php @@ -48,14 +48,5 @@ defined('CLASS_APPEND_SUFFIX') or define('CLASS_APPEND_SUFFIX', false); // 是 defined('APP_MODE') or define('APP_MODE', function_exists('saeAutoLoader') ? 'sae' : 'common'); // 环境常量 -define('IS_CGI', strpos(PHP_SAPI, 'cgi') === 0 ? 1 : 0); define('IS_WIN', strstr(PHP_OS, 'WIN') ? 1 : 0); define('IS_MAC', strstr(PHP_OS, 'Darwin') ? 1 : 0); -define('IS_CLI', PHP_SAPI == 'cli' ? 1 : 0); -define('IS_AJAX', (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false); -define('NOW_TIME', $_SERVER['REQUEST_TIME']); -define('REQUEST_METHOD', IS_CLI ? 'GET' : $_SERVER['REQUEST_METHOD']); -define('IS_GET', REQUEST_METHOD == 'GET' ? true : false); -define('IS_POST', REQUEST_METHOD == 'POST' ? true : false); -define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false); -define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false); diff --git a/library/think/App.php b/library/think/App.php index 6120a7b0..6111d8cf 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -28,7 +28,6 @@ use think\Route; */ class App { - /** * 执行应用程序 * @access public @@ -40,6 +39,18 @@ class App { is_null($request) && $request = Request::instance(); + define('NOW_TIME', $request->time()); + define('REQUEST_METHOD', $request->method()); + define('HTTP_HOST', $request->host()); + define('IS_GET', REQUEST_METHOD == 'GET' ? true : false); + define('IS_POST', REQUEST_METHOD == 'POST' ? true : false); + define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false); + define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false); + define('IS_AJAX', $request->isAjax()); + define('__EXT__', $request->ext()); + define('IS_CGI', $request->isCgi()); + define('IS_CLI', $request->isCli()); + // 初始化应用(公共模块) $config = self::initModule(COMMON_MODULE, Config::get()); @@ -343,12 +354,8 @@ class App */ public static function route($request, array $config) { - - define('__INFO__', $request->pathinfo()); - define('__EXT__', $request->ext()); - // 检测URL禁用后缀 - if ($config['url_deny_suffix'] && preg_match('/\.(' . $config['url_deny_suffix'] . ')$/i', __INFO__)) { + if ($config['url_deny_suffix'] && preg_match('/\.(' . $config['url_deny_suffix'] . ')$/i', $request->pathinfo())) { throw new Exception('url suffix deny'); } diff --git a/library/think/Request.php b/library/think/Request.php index 3aff5d89..a63493fc 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -21,6 +21,7 @@ class Request */ protected static $instance; + protected $method; /** * @var string 域名 */ @@ -406,11 +407,78 @@ class Request /** * 当前的请求类型 * @access public + * @param string $method 请求类型 * @return string */ - public function method() + public function method($method = '') { - return IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); + if ($method) { + $this->method = $method; + return; + } elseif (!$this->method) { + $this->method = IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); + } + return $this->method; + } + + /** + * 是否为GET请求 + * @access public + * @return bool + */ + public function isGet() + { + return $this->method() == 'GET'; + } + + /** + * 是否为POST请求 + * @access public + * @return bool + */ + public function isPost() + { + return $this->method() == 'POST'; + } + + /** + * 是否为PUT请求 + * @access public + * @return bool + */ + public function isPut() + { + return $this->method() == 'PUT'; + } + + /** + * 是否为DELTE请求 + * @access public + * @return bool + */ + public function isDelete() + { + return $this->method() == 'DELETE'; + } + + /** + * 是否为cli + * @access public + * @return bool + */ + public function isCli() + { + return PHP_SAPI == 'cli'; + } + + /** + * 是否为cgi + * @access public + * @return bool + */ + public function isCgi() + { + return strpos(PHP_SAPI, 'cgi') === 0; } /** @@ -649,7 +717,7 @@ class Request */ public function host() { - return $this->server('SERVER_NAME'); + return $this->server('HTTP_HOST'); } /** diff --git a/library/think/Response.php b/library/think/Response.php index be0146aa..57aa426e 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -99,6 +99,10 @@ class Response // 处理输出数据 $data = $this->output($data); + + // 监听response_data + APP_HOOK && Hook::listen('response_data', $data); + // 发送头部信息 if (!headers_sent() && !empty($this->header)) { // 发送状态码 diff --git a/library/think/Route.php b/library/think/Route.php index a9c86a3f..55ca38ff 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -252,7 +252,7 @@ class Route * 注册路由分组 * @access public * @param string|array $name 分组名称或者参数 - * @param array $routes 路由地址 + * @param array|\Closure $routes 路由地址 * @param array $option 路由参数 * @param string $type 请求类型 * @param array $pattern 变量规则 @@ -493,16 +493,16 @@ class Route $rules = self::$domain; // 开启子域名部署 支持二级和三级域名 if (!empty($rules)) { - if (isset($rules[$_SERVER['HTTP_HOST']])) { + if (isset($rules[HTTP_HOST])) { // 完整域名或者IP配置 - $rule = $rules[$_SERVER['HTTP_HOST']]; + $rule = $rules[HTTP_HOST]; } else { $rootDomain = Config::get('url_domain_root'); if ($rootDomain) { // 配置域名根 例如 thinkphp.cn 163.com.cn 如果是国家级域名 com.cn net.cn 之类的域名需要配置 - $domain = explode('.', rtrim(stristr($_SERVER['HTTP_HOST'], $rootDomain, true), '.')); + $domain = explode('.', rtrim(stristr(HTTP_HOST, $rootDomain, true), '.')); } else { - $domain = explode('.', $_SERVER['HTTP_HOST'], -2); + $domain = explode('.', HTTP_HOST, -2); } // 子域名配置 if (!empty($domain)) { @@ -586,7 +586,7 @@ class Route { // 检测域名部署 if ($checkDomain) { - self::checkDomain(); + self::checkDomain($request); } // 分隔符替换 确保路由定义使用统一的分隔符 @@ -625,7 +625,7 @@ class Route $pattern = isset($val['pattern']) ? $val['pattern'] : []; // 参数有效性检查 - if (!self::checkOption($option, $url)) { + if (!self::checkOption($option, $url, $request)) { continue; } @@ -645,12 +645,12 @@ class Route $key = array_shift($route); } - $key = $rule . '/' . $key; + $key = $rule . ($key ? '/' . $key : ''); // 检查规则路由 if (is_array($route)) { $option1 = $route[1]; // 检查参数有效性 - if (!self::checkOption($option1, $url)) { + if (!self::checkOption($option1, $url, $rquest)) { continue; } $pattern = array_merge($pattern, isset($route[2]) ? $route[2] : []); @@ -683,7 +683,7 @@ class Route // 执行闭包 return ['type' => 'function', 'function' => $miss, 'params' => []]; } - if (self::checkOption($miss['option'], $url)) { + if (self::checkOption($miss['option'], $url, $request)) { return self::parseRule('', $miss['route'], $url, []); } } @@ -741,15 +741,16 @@ class Route * @access private * @param array $option 路由参数 * @param string $url URL地址 + * @param \think\Request $request Request对象 * @return bool */ - private static function checkOption($option, $url) + private static function checkOption($option, $url, $request) { // 请求类型检测 if ((isset($option['method']) && false === stripos($option['method'], REQUEST_METHOD)) || (isset($option['ext']) && false === stripos($option['ext'], __EXT__)) // 伪静态后缀检测 - || (isset($option['domain']) && !in_array($option['domain'], [$_SERVER['HTTP_HOST'], self::$subDomain])) // 域名检测 - || (!empty($option['https']) && !self::isSsl()) // https检测 + || (isset($option['domain']) && !in_array($option['domain'], [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'])) // 自定义检测 ) { @@ -817,21 +818,6 @@ class Route return false; } - /** - * 判断是否SSL协议 - * @return boolean - */ - public static function isSsl() - { - if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) { - return true; - } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) { - return true; - } else { - return false; - } - } - /** * 解析模块的URL地址 [模块/控制器/操作?]参数1=值1&参数2=值2... * @access public diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index 0a614e4a..e88826d9 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -46,7 +46,7 @@ abstract class Rest $this->_type = __EXT__; } // 请求方式检测 - $method = strtolower($_SERVER['REQUEST_METHOD']); + $method = strtolower(REQUEST_METHOD); if (false === stripos($this->restMethodList, $method)) { // 请求方式非法 则用默认请求方法 $method = $this->restDefaultMethod; From 9d0424d34f7e91b0aefa0bae40c9921804c6820d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 16:43:32 +0800 Subject: [PATCH 153/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 2 ++ library/think/App.php | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/base.php b/base.php index 118d3ac6..f12ae4ac 100644 --- a/base.php +++ b/base.php @@ -48,5 +48,7 @@ defined('CLASS_APPEND_SUFFIX') or define('CLASS_APPEND_SUFFIX', false); // 是 defined('APP_MODE') or define('APP_MODE', function_exists('saeAutoLoader') ? 'sae' : 'common'); // 环境常量 +define('IS_CGI', strpos(PHP_SAPI, 'cgi') === 0 ? 1 : 0); +define('IS_CLI', PHP_SAPI == 'cli' ? 1 : 0); define('IS_WIN', strstr(PHP_OS, 'WIN') ? 1 : 0); define('IS_MAC', strstr(PHP_OS, 'Darwin') ? 1 : 0); diff --git a/library/think/App.php b/library/think/App.php index 6111d8cf..47b0c92c 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -48,8 +48,6 @@ class App define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false); define('IS_AJAX', $request->isAjax()); define('__EXT__', $request->ext()); - define('IS_CGI', $request->isCgi()); - define('IS_CLI', $request->isCli()); // 初始化应用(公共模块) $config = self::initModule(COMMON_MODULE, Config::get()); From d4ab8576b283ad029131a59386a22f917fd0a31c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 16:49:54 +0800 Subject: [PATCH 154/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Route.php b/library/think/Route.php index 55ca38ff..8d140f46 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -650,7 +650,7 @@ class Route if (is_array($route)) { $option1 = $route[1]; // 检查参数有效性 - if (!self::checkOption($option1, $url, $rquest)) { + if (!self::checkOption($option1, $url, $request)) { continue; } $pattern = array_merge($pattern, isset($route[2]) ? $route[2] : []); From e936d7dc7d14089bd41430cbee2dbec39ff26b2a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 17:02:21 +0800 Subject: [PATCH 155/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 2 +- tests/thinkphp/library/think/routeTest.php | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 8d140f46..09c09ac5 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -645,7 +645,7 @@ class Route $key = array_shift($route); } - $key = $rule . ($key ? '/' . $key : ''); + $key = $rule . ($key ? '/' . ltrim($key, '/') : ''); // 检查规则路由 if (is_array($route)) { $option1 = $route[1]; diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index e3d3e20f..242b4a4a 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -166,11 +166,6 @@ class routeTest extends \PHPUnit_Framework_TestCase $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check($request, 'read')); } - public function testSsl() - { - $this->assertEquals(false, Route::isSsl()); - } - public function testDomain() { $_SERVER['HTTP_HOST'] = 'subdomain.thinkphp.cn'; From 901631b8d5691ac32f01f98e5d4aa4cbd0af2b83 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 17:55:05 +0800 Subject: [PATCH 156/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 3 ++- tests/thinkphp/baseTest.php | 7 ------- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 09c09ac5..60521ac3 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -401,7 +401,8 @@ class Route if (strpos($val[1], ':id') && isset($option['var'][$rule])) { $val[1] = str_replace(':id', ':' . $option['var'][$rule], $val[1]); } - self::rule($rule . $val[1] . '$', $route . '/' . $val[2], $val[0], $option, $pattern); + $rule = $rule . $val[1]; + self::rule($rule ? $rule . '$' : '', $route . '/' . $val[2], $val[0], $option, $pattern); } } } diff --git a/tests/thinkphp/baseTest.php b/tests/thinkphp/baseTest.php index 408974bc..a56c7ccd 100644 --- a/tests/thinkphp/baseTest.php +++ b/tests/thinkphp/baseTest.php @@ -46,12 +46,5 @@ class baseTest extends \PHPUnit_Framework_TestCase $this->assertTrue(!is_null(IS_CGI)); $this->assertTrue(!is_null(IS_WIN)); $this->assertTrue(!is_null(IS_CLI)); - $this->assertTrue(is_bool(IS_AJAX)); - $this->assertNotEmpty(NOW_TIME); - $this->assertNotEmpty(REQUEST_METHOD); - $this->assertTrue(is_bool(IS_GET)); - $this->assertTrue(is_bool(IS_POST)); - $this->assertTrue(is_bool(IS_PUT)); - $this->assertTrue(is_bool(IS_DELETE)); } } From 200e51c3b14322f7abdc52a8a70e6bf0b09b956b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 18:30:23 +0800 Subject: [PATCH 157/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Route.php b/library/think/Route.php index 60521ac3..51ac3b40 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -401,7 +401,7 @@ class Route if (strpos($val[1], ':id') && isset($option['var'][$rule])) { $val[1] = str_replace(':id', ':' . $option['var'][$rule], $val[1]); } - $rule = $rule . $val[1]; + $rule = ltrim($rule . $val[1], '/'); self::rule($rule ? $rule . '$' : '', $route . '/' . $val[2], $val[0], $option, $pattern); } } From 11cda0c26d9eb6eecc7355ac992e3432e5de90eb Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 18:45:49 +0800 Subject: [PATCH 158/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= =?UTF-8?q?=E7=9A=84rescource=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 51ac3b40..378400d0 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -401,8 +401,8 @@ class Route if (strpos($val[1], ':id') && isset($option['var'][$rule])) { $val[1] = str_replace(':id', ':' . $option['var'][$rule], $val[1]); } - $rule = ltrim($rule . $val[1], '/'); - self::rule($rule ? $rule . '$' : '', $route . '/' . $val[2], $val[0], $option, $pattern); + $item = ltrim($rule . $val[1], '/'); + self::rule($item ? $item . '$' : '', $route . '/' . $val[2], $val[0], $option, $pattern); } } } From b848abdf3ba2461a602e329714bd068d25950dc8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 18:48:26 +0800 Subject: [PATCH 159/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 378400d0..395e2f49 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -494,16 +494,16 @@ class Route $rules = self::$domain; // 开启子域名部署 支持二级和三级域名 if (!empty($rules)) { - if (isset($rules[HTTP_HOST])) { + if (isset($rules[$_SERVER['HTTP_HOST']])) { // 完整域名或者IP配置 - $rule = $rules[HTTP_HOST]; + $rule = $rules[$_SERVER['HTTP_HOST']]; } else { $rootDomain = Config::get('url_domain_root'); if ($rootDomain) { // 配置域名根 例如 thinkphp.cn 163.com.cn 如果是国家级域名 com.cn net.cn 之类的域名需要配置 - $domain = explode('.', rtrim(stristr(HTTP_HOST, $rootDomain, true), '.')); + $domain = explode('.', rtrim(stristr($_SERVER['HTTP_HOST'], $rootDomain, true), '.')); } else { - $domain = explode('.', HTTP_HOST, -2); + $domain = explode('.', $_SERVER['HTTP_HOST'], -2); } // 子域名配置 if (!empty($domain)) { From 188e64abf667404687b7d3ab0ca1abb4f8a7b42b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 22:08:34 +0800 Subject: [PATCH 160/670] =?UTF-8?q?=E5=8F=96=E6=B6=88APP=5FHOOK=E5=B8=B8?= =?UTF-8?q?=E9=87=8F=20=E9=BB=98=E8=AE=A4=E5=BC=80=E5=90=AF=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 3 +-- library/think/App.php | 10 +++++----- library/think/Log.php | 2 +- library/think/Response.php | 2 +- library/think/Route.php | 2 +- library/think/View.php | 2 +- library/think/log/driver/Trace.php | 6 ++++-- mode/console/App.php | 4 ++-- start.php | 5 +---- 9 files changed, 17 insertions(+), 19 deletions(-) diff --git a/base.php b/base.php index f12ae4ac..c9b54fba 100644 --- a/base.php +++ b/base.php @@ -44,8 +44,7 @@ defined('APP_AUTO_RUN') or define('APP_AUTO_RUN', true); // 是否自动运行 defined('APP_ROUTE_ON') or define('APP_ROUTE_ON', true); // 是否允许路由 defined('APP_ROUTE_MUST') or define('APP_ROUTE_MUST', true); // 是否严格检查路由 defined('CLASS_APPEND_SUFFIX') or define('CLASS_APPEND_SUFFIX', false); // 是否追加类名后缀 -// 应用模式 默认为普通模式 -defined('APP_MODE') or define('APP_MODE', function_exists('saeAutoLoader') ? 'sae' : 'common'); +defined('APP_MODE') or define('APP_MODE', 'common'); // 应用模式 默认为普通模式 // 环境常量 define('IS_CGI', strpos(PHP_SAPI, 'cgi') === 0 ? 1 : 0); diff --git a/library/think/App.php b/library/think/App.php index 47b0c92c..2e7f4247 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -71,7 +71,7 @@ class App date_default_timezone_set($config['default_timezone']); // 监听app_init - APP_HOOK && Hook::listen('app_init'); + Hook::listen('app_init'); // 开启多语言机制 if ($config['lang_switch_on']) { @@ -93,7 +93,7 @@ class App // 记录路由信息 APP_DEBUG && Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info'); // 监听app_begin - APP_HOOK && Hook::listen('app_begin', $dispatch); + Hook::listen('app_begin', $dispatch); try { switch ($dispatch['type']) { case 'redirect': @@ -127,7 +127,7 @@ class App } // 监听app_end - APP_HOOK && Hook::listen('app_end', $data); + Hook::listen('app_end', $data); // 输出数据到客户端 if ($data instanceof Response) { @@ -266,7 +266,7 @@ class App try { // 操作方法开始监听 $call = [$instance, $action]; - APP_HOOK && Hook::listen('action_begin', $call); + Hook::listen('action_begin', $call); if (!preg_match('/^[A-Za-z](\w)*$/', $action)) { // 非法操作 throw new \ReflectionException('illegal action name :' . ACTION_NAME); @@ -325,7 +325,7 @@ class App } // 加载行为扩展文件 - if (APP_HOOK && is_file($path . 'tags' . EXT)) { + if (is_file($path . 'tags' . EXT)) { Hook::import(include $path . 'tags' . EXT); } diff --git a/library/think/Log.php b/library/think/Log.php index a7cb4ec9..ffa03fd4 100644 --- a/library/think/Log.php +++ b/library/think/Log.php @@ -126,7 +126,7 @@ class Log $log[] = ['type' => $type, 'msg' => $msg]; // 监听log_write - APP_HOOK && Hook::listen('log_write', $log); + Hook::listen('log_write', $log); if (is_null(self::$driver)) { self::init(Config::get('log')); } diff --git a/library/think/Response.php b/library/think/Response.php index 57aa426e..13a5dc76 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -101,7 +101,7 @@ class Response $data = $this->output($data); // 监听response_data - APP_HOOK && Hook::listen('response_data', $data); + Hook::listen('response_data', $data); // 发送头部信息 if (!headers_sent() && !empty($this->header)) { diff --git a/library/think/Route.php b/library/think/Route.php index 395e2f49..372e9582 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -750,7 +750,7 @@ class Route // 请求类型检测 if ((isset($option['method']) && false === stripos($option['method'], REQUEST_METHOD)) || (isset($option['ext']) && false === stripos($option['ext'], __EXT__)) // 伪静态后缀检测 - || (isset($option['domain']) && !in_array($option['domain'], [HTTP_HOST, self::$subDomain])) // 域名检测 + || (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'])) // 自定义检测 diff --git a/library/think/View.php b/library/think/View.php index 2cd90226..84f2e428 100644 --- a/library/think/View.php +++ b/library/think/View.php @@ -117,7 +117,7 @@ class View // 获取并清空缓存 $content = ob_get_clean(); // 内容过滤标签 - APP_HOOK && Hook::listen('view_filter', $content); + Hook::listen('view_filter', $content); // 允许用户自定义模板的字符串替换 $replace = array_merge($this->replace, $replace); if (!empty($replace)) { diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index e4565c83..d0501b2f 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -11,7 +11,9 @@ namespace think\log\driver; +use think\Cache; use think\Config; +use think\Db; use think\Debug; /** @@ -53,8 +55,8 @@ class Trace $base = [ '请求信息' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']) . ' ' . $_SERVER['SERVER_PROTOCOL'] . ' ' . $_SERVER['REQUEST_METHOD'] . ' : ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '运行时间' => "{$runtime}s [ 吞吐率:{$reqs}req/s ] 内存消耗:{$mem}kb 文件加载:" . count(get_included_files()), - '查询信息' => \think\Db::$queryTimes . ' queries ' . \think\Db::$executeTimes . ' writes ', - '缓存信息' => \think\Cache::$readTimes . ' reads,' . \think\Cache::$writeTimes . ' writes', + '查询信息' => Db::$queryTimes . ' queries ' . Db::$executeTimes . ' writes ', + '缓存信息' => Cache::$readTimes . ' reads,' . Cache::$writeTimes . ' writes', '配置加载' => count(Config::get()), ]; diff --git a/mode/console/App.php b/mode/console/App.php index fd19be16..01594d58 100644 --- a/mode/console/App.php +++ b/mode/console/App.php @@ -73,7 +73,7 @@ class App } // 加载行为扩展文件 - if (APP_HOOK && is_file(APP_PATH . 'tags' . EXT)) { + if (is_file(APP_PATH . 'tags' . EXT)) { Hook::import(include APP_PATH . 'tags' . EXT); } @@ -102,6 +102,6 @@ class App date_default_timezone_set($config['default_timezone']); // 监听app_init - APP_HOOK && Hook::listen('app_init'); + Hook::listen('app_init'); } } \ No newline at end of file diff --git a/start.php b/start.php index 5ad6f069..b8fa8b9b 100644 --- a/start.php +++ b/start.php @@ -54,11 +54,8 @@ if (isset($mode['config'])) { is_array($mode['config']) ? Config::set($mode['config']) : Config::load($mode['config']); } -// 是否开启HOOK -defined('APP_HOOK') or define('APP_HOOK', false); - // 加载模式行为定义 -if (APP_HOOK && isset($mode['tags'])) { +if (isset($mode['tags'])) { Hook::import($mode['tags']); } From fb09cad6de6cd4bbca513458516d907af3e5af50 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 22:09:30 +0800 Subject: [PATCH 161/670] =?UTF-8?q?=E5=88=A0=E9=99=A4route=E5=8A=A9?= =?UTF-8?q?=E6=89=8B=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/helper.php b/helper.php index 0a3206fd..0a458e5b 100644 --- a/helper.php +++ b/helper.php @@ -24,7 +24,6 @@ use think\Loader; use think\Log; use think\Request; use think\Response; -use think\Route; use think\Session; use think\Url; use think\View; @@ -336,20 +335,6 @@ function trace($log = '[think]', $level = 'log') } } -/** - * 路由注册 - * @param string $rule 路由规则 - * @param mixed $route 路由地址 - * @param sting $type 请求类型 - * @param array $option 路由参数 - * @param array $pattern 变量规则 - * @return void - */ -function route($rule = '', $route = [], $type = '*', $option = [], $pattern = []) -{ - Route::rule($rule, $route, $type, $option, $pattern); -} - /** * 获取当前Request对象实例 * @return \think\Request From 53c3312b0282ab38864de0fc962213fde02b3b5c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 22:16:51 +0800 Subject: [PATCH 162/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/thinkphp/baseTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/thinkphp/baseTest.php b/tests/thinkphp/baseTest.php index a56c7ccd..85f63a2e 100644 --- a/tests/thinkphp/baseTest.php +++ b/tests/thinkphp/baseTest.php @@ -39,7 +39,6 @@ class baseTest extends \PHPUnit_Framework_TestCase $this->assertNotEmpty(VIEW_LAYER); $this->assertNotEmpty(CONTROLLER_LAYER); $this->assertTrue(is_bool(APP_DEBUG)); - $this->assertTrue(is_bool(APP_HOOK)); $this->assertNotEmpty(ENV_PREFIX); $this->assertTrue(is_bool(IS_API)); $this->assertNotEmpty(APP_MODE); From 44e86a7f5359ce6e156bed64503a8a50dc1e1a1e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 May 2016 22:33:52 +0800 Subject: [PATCH 163/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84view=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index bd1138ca..a5e042b8 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -662,11 +662,11 @@ class Query $fields = []; if (is_array($join)) { // 支持数据表别名 - list($join, $alias) = $join; + list($join, $alias, $table) = array_pad($join, 3, ''); } else { $alias = $join; } - $table = $this->getTable($join); + $table = !empty($table) ? $table : $this->getTable($join); if (is_string($field)) { $field = explode(',', $field); } From 1a02bb7081f3461844af1bd10383f934c96f0300 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 10:29:25 +0800 Subject: [PATCH 164/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Request=E7=B1=BB?= =?UTF-8?q?=E7=9A=84baseUrl=E6=96=B9=E6=B3=95=20=E4=BF=AE=E6=AD=A3Hook?= =?UTF-8?q?=E7=B1=BB=E7=9A=84=E8=AD=A6=E5=91=8A=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 1 + library/think/App.php | 2 -- library/think/Hook.php | 3 ++- library/think/Request.php | 3 ++- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/base.php b/base.php index c9b54fba..df8eba84 100644 --- a/base.php +++ b/base.php @@ -51,3 +51,4 @@ define('IS_CGI', strpos(PHP_SAPI, 'cgi') === 0 ? 1 : 0); define('IS_CLI', PHP_SAPI == 'cli' ? 1 : 0); define('IS_WIN', strstr(PHP_OS, 'WIN') ? 1 : 0); define('IS_MAC', strstr(PHP_OS, 'Darwin') ? 1 : 0); +define('NOW_TIME', $_SERVER['REQUEST_TIME']); diff --git a/library/think/App.php b/library/think/App.php index 2e7f4247..f58350f6 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -39,9 +39,7 @@ class App { is_null($request) && $request = Request::instance(); - define('NOW_TIME', $request->time()); define('REQUEST_METHOD', $request->method()); - define('HTTP_HOST', $request->host()); define('IS_GET', REQUEST_METHOD == 'GET' ? true : false); define('IS_POST', REQUEST_METHOD == 'POST' ? true : false); define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false); diff --git a/library/think/Hook.php b/library/think/Hook.php index 8e6b846c..b789d08a 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -43,8 +43,9 @@ class Hook * @param boolean $recursive 是否递归合并 * @return void */ - public static function import(array $tags, $recursive = true) + public static function import($tags, $recursive = true) { + empty($tags) && $tags = []; if (!$recursive) { // 覆盖导入 self::$tags = array_merge(self::$tags, $tags); diff --git a/library/think/Request.php b/library/think/Request.php index a63493fc..c205f970 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -240,7 +240,8 @@ class Request $this->baseUrl = $url; return; } elseif (!$this->baseUrl) { - $this->baseUrl = rtrim($this->url(), '?' . $this->query()); + $str = $this->url(); + $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str; } return true === $url ? $this->domain() . $this->baseUrl : $this->baseUrl; } From db4cbebd2ec87d4cbbd2853918870c71c6b62168 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 11:32:40 +0800 Subject: [PATCH 165/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BPgsql=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/connector/Pgsql.php | 2 +- library/think/db/connector/pgsql.sql | 117 +++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 library/think/db/connector/pgsql.sql diff --git a/library/think/db/connector/Pgsql.php b/library/think/db/connector/Pgsql.php index a2c40b17..350803a8 100644 --- a/library/think/db/connector/Pgsql.php +++ b/library/think/db/connector/Pgsql.php @@ -45,7 +45,7 @@ class Pgsql extends Connection { $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 . ');'; + $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 . '\');'; $pdo = $this->linkID->query($sql); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; diff --git a/library/think/db/connector/pgsql.sql b/library/think/db/connector/pgsql.sql new file mode 100644 index 00000000..e1a09a30 --- /dev/null +++ b/library/think/db/connector/pgsql.sql @@ -0,0 +1,117 @@ +CREATE OR REPLACE FUNCTION pgsql_type(a_type varchar) RETURNS varchar AS +$BODY$ +DECLARE + v_type varchar; +BEGIN + IF a_type='int8' THEN + v_type:='bigint'; + ELSIF a_type='int4' THEN + v_type:='integer'; + ELSIF a_type='int2' THEN + v_type:='smallint'; + ELSIF a_type='bpchar' THEN + v_type:='char'; + ELSE + v_type:=a_type; + END IF; + RETURN v_type; +END; +$BODY$ +LANGUAGE PLPGSQL; + +CREATE TYPE "public"."tablestruct" AS ( + "fields_key_name" varchar(100), + "fields_name" VARCHAR(200), + "fields_type" VARCHAR(20), + "fields_length" BIGINT, + "fields_not_null" VARCHAR(10), + "fields_default" VARCHAR(500), + "fields_comment" VARCHAR(1000) +); + +CREATE OR REPLACE FUNCTION "public"."table_msg" (a_schema_name varchar, a_table_name varchar) RETURNS SETOF "public"."tablestruct" AS +$body$ +DECLARE + v_ret tablestruct; + v_oid oid; + v_sql varchar; + v_rec RECORD; + v_key varchar; +BEGIN + SELECT + pg_class.oid INTO v_oid + FROM + pg_class + INNER JOIN pg_namespace ON (pg_class.relnamespace = pg_namespace.oid AND lower(pg_namespace.nspname) = a_schema_name) + WHERE + pg_class.relname=a_table_name; + IF NOT FOUND THEN + RETURN; + END IF; + + v_sql=' + SELECT + pg_attribute.attname AS fields_name, + pg_attribute.attnum AS fields_index, + pgsql_type(pg_type.typname::varchar) AS fields_type, + pg_attribute.atttypmod-4 as fields_length, + CASE WHEN pg_attribute.attnotnull THEN ''not null'' + ELSE '''' + END AS fields_not_null, + pg_attrdef.adsrc AS fields_default, + pg_description.description AS fields_comment + FROM + pg_attribute + INNER JOIN pg_class ON pg_attribute.attrelid = pg_class.oid + INNER JOIN pg_type ON pg_attribute.atttypid = pg_type.oid + LEFT OUTER JOIN pg_attrdef ON pg_attrdef.adrelid = pg_class.oid AND pg_attrdef.adnum = pg_attribute.attnum + LEFT OUTER JOIN pg_description ON pg_description.objoid = pg_class.oid AND pg_description.objsubid = pg_attribute.attnum + WHERE + pg_attribute.attnum > 0 + AND attisdropped <> ''t'' + AND pg_class.oid = ' || v_oid || ' + ORDER BY pg_attribute.attnum' ; + + FOR v_rec IN EXECUTE v_sql LOOP + v_ret.fields_name=v_rec.fields_name; + v_ret.fields_type=v_rec.fields_type; + IF v_rec.fields_length > 0 THEN + v_ret.fields_length:=v_rec.fields_length; + ELSE + v_ret.fields_length:=NULL; + END IF; + v_ret.fields_not_null=v_rec.fields_not_null; + v_ret.fields_default=v_rec.fields_default; + v_ret.fields_comment=v_rec.fields_comment; + SELECT constraint_name INTO v_key FROM information_schema.key_column_usage WHERE table_schema=a_schema_name AND table_name=a_table_name AND column_name=v_rec.fields_name; + IF FOUND THEN + v_ret.fields_key_name=v_key; + ELSE + v_ret.fields_key_name=''; + END IF; + RETURN NEXT v_ret; + END LOOP; + RETURN ; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; + +COMMENT ON FUNCTION "public"."table_msg"(a_schema_name varchar, a_table_name varchar) +IS '获得表信息'; + +---重载一个函数 +CREATE OR REPLACE FUNCTION "public"."table_msg" (a_table_name varchar) RETURNS SETOF "public"."tablestruct" AS +$body$ +DECLARE + v_ret tablestruct; +BEGIN + FOR v_ret IN SELECT * FROM table_msg('public',a_table_name) LOOP + RETURN NEXT v_ret; + END LOOP; + RETURN; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; + +COMMENT ON FUNCTION "public"."table_msg"(a_table_name varchar) +IS '获得表信息'; \ No newline at end of file From f0c84ac46b4e87959b4ab779b0a02efc32c1cada Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 11:54:49 +0800 Subject: [PATCH 166/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3console=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=E4=B8=8B=E9=9D=A2=E6=97=A5=E5=BF=97=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/File.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/log/driver/File.php b/library/think/log/driver/File.php index 0f781866..d525e4ca 100644 --- a/library/think/log/driver/File.php +++ b/library/think/log/driver/File.php @@ -74,7 +74,7 @@ class File $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 = REQUEST_METHOD; + $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'CLI'; $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; return error_log("[{$now}] {$server} {$remote} {$method} {$uri}\r\n{$info}\r\n", 3, $destination); } From 4ccb4c6bdf5ba36826861e6682f74f808b7f6c38 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 12:04:53 +0800 Subject: [PATCH 167/670] =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E5=AE=9A=E4=B9=89?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Hook.php | 3 ++ library/think/Url.php | 4 ++ mode/common.php | 89 ++++++++++++++++++++------------------- mode/sae.php | 95 ++++++++++++++++++++++-------------------- 4 files changed, 102 insertions(+), 89 deletions(-) diff --git a/library/think/Hook.php b/library/think/Hook.php index b789d08a..b2cb0471 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -11,6 +11,9 @@ namespace think; +use think\Debug; +use think\Log; + class Hook { diff --git a/library/think/Url.php b/library/think/Url.php index bd895c25..de222ea5 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -11,6 +11,10 @@ namespace think; +use think\Cache; +use think\Config; +use think\Route; + class Url { /** diff --git a/mode/common.php b/mode/common.php index e29cffdc..b56e1f06 100644 --- a/mode/common.php +++ b/mode/common.php @@ -26,48 +26,51 @@ return [ // 别名定义 'alias' => [ - 'think\App' => CORE_PATH . 'App' . EXT, - 'think\Build' => CORE_PATH . 'Build' . EXT, - 'think\Cache' => CORE_PATH . 'Cache' . EXT, - 'think\Config' => CORE_PATH . 'Config' . EXT, - 'think\Console' => CORE_PATH . 'Console' . EXT, - 'think\Controller' => CORE_PATH . 'Controller' . EXT, - 'think\Cookie' => CORE_PATH . 'Cookie' . EXT, - 'think\Db' => CORE_PATH . 'Db' . EXT, - 'think\Debug' => CORE_PATH . 'Debug' . EXT, - 'think\Error' => CORE_PATH . 'Error' . EXT, - 'think\Exception' => CORE_PATH . 'Exception' . EXT, - 'think\exception\DbException' => CORE_PATH . 'exception' . DS . 'DbException' . EXT, - 'think\exception\PDOException' => CORE_PATH . 'exception' . DS . 'PDOException' . EXT, - 'think\exception\ErrorException' => CORE_PATH . 'exception' . DS . 'ErrorException' . EXT, - 'think\exception\DbBindParamException' => CORE_PATH . 'exception' . DS . 'DbBindParamException' . EXT, - 'think\exception\NotFoundException' => CORE_PATH . 'exception' . DS . 'NotFoundException' . EXT, - 'think\File' => CORE_PATH . 'File' . EXT, - 'think\Hook' => CORE_PATH . 'Hook' . EXT, - 'think\Input' => CORE_PATH . 'Input' . EXT, - 'think\Lang' => CORE_PATH . 'Lang' . EXT, - 'think\Log' => CORE_PATH . 'Log' . EXT, - 'think\Model' => CORE_PATH . 'Model' . EXT, - 'think\model\Relation' => CORE_PATH . 'model' . DS . 'Relation' . EXT, - 'think\model\Merge' => CORE_PATH . 'model' . DS . 'Merge' . EXT, - 'think\model\Pivot' => CORE_PATH . 'model' . DS . 'Pivot' . EXT, - 'think\Response' => CORE_PATH . 'Response' . EXT, - 'think\Process' => CORE_PATH . 'Process' . EXT, - 'think\Route' => CORE_PATH . 'Route' . EXT, - 'think\Session' => CORE_PATH . 'Session' . EXT, - 'think\Template' => CORE_PATH . 'Template' . EXT, - 'think\Url' => CORE_PATH . 'Url' . EXT, - 'think\Validate' => CORE_PATH . 'Validate' . EXT, - 'think\View' => CORE_PATH . 'View' . EXT, - 'think\db\Connection' => CORE_PATH . 'db' . DS . 'Connection' . EXT, - 'think\db\connector\Mysql' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Mysql' . EXT, - 'think\db\Builder' => CORE_PATH . 'db' . DS . 'Builder' . EXT, - 'think\db\Builder\Mysql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Mysql' . EXT, - 'think\db\Query' => CORE_PATH . 'db' . DS . 'Query' . EXT, - 'think\view\driver\Think' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Think' . EXT, - 'think\view\driver\Php' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Php' . EXT, - 'think\template\driver\File' => CORE_PATH . 'template' . DS . 'driver' . DS . 'File' . EXT, - 'think\log\driver\File' => CORE_PATH . 'log' . DS . 'driver' . DS . 'File' . EXT, - 'think\cache\driver\File' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'File' . EXT, + 'think\App' => CORE_PATH . 'App' . EXT, + 'think\Build' => CORE_PATH . 'Build' . EXT, + 'think\Cache' => CORE_PATH . 'Cache' . EXT, + 'think\Config' => CORE_PATH . 'Config' . EXT, + 'think\Console' => CORE_PATH . 'Console' . EXT, + 'think\Controller' => CORE_PATH . 'Controller' . EXT, + 'think\Cookie' => CORE_PATH . 'Cookie' . EXT, + 'think\Db' => CORE_PATH . 'Db' . EXT, + 'think\Debug' => CORE_PATH . 'Debug' . EXT, + 'think\Error' => CORE_PATH . 'Error' . EXT, + 'think\Exception' => CORE_PATH . 'Exception' . EXT, + 'think\exception\DbException' => CORE_PATH . 'exception' . DS . 'DbException' . EXT, + 'think\exception\Handle' => CORE_PATH . 'exception' . DS . 'Handle' . EXT, + 'think\exception\HttpException' => CORE_PATH . 'exception' . DS . 'HttpException' . EXT, + 'think\exception\HttpResponseException' => CORE_PATH . 'exception' . DS . 'HttpResponseException' . EXT, + 'think\exception\PDOException' => CORE_PATH . 'exception' . DS . 'PDOException' . EXT, + 'think\exception\ErrorException' => CORE_PATH . 'exception' . DS . 'ErrorException' . EXT, + 'think\exception\DbBindParamException' => CORE_PATH . 'exception' . DS . 'DbBindParamException' . EXT, + 'think\exception\ThrowableError' => CORE_PATH . 'exception' . DS . 'ThrowableError' . EXT, + 'think\File' => CORE_PATH . 'File' . EXT, + 'think\Hook' => CORE_PATH . 'Hook' . EXT, + 'think\Input' => CORE_PATH . 'Input' . EXT, + 'think\Lang' => CORE_PATH . 'Lang' . EXT, + 'think\Log' => CORE_PATH . 'Log' . EXT, + 'think\Model' => CORE_PATH . 'Model' . EXT, + 'think\model\Relation' => CORE_PATH . 'model' . DS . 'Relation' . EXT, + 'think\model\Merge' => CORE_PATH . 'model' . DS . 'Merge' . EXT, + 'think\model\Pivot' => CORE_PATH . 'model' . DS . 'Pivot' . EXT, + 'think\Response' => CORE_PATH . 'Response' . EXT, + 'think\Process' => CORE_PATH . 'Process' . EXT, + 'think\Route' => CORE_PATH . 'Route' . EXT, + 'think\Session' => CORE_PATH . 'Session' . EXT, + 'think\Template' => CORE_PATH . 'Template' . EXT, + 'think\Url' => CORE_PATH . 'Url' . EXT, + 'think\Validate' => CORE_PATH . 'Validate' . EXT, + 'think\View' => CORE_PATH . 'View' . EXT, + 'think\db\Connection' => CORE_PATH . 'db' . DS . 'Connection' . EXT, + 'think\db\connector\Mysql' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Mysql' . EXT, + 'think\db\Builder' => CORE_PATH . 'db' . DS . 'Builder' . EXT, + 'think\db\Builder\Mysql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Mysql' . EXT, + 'think\db\Query' => CORE_PATH . 'db' . DS . 'Query' . EXT, + 'think\view\driver\Think' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Think' . EXT, + 'think\view\driver\Php' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Php' . EXT, + 'think\template\driver\File' => CORE_PATH . 'template' . DS . 'driver' . DS . 'File' . EXT, + 'think\log\driver\File' => CORE_PATH . 'log' . DS . 'driver' . DS . 'File' . EXT, + 'think\cache\driver\File' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'File' . EXT, ], ]; diff --git a/mode/sae.php b/mode/sae.php index c17d12c8..4a944a6a 100644 --- a/mode/sae.php +++ b/mode/sae.php @@ -70,52 +70,55 @@ return [ // 别名定义 'alias' => [ - 'think\App' => CORE_PATH . 'App' . EXT, - 'think\Build' => CORE_PATH . 'Build' . EXT, - 'think\Cache' => CORE_PATH . 'Cache' . EXT, - 'think\Config' => CORE_PATH . 'Config' . EXT, - 'think\Console' => CORE_PATH . 'Console' . EXT, - 'think\Controller' => CORE_PATH . 'Controller' . EXT, - 'think\Cookie' => CORE_PATH . 'Cookie' . EXT, - 'think\Db' => CORE_PATH . 'Db' . EXT, - 'think\Debug' => CORE_PATH . 'Debug' . EXT, - 'think\Error' => CORE_PATH . 'Error' . EXT, - 'think\Exception' => CORE_PATH . 'Exception' . EXT, - 'think\exception\DbException' => CORE_PATH . 'exception' . DS . 'DbException' . EXT, - 'think\exception\PDOException' => CORE_PATH . 'exception' . DS . 'PDOException' . EXT, - 'think\exception\ErrorException' => CORE_PATH . 'exception' . DS . 'ErrorException' . EXT, - 'think\exception\DbBindParamException' => CORE_PATH . 'exception' . DS . 'DbBindParamException' . EXT, - 'think\exception\NotFoundException' => CORE_PATH . 'exception' . DS . 'NotFoundException' . EXT, - 'think\File' => CORE_PATH . 'File' . EXT, - 'think\Hook' => CORE_PATH . 'Hook' . EXT, - 'think\Input' => CORE_PATH . 'Input' . EXT, - 'think\Lang' => CORE_PATH . 'Lang' . EXT, - 'think\Log' => CORE_PATH . 'Log' . EXT, - 'think\Model' => CORE_PATH . 'Model' . EXT, - 'think\model\Relation' => CORE_PATH . 'model' . DS . 'Relation' . EXT, - 'think\model\Merge' => CORE_PATH . 'model' . DS . 'Merge' . EXT, - 'think\model\Pivot' => CORE_PATH . 'model' . DS . 'Pivot' . EXT, - 'think\Process' => CORE_PATH . 'Process' . EXT, - 'think\Response' => CORE_PATH . 'Response' . EXT, - 'think\Route' => CORE_PATH . 'Route' . EXT, - 'think\Session' => CORE_PATH . 'Session' . EXT, - 'think\Template' => CORE_PATH . 'Template' . EXT, - 'think\Url' => CORE_PATH . 'Url' . EXT, - 'think\Validate' => CORE_PATH . 'Validate' . EXT, - 'think\View' => CORE_PATH . 'View' . EXT, - 'think\db\Connection' => CORE_PATH . 'db' . DS . 'Connection' . EXT, - 'think\db\connector\Mysql' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Mysql' . EXT, - 'think\db\Builder' => CORE_PATH . 'db' . DS . 'Builder' . EXT, - 'think\db\Builder\Mysql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Mysql' . EXT, - 'think\db\Query' => CORE_PATH . 'db' . DS . 'Query' . EXT, - 'think\view\driver\Think' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Think' . EXT, - 'think\view\driver\Php' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Php' . EXT, - 'think\template\driver\File' => CORE_PATH . 'template' . DS . 'driver' . DS . 'File' . EXT, - 'think\log\driver\File' => CORE_PATH . 'log' . DS . 'driver' . DS . 'File' . EXT, - 'think\cache\driver\File' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'File' . EXT, - 'think\log\driver\Sae' => CORE_PATH . 'log' . DS . 'driver' . DS . 'Sae' . EXT, - 'think\cache\driver\Sae' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Sae' . EXT, - 'think\template\driver\Sae' => CORE_PATH . 'template' . DS . 'driver' . DS . 'Sae' . EXT, + 'think\App' => CORE_PATH . 'App' . EXT, + 'think\Build' => CORE_PATH . 'Build' . EXT, + 'think\Cache' => CORE_PATH . 'Cache' . EXT, + 'think\Config' => CORE_PATH . 'Config' . EXT, + 'think\Console' => CORE_PATH . 'Console' . EXT, + 'think\Controller' => CORE_PATH . 'Controller' . EXT, + 'think\Cookie' => CORE_PATH . 'Cookie' . EXT, + 'think\Db' => CORE_PATH . 'Db' . EXT, + 'think\Debug' => CORE_PATH . 'Debug' . EXT, + 'think\Error' => CORE_PATH . 'Error' . EXT, + 'think\Exception' => CORE_PATH . 'Exception' . EXT, + 'think\exception\DbException' => CORE_PATH . 'exception' . DS . 'DbException' . EXT, + 'think\exception\Handle' => CORE_PATH . 'exception' . DS . 'Handle' . EXT, + 'think\exception\HttpException' => CORE_PATH . 'exception' . DS . 'HttpException' . EXT, + 'think\exception\HttpResponseException' => CORE_PATH . 'exception' . DS . 'HttpResponseException' . EXT, + 'think\exception\PDOException' => CORE_PATH . 'exception' . DS . 'PDOException' . EXT, + 'think\exception\ErrorException' => CORE_PATH . 'exception' . DS . 'ErrorException' . EXT, + 'think\exception\DbBindParamException' => CORE_PATH . 'exception' . DS . 'DbBindParamException' . EXT, + 'think\exception\ThrowableError' => CORE_PATH . 'exception' . DS . 'ThrowableError' . EXT, + 'think\File' => CORE_PATH . 'File' . EXT, + 'think\Hook' => CORE_PATH . 'Hook' . EXT, + 'think\Input' => CORE_PATH . 'Input' . EXT, + 'think\Lang' => CORE_PATH . 'Lang' . EXT, + 'think\Log' => CORE_PATH . 'Log' . EXT, + 'think\Model' => CORE_PATH . 'Model' . EXT, + 'think\model\Relation' => CORE_PATH . 'model' . DS . 'Relation' . EXT, + 'think\model\Merge' => CORE_PATH . 'model' . DS . 'Merge' . EXT, + 'think\model\Pivot' => CORE_PATH . 'model' . DS . 'Pivot' . EXT, + 'think\Process' => CORE_PATH . 'Process' . EXT, + 'think\Response' => CORE_PATH . 'Response' . EXT, + 'think\Route' => CORE_PATH . 'Route' . EXT, + 'think\Session' => CORE_PATH . 'Session' . EXT, + 'think\Template' => CORE_PATH . 'Template' . EXT, + 'think\Url' => CORE_PATH . 'Url' . EXT, + 'think\Validate' => CORE_PATH . 'Validate' . EXT, + 'think\View' => CORE_PATH . 'View' . EXT, + 'think\db\Connection' => CORE_PATH . 'db' . DS . 'Connection' . EXT, + 'think\db\connector\Mysql' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Mysql' . EXT, + 'think\db\Builder' => CORE_PATH . 'db' . DS . 'Builder' . EXT, + 'think\db\Builder\Mysql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Mysql' . EXT, + 'think\db\Query' => CORE_PATH . 'db' . DS . 'Query' . EXT, + 'think\view\driver\Think' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Think' . EXT, + 'think\view\driver\Php' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Php' . EXT, + 'think\template\driver\File' => CORE_PATH . 'template' . DS . 'driver' . DS . 'File' . EXT, + 'think\log\driver\File' => CORE_PATH . 'log' . DS . 'driver' . DS . 'File' . EXT, + 'think\cache\driver\File' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'File' . EXT, + 'think\log\driver\Sae' => CORE_PATH . 'log' . DS . 'driver' . DS . 'Sae' . EXT, + 'think\cache\driver\Sae' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Sae' . EXT, + 'think\template\driver\Sae' => CORE_PATH . 'template' . DS . 'driver' . DS . 'Sae' . EXT, ], ]; From 7a9eeba5652c864c95f38e4805e8a5f7ef8d2cac Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 14:26:28 +0800 Subject: [PATCH 168/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Bstart.php=E7=8E=AF?= =?UTF-8?q?=E5=A2=83=E5=8F=98=E9=87=8F=E5=A4=84=E7=90=86=20=E6=94=B9?= =?UTF-8?q?=E8=BF=9Bhook=E7=B1=BB=E6=96=B9=E6=B3=95=E6=89=A7=E8=A1=8C?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Hook.php | 18 ++++++++++-------- library/think/Response.php | 2 +- start.php | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/library/think/Hook.php b/library/think/Hook.php index b2cb0471..82834542 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -90,10 +90,11 @@ class Hook * 监听标签的行为 * @param string $tag 标签名称 * @param mixed $params 传入参数 + * @param mixed $extra 额外参数 * @return void */ - public static function listen($tag, &$params = null) - { + public static function listen($tag, &$params = null,$extra=null) { + $result = true; if (isset(self::$tags[$tag])) { foreach (self::$tags[$tag] as $name) { @@ -101,7 +102,7 @@ class Hook Debug::remark('behavior_start', 'time'); } - $result = self::exec($name, $tag, $params); + $result = self::exec($name, $tag, $params,$extra); if (APP_DEBUG) { Debug::remark('behavior_end', 'time'); @@ -118,7 +119,7 @@ class Hook } } } - return; + return $result; } /** @@ -126,17 +127,18 @@ class Hook * @param mixed $class 要执行的行为 * @param string $tag 方法名(标签名) * @param Mixed $params 传人的参数 + * @param mixed $extra 额外参数 * @return mixed */ - public static function exec($class, $tag = '', &$params = null) + public static function exec($class, $tag = '', &$params = null,$extra=null) { if ($class instanceof \Closure) { - $result = call_user_func_array($class, [ & $params]); + $result = call_user_func_array($class, [ & $params,$extra]); } elseif (is_object($class)) { - $result = call_user_func_array([$class, $tag], [ & $params]); + $result = call_user_func_array([$class, $tag], [ & $params,$extra]); } else { $obj = new $class(); - $result = ($tag && is_callable([$obj, $tag])) ? $obj->$tag($params) : $obj->run($params); + $result = ($tag && is_callable([$obj, $tag])) ? $obj->$tag($params,$extra) : $obj->run($params,$extra); } return $result; } diff --git a/library/think/Response.php b/library/think/Response.php index 13a5dc76..eb70ad8f 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -101,7 +101,7 @@ class Response $data = $this->output($data); // 监听response_data - Hook::listen('response_data', $data); + Hook::listen('response_data', $data, $this); // 发送头部信息 if (!headers_sent() && !empty($this->header)) { diff --git a/start.php b/start.php index b8fa8b9b..b5a209ee 100644 --- a/start.php +++ b/start.php @@ -21,7 +21,7 @@ if (is_file(ROOT_PATH . 'env' . EXT)) { $env = include ROOT_PATH . 'env' . EXT; foreach ($env as $key => $val) { $name = ENV_PREFIX . $key; - putenv("$name=$val"); + putenv("$name=".var_export($var,true)); } } // 自动识别调试模式 From 458cd825075a1fe18d823e48527be115ce544088 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 16:03:15 +0800 Subject: [PATCH 169/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E9=A1=B5=E9=9D=A2tra?= =?UTF-8?q?ce=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 9 +++++++-- library/think/log/driver/Trace.php | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/library/think/Response.php b/library/think/Response.php index eb70ad8f..d531979f 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -53,8 +53,11 @@ class Response if (isset($this->contentTypes[$this->type])) { $this->contentType($this->contentTypes[$this->type]); } - - $this->options = array_merge($this->options, $options); + if(!empty($options)){ + $this->options = array_merge($this->options, $options); + } + // 方便获取某个类型的实例 + self::$instance[$this->type] = $this; } /** @@ -97,6 +100,8 @@ class Response $data = call_user_func_array($this->transform, [$data]); } + define('RESPONSE_TYPE',$this->type); + // 处理输出数据 $data = $this->output($data); diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index d0501b2f..6b160042 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -41,7 +41,7 @@ class Trace */ public function save(array $log = []) { - if (IS_AJAX || IS_CLI || IS_API || 'html' != Config::get('default_return_type')) { + if (IS_AJAX || IS_CLI || IS_API || 'html' != RESPONSE_TYPE) { // ajax cli api方式下不输出 return false; } From 62b01bf566afb54024f875052afe8c6f7be3a8df Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 16:10:47 +0800 Subject: [PATCH 170/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=20=E6=94=B9=E8=BF=9Bstart?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 2 +- start.php | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/library/think/Response.php b/library/think/Response.php index d531979f..5b86e940 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -100,7 +100,7 @@ class Response $data = call_user_func_array($this->transform, [$data]); } - define('RESPONSE_TYPE',$this->type); + defined('RESPONSE_TYPE') or define('RESPONSE_TYPE',$this->type); // 处理输出数据 $data = $this->output($data); diff --git a/start.php b/start.php index b5a209ee..970fc937 100644 --- a/start.php +++ b/start.php @@ -21,7 +21,10 @@ if (is_file(ROOT_PATH . 'env' . EXT)) { $env = include ROOT_PATH . 'env' . EXT; foreach ($env as $key => $val) { $name = ENV_PREFIX . $key; - putenv("$name=".var_export($var,true)); + if(is_bool($val)){ + $val = $val ? 1 : 0; + } + putenv("$name=$var"); } } // 自动识别调试模式 From e890d43d55d3fe6b33cdc71a7d85e2af046c0ebc Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 17:57:50 +0800 Subject: [PATCH 171/670] =?UTF-8?q?=E5=85=B3=E8=81=94=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E8=BF=9C=E7=A8=8B=E4=B8=80=E5=AF=B9=E5=A4=9A?= =?UTF-8?q?=E5=85=B3=E8=81=94=20Query=E7=B1=BBview=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E7=9A=84field=E5=8F=82=E6=95=B0=E6=94=AF=E6=8C=81=E4=BC=A0?= =?UTF-8?q?=E5=85=A5true?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 22 ++++++++++++ library/think/db/Query.php | 24 +++++++------ library/think/model/Relation.php | 62 ++++++++++++++++++++++++++++---- 3 files changed, 92 insertions(+), 16 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 80eb92ea..fcb94814 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -885,6 +885,28 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $this->relation()->hasMany($model, $foreignKey, $localKey, $alias); } + /** + * HAS MANY 远程关联定义 + * @access public + * @param string $model 模型名 + * @param string $through 中间模型名 + * @param string $foreignKey 关联外键 + * @param string $throughKey 关联外键 + * @param string $localKey 关联主键 + * @param array $alias 别名定义 + * @return \think\db\Query|string + */ + public function hasManyThrough($model,$through,$foreignKey='',$throughKey='',$localKey='',$alias=[]){ + // 记录当前关联信息 + $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); + } + /** * BELONGS TO MANY 关联定义 * @access public diff --git a/library/think/db/Query.php b/library/think/db/Query.php index a5e042b8..99e2387b 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -667,17 +667,21 @@ class Query $alias = $join; } $table = !empty($table) ? $table : $this->getTable($join); - if (is_string($field)) { - $field = explode(',', $field); - } - foreach ($field as $key => $val) { - if (is_numeric($key)) { - $fields[] = $alias . '.' . $val; - $this->options['map'][$val] = $alias . '.' . $val; - } else { - $fields[] = $alias . '.' . $key . ' AS ' . $val; - $this->options['map'][$val] = $alias . '.' . $key; + 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; + $this->options['map'][$val] = $alias . '.' . $val; + } else { + $fields[] = $alias . '.' . $key . ' AS ' . $val; + $this->options['map'][$val] = $alias . '.' . $key; + } + } } $this->field($fields); if ($on) { diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index c5965743..52d2d556 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -21,9 +21,11 @@ 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 当前关联的模型类 */ @@ -32,9 +34,11 @@ class Relation protected $middle; // 当前关联类型 protected $type; - // 关联外键 + // 关联表外键 protected $foreignKey; - // 关联键 + // 中间关联表外键 + protected $throughKey; + // 关联表主键 protected $localKey; // 数据表别名 protected $alias; @@ -85,7 +89,10 @@ class Relation $result = $relation->where($localKey, $this->parent->$foreignKey)->find(); break; case self::HAS_MANY: - $result = $relation->where($foreignKey, $this->parent->$localKey)->select(); + $result = $relation->select(); + break; + case self::HAS_MANY_THROUGH: + $result = $relation->select(); break; case self::BELONGS_TO_MANY: // 关联查询 @@ -451,6 +458,32 @@ class Relation return $this; } + /** + * 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) + { + // 记录当前关联信息 + $this->type = self::HAS_MANY_THROUGH; + $this->model = $model; + $this->middle = $through; + $this->foreignKey = $foreignKey; + $this->throughKey = $throughKey; + $this->localKey = $localKey; + $this->alias = $alias; + + // 返回关联的模型对象 + return $this; + } + /** * BELONGS TO MANY 关联定义 * @access public @@ -621,9 +654,26 @@ class Relation if ($this->model) { $model = new $this->model; $db = $model->db(); - if (self::HAS_MANY == $this->type && isset($this->parent->{$this->localKey})) { - // 关联查询带入关联条件 - $db->where($this->foreignKey, $this->parent->{$this->localKey}); + switch($this->type){ + case self::HAS_MANY: + if (isset($this->parent->{$this->localKey})) { + // 关联查询带入关联条件 + $db->where($this->foreignKey, $this->parent->{$this->localKey}); + } + break; + case self::HAS_MANY_THROUGH: + $through = $this->middle; + $model = $this->model; + $table = $model::getTable(); + $throughTable = $through::getTable(); + $pk = (new $this->model)->getPk(); + $throughKey = $this->throughKey; + $modelTable = $this->parent->getTable(); + $result = $db->field($table.'.*') + ->join($throughTable,$throughTable.'.'.$pk.'='.$table.'.'.$throughKey) + ->join($modelTable,$modelTable.'.'.$this->localKey.'='.$throughTable.'.'.$this->foreignKey) + ->where($throughTable.'.'.$this->foreignKey, $this->parent->{$this->localKey}); + break; } return call_user_func_array([$db, $method], $args); } else { From 15de3e328a94d8c7f1c27073d7db4531e4862951 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 18:17:45 +0800 Subject: [PATCH 172/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E8=BF=9C=E7=A8=8B?= =?UTF-8?q?=E4=B8=80=E5=AF=B9=E5=A4=9A=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 41 ++++++++++++++++++++------------ library/think/model/Relation.php | 6 ++--- 2 files changed, 29 insertions(+), 18 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index fcb94814..5c98a858 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -740,10 +740,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $model = new static(); $info = $model->$relation()->getRelationInfo(); $table = $info['model']::getTable(); - return $model->db()->alias('a') - ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey']) - ->group('b.' . $info['foreignKey']) - ->having('count(' . $id . ')' . $operator . $count); + switch($info['type']){ + case Relation::HAS_MANY: + return $model->db()->alias('a') + ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey']) + ->group('b.' . $info['foreignKey']) + ->having('count(' . $id . ')' . $operator . $count); + case Relation::HAS_MANY_THROUGH: + // TODO + } + } /** @@ -757,19 +763,24 @@ abstract class Model implements \JsonSerializable, \ArrayAccess { $model = new static(); $info = $model->$relation()->getRelationInfo(); - $table = $info['model']::getTable(); - if (is_array($where)) { - foreach ($where as $key => $val) { - if (false === strpos($key, '.')) { - $where['b.' . $key] = $val; - unset($where[$key]); + switch($info['type']){ + 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']) + ->where($where); + case Relation::HAS_MANY_THROUGH: + // TODO } - return $model->db()->alias('a') - ->field('a.*') - ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey']) - ->where($where); } /** diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index 52d2d556..cc9c1cf6 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -664,13 +664,13 @@ class Relation case self::HAS_MANY_THROUGH: $through = $this->middle; $model = $this->model; - $table = $model::getTable(); + $alias = Loader::parseName(basename(str_replace('\\', '/', $model))); $throughTable = $through::getTable(); $pk = (new $this->model)->getPk(); $throughKey = $this->throughKey; $modelTable = $this->parent->getTable(); - $result = $db->field($table.'.*') - ->join($throughTable,$throughTable.'.'.$pk.'='.$table.'.'.$throughKey) + $result = $db->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; From 190e870dce0b71b940cc337464c4036c28d6fc5b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 18:18:52 +0800 Subject: [PATCH 173/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E4=B8=80=E5=A4=84?= =?UTF-8?q?=E5=8F=AF=E8=83=BD=E7=9A=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/Trace.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index 6b160042..bd9c6ea4 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -41,7 +41,7 @@ class Trace */ public function save(array $log = []) { - if (IS_AJAX || IS_CLI || IS_API || 'html' != RESPONSE_TYPE) { + if (IS_AJAX || IS_CLI || IS_API || (defined('RESPONSE_TYPE') && 'html' != RESPONSE_TYPE)) { // ajax cli api方式下不输出 return false; } From afa64cfd21a77d232222fb6a9c57ee790f1ab4ca Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 19:20:12 +0800 Subject: [PATCH 174/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E5=AD=98=E5=82=A8?= =?UTF-8?q?=E8=BF=87=E7=A8=8B=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index e613e882..45f90eab 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -356,7 +356,8 @@ abstract class Connection $result = $this->PDOStatement->execute(); // 调试结束 $this->debug(false); - return $this->getResult($class); + $procedure = 0 === strpos(strtolower(substr(trim($sql),0,4)),'call'); + return $this->getResult($class,$procedure); } catch (\PDOException $e) { throw new PDOException($e, $this->config, $this->queryStr); } @@ -472,14 +473,18 @@ abstract class Connection * 获得数据集 * @access protected * @param bool|string $class true 返回PDOStatement 字符串用于指定返回的类名 + * @param bool $procedure 是否存储过程 * @return mixed */ - protected function getResult($class = '') + protected function getResult($class = '',$procedure=false) { if (true === $class) { // 返回PDOStatement对象处理 return $this->PDOStatement; } + if($procedure){ + return $this->procedure($class); + } $result = $this->PDOStatement->fetchAll($this->fetchType); $this->numRows = count($result); @@ -501,6 +506,23 @@ abstract class Connection return $result; } + /** + * 获得存储过程数据集 + * @access protected + * @param bool|string $class true 返回PDOStatement 字符串用于指定返回的类名 + * @return array + */ + protected function procedure($class){ + $item = []; + do { + $result = $this->getResult($class); + if($result){ + $item[] = $result; + } + } while ($this->PDOStatement->nextRowset()); + return $result; + } + /** * 执行数据库事务 * @access public From 0bffec6aaa612a3e59d7b4e03f7a44c9aa433c3b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 21:55:57 +0800 Subject: [PATCH 175/670] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 17 ++++++------- library/think/db/Connection.php | 13 +++++----- library/think/model/Relation.php | 41 ++++++++++++++++---------------- 3 files changed, 36 insertions(+), 35 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 5c98a858..787f19ff 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -740,14 +740,14 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $model = new static(); $info = $model->$relation()->getRelationInfo(); $table = $info['model']::getTable(); - switch($info['type']){ + switch ($info['type']) { case Relation::HAS_MANY: return $model->db()->alias('a') ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey']) ->group('b.' . $info['foreignKey']) - ->having('count(' . $id . ')' . $operator . $count); + ->having('count(' . $id . ')' . $operator . $count); case Relation::HAS_MANY_THROUGH: - // TODO + // TODO } } @@ -763,7 +763,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess { $model = new static(); $info = $model->$relation()->getRelationInfo(); - switch($info['type']){ + switch ($info['type']) { case Relation::HAS_MANY: $table = $info['model']::getTable(); if (is_array($where)) { @@ -777,9 +777,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $model->db()->alias('a') ->field('a.*') ->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey']) - ->where($where); + ->where($where); case Relation::HAS_MANY_THROUGH: - // TODO + // TODO } } @@ -907,7 +907,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param array $alias 别名定义 * @return \think\db\Query|string */ - public function hasManyThrough($model,$through,$foreignKey='',$throughKey='',$localKey='',$alias=[]){ + public function hasManyThrough($model, $through, $foreignKey = '', $throughKey = '', $localKey = '', $alias = []) + { // 记录当前关联信息 $model = $this->parseModel($model); $through = $this->parseModel($through); @@ -915,7 +916,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $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->relation()->hasManyThrough($model, $through, $foreignKey, $throughKey, $localKey, $alias); } /** diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 45f90eab..dba76bdc 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -356,8 +356,8 @@ abstract class Connection $result = $this->PDOStatement->execute(); // 调试结束 $this->debug(false); - $procedure = 0 === strpos(strtolower(substr(trim($sql),0,4)),'call'); - return $this->getResult($class,$procedure); + $procedure = 0 === strpos(strtolower(substr(trim($sql), 0, 4)), 'call'); + return $this->getResult($class, $procedure); } catch (\PDOException $e) { throw new PDOException($e, $this->config, $this->queryStr); } @@ -476,13 +476,13 @@ abstract class Connection * @param bool $procedure 是否存储过程 * @return mixed */ - protected function getResult($class = '',$procedure=false) + protected function getResult($class = '', $procedure = false) { if (true === $class) { // 返回PDOStatement对象处理 return $this->PDOStatement; } - if($procedure){ + if ($procedure) { return $this->procedure($class); } $result = $this->PDOStatement->fetchAll($this->fetchType); @@ -512,11 +512,12 @@ abstract class Connection * @param bool|string $class true 返回PDOStatement 字符串用于指定返回的类名 * @return array */ - protected function procedure($class){ + protected function procedure($class) + { $item = []; do { $result = $this->getResult($class); - if($result){ + if ($result) { $item[] = $result; } } while ($this->PDOStatement->nextRowset()); diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index cc9c1cf6..fa97e260 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -19,12 +19,11 @@ use think\model\Pivot; class Relation { - const HAS_ONE = 1; - const HAS_MANY = 2; - const HAS_MANY_THROUGH= 5; - const BELONGS_TO = 3; - const BELONGS_TO_MANY = 4; - + const HAS_ONE = 1; + const HAS_MANY = 2; + const HAS_MANY_THROUGH = 5; + const BELONGS_TO = 3; + const BELONGS_TO_MANY = 4; // 父模型对象 protected $parent; @@ -37,7 +36,7 @@ class Relation // 关联表外键 protected $foreignKey; // 中间关联表外键 - protected $throughKey; + protected $throughKey; // 关联表主键 protected $localKey; // 数据表别名 @@ -469,7 +468,7 @@ class Relation * @param array $alias 别名定义 * @return $this */ - public function hasManyThrough($model, $through,$foreignKey,$throughKey, $localKey, $alias) + public function hasManyThrough($model, $through, $foreignKey, $throughKey, $localKey, $alias) { // 记录当前关联信息 $this->type = self::HAS_MANY_THROUGH; @@ -654,25 +653,25 @@ class Relation if ($this->model) { $model = new $this->model; $db = $model->db(); - switch($this->type){ + switch ($this->type) { case self::HAS_MANY: if (isset($this->parent->{$this->localKey})) { // 关联查询带入关联条件 $db->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(); - $result = $db->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}); + $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(); + $result = $db->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; } return call_user_func_array([$db, $method], $args); From 4b743713a73c99135a495ee23e758d91d036a516 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 25 May 2016 23:00:31 +0800 Subject: [PATCH 176/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E5=B8=B8=E9=87=8F=20CONF=5FPATH=20=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E8=AE=BE=E7=BD=AE=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E7=9B=AE=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 1 + library/think/App.php | 14 +++++++------- library/think/Build.php | 2 +- mode/console/App.php | 20 ++++++++++---------- 4 files changed, 19 insertions(+), 18 deletions(-) diff --git a/base.php b/base.php index df8eba84..272fd268 100644 --- a/base.php +++ b/base.php @@ -32,6 +32,7 @@ defined('CACHE_PATH') or define('CACHE_PATH', RUNTIME_PATH . 'cache' . DS); defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH . 'temp' . DS); defined('VENDOR_PATH') or define('VENDOR_PATH', ROOT_PATH . 'vendor' . DS); defined('EXT') or define('EXT', '.php'); +defined('CONF_PATH') or define('CONF_PATH', APP_PATH); // 配置文件目录 defined('CONF_EXT') or define('CONF_EXT', EXT); // 配置文件后缀 defined('MODEL_LAYER') or define('MODEL_LAYER', 'model'); defined('VIEW_LAYER') or define('VIEW_LAYER', 'view'); diff --git a/library/think/App.php b/library/think/App.php index f58350f6..7bb61231 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -302,29 +302,29 @@ class App } else { $path = APP_PATH . $module; // 加载模块配置 - $config = Config::load(APP_PATH . $module . 'config' . CONF_EXT); + $config = Config::load(CONF_PATH . $module . 'config' . CONF_EXT); // 加载应用状态配置 if ($config['app_status']) { - $config = Config::load(APP_PATH . $module . $config['app_status'] . CONF_EXT); + $config = Config::load(CONF_PATH . $module . $config['app_status'] . CONF_EXT); } // 读取扩展配置文件 if ($config['extra_config_list']) { foreach ($config['extra_config_list'] as $name => $file) { - $filename = $path . $file . CONF_EXT; + $filename = CONF_PATH . $module . $file . CONF_EXT; Config::load($filename, is_string($name) ? $name : pathinfo($filename, PATHINFO_FILENAME)); } } // 加载别名文件 - if (is_file($path . 'alias' . EXT)) { - Loader::addMap(include $path . 'alias' . EXT); + if (is_file(CONF_PATH . $module . 'alias' . EXT)) { + Loader::addMap(include CONF_PATH . $module . 'alias' . EXT); } // 加载行为扩展文件 - if (is_file($path . 'tags' . EXT)) { - Hook::import(include $path . 'tags' . EXT); + if (is_file(CONF_PATH . $module . 'tags' . EXT)) { + Hook::import(include CONF_PATH . $module . 'tags' . EXT); } // 加载公共文件 diff --git a/library/think/Build.php b/library/think/Build.php index 5cc2147e..ada56595 100644 --- a/library/think/Build.php +++ b/library/think/Build.php @@ -186,7 +186,7 @@ class Build */ protected static function buildCommon($module) { - $filename = APP_PATH . ($module ? $module . DS : '') . 'config.php'; + $filename = CONF_PATH . ($module ? $module . DS : '') . 'config.php'; if (!is_file($filename)) { file_put_contents($filename, " $file) { - $filename = APP_PATH . $file . EXT; + $filename = CONF_PATH . $file . CONF_EXT; Config::load($filename, is_string($name) ? $name : pathinfo($filename, PATHINFO_FILENAME)); } } // 加载别名文件 - if (is_file(APP_PATH . 'alias' . EXT)) { - Loader::addMap(include APP_PATH . 'alias' . EXT); + if (is_file(CONF_PATH . 'alias' . EXT)) { + Loader::addMap(include CONF_PATH . 'alias' . EXT); } // 加载行为扩展文件 - if (is_file(APP_PATH . 'tags' . EXT)) { - Hook::import(include APP_PATH . 'tags' . EXT); + if (is_file(CONF_PATH . 'tags' . EXT)) { + Hook::import(include CONF_PATH . 'tags' . EXT); } // 加载公共文件 @@ -104,4 +104,4 @@ class App // 监听app_init Hook::listen('app_init'); } -} \ No newline at end of file +} From 4c456e3b4ef68b52eb0cd51bc74fa4e274d59bce Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 26 May 2016 10:45:31 +0800 Subject: [PATCH 177/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E4=BA=8B=E5=8A=A1?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index dba76bdc..c66515a2 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -521,7 +521,8 @@ abstract class Connection $item[] = $result; } } while ($this->PDOStatement->nextRowset()); - return $result; + $this->numRows = count($item); + return $item; } /** From ccf4c2fdd669adee35fda197c93af8af214be7c0 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 26 May 2016 11:18:09 +0800 Subject: [PATCH 178/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB?= =?UTF-8?q?=E7=9A=84import=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 372e9582..0a8d4a13 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -162,10 +162,10 @@ class Route if (is_numeric($key)) { $key = array_shift($val); } + if (empty($val)) { + continue; + } if (0 === strpos($key, '[')) { - if (empty($val)) { - continue; - } $key = substr($key, 1, -1); $result = ['routes' => $val, 'option' => [], 'pattern' => []]; } elseif (is_array($val)) { From 8ccb3f1162115d170d83727fe619c55442cf13b4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 26 May 2016 12:26:02 +0800 Subject: [PATCH 179/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BConnection=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getBindSql=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index c66515a2..b7d94dfb 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -433,7 +433,10 @@ abstract class Connection // 判断占位符 $sql = is_numeric($key) ? substr_replace($sql, $val, strpos($sql, '?'), 1) : - str_replace([':' . $key . ')', ':' . $key . ' '], [$val . ')', $val . ' '], $sql . ' '); + str_replace( + [':' . $key . ')', ':' . $key . ',', ':' . $key . ' '], + [$val . ')', $val . ',', $val . ' '], + $sql . ' '); } } return $sql; From d6c74d30813da320bb1f18e72d9e9eb8f8305f83 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 26 May 2016 13:06:11 +0800 Subject: [PATCH 180/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E9=9D=99=E6=80=81=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 100 +++++++++++++++++++++++--------------- 1 file changed, 62 insertions(+), 38 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index c205f970..f863619f 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -195,7 +195,7 @@ class Request * @param string $url URL地址 * @return string */ - public function domain($domain = '') + protected function domain($domain = '') { if (!empty($domain)) { $this->domain = $domain; @@ -213,7 +213,7 @@ class Request * @param bool $domain 是否需要域名 * @return string */ - public function url($url = '') + protected function url($url = '') { if (is_string($url) && !empty($url)) { $this->url = $url; @@ -234,7 +234,7 @@ class Request * @param string $url URL地址 * @return string */ - public function baseUrl($url = '') + protected function baseUrl($url = '') { if (is_string($url) && !empty($url)) { $this->baseUrl = $url; @@ -252,7 +252,7 @@ class Request * @param string $file 当前执行的文件 * @return string */ - public function baseFile($file = '') + protected function baseFile($file = '') { if (is_string($file) && !empty($file)) { $this->baseFile = $file; @@ -284,7 +284,7 @@ class Request * @param string $url URL地址 * @return string */ - public function root($url = '') + protected function root($url = '') { if (is_string($url) && !empty($url)) { $this->root = $url; @@ -304,7 +304,7 @@ class Request * @access public * @return string */ - public function pathinfo() + protected function pathinfo() { if (is_null($this->pathinfo)) { if (isset($_GET[Config::get('var_pathinfo')])) { @@ -336,7 +336,7 @@ class Request * @access public * @return string */ - public function path() + protected function path() { if (is_null($this->path)) { // 去除正常的URL后缀 @@ -350,7 +350,7 @@ class Request * @access public * @return string */ - public function ext() + protected function ext() { return pathinfo($this->pathinfo(), PATHINFO_EXTENSION); } @@ -361,7 +361,7 @@ class Request * @param bool $float 是否使用浮点类型 * @return integer|float */ - public function time($float = false) + protected function time($float = false) { return $float ? $_SERVER['REQUEST_TIME_FLOAT'] : $_SERVER['REQUEST_TIME']; } @@ -371,7 +371,7 @@ class Request * @access public * @return false|string */ - public function type() + protected function type() { $accept = isset($this->server['HTTP_ACCEPT']) ? $this->server['HTTP_ACCEPT'] : $_SERVER['HTTP_ACCEPT']; if (empty($accept)) { @@ -396,7 +396,7 @@ class Request * @param string $val 资源类型 * @return void */ - public function mimeType($type, $val = '') + protected function mimeType($type, $val = '') { if (is_array($type)) { $this->mimeType = array_merge($this->mimeType, $type); @@ -411,7 +411,7 @@ class Request * @param string $method 请求类型 * @return string */ - public function method($method = '') + protected function method($method = '') { if ($method) { $this->method = $method; @@ -427,7 +427,7 @@ class Request * @access public * @return bool */ - public function isGet() + protected function isGet() { return $this->method() == 'GET'; } @@ -437,7 +437,7 @@ class Request * @access public * @return bool */ - public function isPost() + protected function isPost() { return $this->method() == 'POST'; } @@ -447,7 +447,7 @@ class Request * @access public * @return bool */ - public function isPut() + protected function isPut() { return $this->method() == 'PUT'; } @@ -457,7 +457,7 @@ class Request * @access public * @return bool */ - public function isDelete() + protected function isDelete() { return $this->method() == 'DELETE'; } @@ -467,7 +467,7 @@ class Request * @access public * @return bool */ - public function isCli() + protected function isCli() { return PHP_SAPI == 'cli'; } @@ -477,7 +477,7 @@ class Request * @access public * @return bool */ - public function isCgi() + protected function isCgi() { return strpos(PHP_SAPI, 'cgi') === 0; } @@ -489,7 +489,7 @@ class Request * @param mixed $default 默认值 * @return mixed */ - public function param($name = '', $default = null) + protected function param($name = '', $default = null) { if (empty($this->param)) { $method = $this->method(); @@ -524,7 +524,7 @@ class Request * @param bool $checkEmpty 是否检测空值 * @return mixed */ - public function has($name, $checkEmpty = false) + protected function has($name, $checkEmpty = false) { if (empty($this->param)) { $param = $this->param(); @@ -544,7 +544,7 @@ class Request * @param string|array $name 变量名 * @return mixed */ - public function only($name) + protected function only($name) { $param = $this->param(); if (is_string($name)) { @@ -565,7 +565,7 @@ class Request * @param string|array $name 变量名 * @return mixed */ - public function except($name) + protected function except($name) { $param = $this->param(); if (is_string($name)) { @@ -585,7 +585,7 @@ class Request * @param string $name 变量名 * @return mixed */ - public function session($name = '') + protected function session($name = '') { if (PHP_SESSION_DISABLED == session_status()) { session_start(); @@ -599,7 +599,7 @@ class Request * @param string $name 变量名 * @return mixed */ - public function cookie($name = '') + protected function cookie($name = '') { return Input::data($this->cookie ?: $_COOKIE, $name); } @@ -610,7 +610,7 @@ class Request * @param string $name 变量名 * @return mixed */ - public function server($name = '') + protected function server($name = '') { return Input::data($this->server ?: $_SERVER, $name); } @@ -621,7 +621,7 @@ class Request * @param string $name 名称 * @return null|array|\think\File */ - public function file($name = '') + protected function file($name = '') { return Input::file($name, $this->file ?: $_FILES); } @@ -631,7 +631,7 @@ class Request * @access public * @return bool */ - public function isSsl() + protected function isSsl() { $server = array_merge($_SERVER, $this->server); if (isset($server['HTTPS']) && ('1' == $server['HTTPS'] || 'on' == strtolower($server['HTTPS']))) { @@ -645,22 +645,32 @@ class Request } /** - * 当前是否ajax请求 + * 当前是否Ajax请求 * @access public * @return bool */ - public function isAjax() + protected function isAjax() { return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false; } + /** + * 当前是否Pjax请求 + * @access public + * @return bool + */ + protected function isPjax() + { + return (isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX']) ? true : false; + } + /** * 获取客户端IP地址 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字 * @param boolean $adv 是否进行高级模式获取(有可能被伪装) * @return mixed */ - public function ip($type = 0, $adv = false) + protected function ip($type = 0, $adv = false) { $type = $type ? 1 : 0; static $ip = null; @@ -696,7 +706,7 @@ class Request * @access public * @return string */ - public function scheme() + protected function scheme() { return $this->isSsl() ? 'https' : 'http'; } @@ -706,7 +716,7 @@ class Request * @access public * @return string */ - public function query() + protected function query() { return $this->server('QUERY_STRING'); } @@ -716,7 +726,7 @@ class Request * @access public * @return string */ - public function host() + protected function host() { return $this->server('HTTP_HOST'); } @@ -726,7 +736,7 @@ class Request * @access public * @return integer */ - public function port() + protected function port() { return $this->server('SERVER_PORT'); } @@ -736,7 +746,7 @@ class Request * @access public * @return integer */ - public function protocol() + protected function protocol() { return $this->server('SERVER_PROTOCOL'); } @@ -746,7 +756,7 @@ class Request * @access public * @return integer */ - public function remotePort() + protected function remotePort() { return $this->server('REMOTE_PORT'); } @@ -757,7 +767,7 @@ class Request * @param array $route 路由名称 * @return array */ - public function route($route = []) + protected function route($route = []) { if (!empty($route)) { $this->route = $route; @@ -772,7 +782,7 @@ class Request * @param array $dispatch 调度信息 * @return array */ - public function dispatch($dispatch = []) + protected function dispatch($dispatch = []) { if (!empty($dispatch)) { $this->dispatch = $dispatch; @@ -780,4 +790,18 @@ class Request return $this->dispatch; } + public static function __callStatic($method, $params) + { + if (is_null(self::$instance)) { + self::instance(); + } + return call_user_func_array([self::$instance, $method], $params); + } + + public function __call($method, $params) + { + if (method_exists($this, $method)) { + return call_user_func_array([$this, $method], $params); + } + } } From 2e44f2a154e5e10ea41a59ec3b956c82800372cc Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 26 May 2016 14:13:21 +0800 Subject: [PATCH 181/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E7=A6=81=E7=94=A8?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E7=9A=84=E5=88=A4=E6=96=AD=20=E7=BB=91?= =?UTF-8?q?=E5=AE=9A=E7=9A=84=E6=A8=A1=E5=9D=97=E4=B8=8D=E5=8F=97=E9=99=90?= =?UTF-8?q?=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/library/think/App.php b/library/think/App.php index 7bb61231..a6205ff8 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -227,9 +227,20 @@ class App $module = strtolower($result[0] ?: $config['default_module']); // 获取模块名称 define('MODULE_NAME', strip_tags($module)); + $bind = Route::bind('module'); + $available = false; + if ($bind) { + // 绑定模块 + list($bindModule) = explode('/', $bind); + if (MODULE_NAME == $bindModule) { + $available = true; + } + } elseif (!in_array(MODULE_NAME, $config['deny_module_list']) && is_dir(APP_PATH . MODULE_NAME)) { + $available = true; + } // 模块初始化 - if (MODULE_NAME && !in_array(MODULE_NAME, $config['deny_module_list']) && is_dir(APP_PATH . MODULE_NAME)) { + if (MODULE_NAME && $available) { define('MODULE_PATH', APP_PATH . MODULE_NAME . DS); define('VIEW_PATH', MODULE_PATH . VIEW_LAYER . DS); // 初始化模块 From 468222c4b81215aaa4236a1f8b33e551aa1a74aa Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 26 May 2016 22:08:50 +0800 Subject: [PATCH 182/670] =?UTF-8?q?Route=E5=8F=82=E6=95=B0=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0merge=5Fextra=5Fvars=E5=8F=82=E6=95=B0=20=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E6=98=AF=E5=90=A6=E5=90=88=E5=B9=B6=E6=9C=80=E5=90=8E?= =?UTF-8?q?=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 0a8d4a13..8e2370e9 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -783,17 +783,20 @@ class Route } $len1 = substr_count($url, '/'); $len2 = substr_count($rule, '/'); + // 多余参数是否合并 + $merge = !empty($option['merge_extra_vars']) ? true : false; + if ($len1 >= $len2 || strpos($rule, '[')) { if ('$' == substr($rule, -1, 1)) { // 完整匹配 - if ($len1 != $len2 && false === strpos($rule, '[')) { + if (!$merge && $len1 != $len2 && false === strpos($rule, '[')) { return false; } else { $rule = substr($rule, 0, -1); } } $pattern = array_merge(self::$pattern, $pattern); - if (false !== $match = self::match($url, $rule, $pattern)) { + if (false !== $match = self::match($url, $rule, $pattern, $merge)) { // 匹配到路由规则 // 检测是否定义路由 if (!empty($option['after_behavior'])) { @@ -813,7 +816,7 @@ class Route // 执行闭包 return ['type' => 'function', 'function' => $route, 'params' => $match]; } - return self::parseRule($rule, $route, $url, $match); + return self::parseRule($rule, $route, $url, $match, $merge); } } return false; @@ -927,12 +930,14 @@ class Route * @param string $url URL地址 * @param string $rule 路由规则 * @param array $pattern 变量规则 + * @param bool $merge 合并额外变量 * @return array|false */ - private static function match($url, $rule, $pattern) + private static function match($url, $rule, $pattern, $merge) { - $m1 = explode('/', $url); - $m2 = explode('/', $rule); + $m2 = explode('/', $rule); + $m1 = explode('/', $url, $merge ? count($m2) : null); + $var = []; foreach ($m2 as $key => $val) { // val中定义了多个变量 @@ -985,16 +990,18 @@ class Route * @param string $route 路由地址 * @param string $pathinfo URL地址 * @param array $matches 匹配的变量 + * @param bool $merge 合并额外变量 * @return array */ - private static function parseRule($rule, $route, $pathinfo, $matches) + private static function parseRule($rule, $route, $pathinfo, $matches, $merge) { - // 获取URL地址中的参数 - $paths = explode('/', $pathinfo); - // 获取路由地址规则 - $url = is_array($route) ? $route[0] : $route; // 解析路由规则 $rule = explode('/', $rule); + // 获取URL地址中的参数 + $paths = explode('/', $pathinfo, $merge ? count($rule) : null); + // 获取路由地址规则 + $url = is_array($route) ? $route[0] : $route; + foreach ($rule as $item) { $fun = ''; if (0 === strpos($item, '[:')) { From fa8aac7c13ec3fb1e0f71a37eced5a1388d8e432 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 26 May 2016 22:38:52 +0800 Subject: [PATCH 183/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 8e2370e9..5d3badce 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -936,7 +936,7 @@ class Route private static function match($url, $rule, $pattern, $merge) { $m2 = explode('/', $rule); - $m1 = explode('/', $url, $merge ? count($m2) : null); + $m1 = $merge ? explode('/', $url, count($m2)) : explode('/', $url); $var = []; foreach ($m2 as $key => $val) { @@ -993,12 +993,12 @@ class Route * @param bool $merge 合并额外变量 * @return array */ - private static function parseRule($rule, $route, $pathinfo, $matches, $merge) + private static function parseRule($rule, $route, $pathinfo, $matches, $merge = false) { // 解析路由规则 $rule = explode('/', $rule); // 获取URL地址中的参数 - $paths = explode('/', $pathinfo, $merge ? count($rule) : null); + $paths = $merge ? explode('/', $pathinfo, count($rule)) : explode('/', $pathinfo); // 获取路由地址规则 $url = is_array($route) ? $route[0] : $route; From 4a4bc53cb59388438908d0e5c08ddd6cb157ca45 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 07:56:46 +0800 Subject: [PATCH 184/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E6=A0=87=E7=AD=BEurl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/template/taglib/Cx.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/template/taglib/Cx.php b/library/think/template/taglib/Cx.php index a3fe83cf..08f2cfaf 100644 --- a/library/think/template/taglib/Cx.php +++ b/library/think/template/taglib/Cx.php @@ -669,7 +669,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 ''; + return ''; } /** From b228efdc00b965e57571de4335d0fa9828534006 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 10:20:17 +0800 Subject: [PATCH 185/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 787f19ff..c5b11bad 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -121,7 +121,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 获取关联模型实例 - * + * @access protected * @return \think\model\Relation */ protected function relation() @@ -134,7 +134,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 初始化模型 - * + * @access protected * @return void */ protected function initialize() @@ -148,7 +148,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 初始化处理 - * + * @access protected * @return void */ protected static function init() From 46ce08b962467eca8150bcf4326a9c5960958680 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 11:06:19 +0800 Subject: [PATCH 186/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E5=99=A8=E6=96=B9=E6=B3=95=E7=9A=84=E5=8F=82=E6=95=B0=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E4=BD=BF=E7=94=A8Request=E5=AF=B9=E8=B1=A1?= =?UTF-8?q?=20=E8=87=AA=E5=8A=A8=E4=BC=A0=E5=85=A5=E5=BD=93=E5=89=8D?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E5=AF=B9=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 4 +++- library/think/Input.php | 2 +- library/think/Route.php | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index a6205ff8..9d545d8f 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -194,7 +194,9 @@ class App $params = $reflect->getParameters(); foreach ($params as $param) { $name = $param->getName(); - if (1 == $type && !empty($vars)) { + if ('think\Request' == $param->getClass()->name) { + $args[] = Request::instance(); + } elseif (1 == $type && !empty($vars)) { $args[] = array_shift($vars); } elseif (0 == $type && isset($vars[$name])) { $args[] = $vars[$name]; diff --git a/library/think/Input.php b/library/think/Input.php index a6445b2d..834bd5f0 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -342,7 +342,7 @@ class Input // TODO 其他安全过滤 // 过滤查询特殊字符 - if (preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i', $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 .= ' '; } } diff --git a/library/think/Route.php b/library/think/Route.php index 5d3badce..ebad2f9b 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -28,8 +28,8 @@ class Route private static $rest = [ 'index' => ['GET', '', 'index'], 'create' => ['GET', '/create', 'create'], - 'read' => ['GET', '/:id', 'read'], 'edit' => ['GET', '/:id/edit', 'edit'], + 'read' => ['GET', '/:id', 'read'], 'save' => ['POST', '', 'save'], 'update' => ['PUT', '/:id', 'update'], 'delete' => ['DELETE', '/:id', 'delete'], From 62debf4bc65aadecbbdb82e36e7126358bdbe24e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 11:30:05 +0800 Subject: [PATCH 187/670] =?UTF-8?q?Controller=E7=B1=BB=E6=9E=B6=E6=9E=84?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E5=A2=9E=E5=8A=A0request=E5=8F=82=E6=95=B0?= =?UTF-8?q?=20=E6=94=B9=E8=BF=9BApp=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 7 ++++--- library/think/Controller.php | 8 ++++++-- library/think/Loader.php | 4 ++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 9d545d8f..8aa14a43 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -163,7 +163,7 @@ class App { if (empty($vars)) { // 自动获取请求变量 - $vars = Request::instance()->param(); + $vars = Request::param(); } if (is_array($method)) { $class = is_object($method[0]) ? $method[0] : new $method[0]; @@ -193,8 +193,9 @@ class App if ($reflect->getNumberOfParameters() > 0) { $params = $reflect->getParameters(); foreach ($params as $param) { - $name = $param->getName(); - if ('think\Request' == $param->getClass()->name) { + $name = $param->getName(); + $class = $param->getClass(); + if ($class && 'think\Request' == $class->getName()) { $args[] = Request::instance(); } elseif (1 == $type && !empty($vars)) { $args[] = array_shift($vars); diff --git a/library/think/Controller.php b/library/think/Controller.php index 8dafcbbe..db0dc194 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -13,6 +13,7 @@ namespace think; \think\Loader::import('controller/Jump', TRAIT_PATH, EXT); +use think\Request; use think\View; class Controller @@ -21,6 +22,8 @@ class Controller // 视图类实例 protected $view = null; + // Request实例 + protected $request; /** * 前置操作方法列表 @@ -33,9 +36,10 @@ class Controller * 架构函数 * @access public */ - public function __construct() + public function __construct(Request $request) { - $this->view = View::instance(Config::get('template'), Config::get('view_replace_str')); + $this->view = View::instance(Config::get('template'), Config::get('view_replace_str')); + $this->request = $request; // 控制器初始化 if (method_exists($this, '_initialize')) { diff --git a/library/think/Loader.php b/library/think/Loader.php index 4509c58b..f271a6b4 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -313,11 +313,11 @@ class Loader } $class = self::parseClass($module, $layer, $name, $appendSuffix); if (class_exists($class)) { - $action = new $class; + $action = new $class(Request::instance()); $_instance[$name . $layer] = $action; return $action; } elseif ($empty && class_exists($emptyClass = self::parseClass($module, $layer, $empty, $appendSuffix))) { - return new $emptyClass; + return new $emptyClass(Request::instance()); } else { throw new Exception('class [ ' . $class . ' ] not exists', 10001); } From bced58597ab82293c699d85f742e4593cb281875 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 11:35:48 +0800 Subject: [PATCH 188/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/Controller.php b/library/think/Controller.php index db0dc194..bd6676d9 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -34,9 +34,10 @@ class Controller /** * 架构函数 + * @param \think\Request $request Request对象 * @access public */ - public function __construct(Request $request) + public function __construct(Request $request = null) { $this->view = View::instance(Config::get('template'), Config::get('view_replace_str')); $this->request = $request; From 93c3fe3df72d4e5f912aa9b7900ff9c6d40786f1 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 11:54:57 +0800 Subject: [PATCH 189/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E5=88=86=E7=BB=84=E4=B8=80=E5=A4=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/library/think/Route.php b/library/think/Route.php index ebad2f9b..8519cb46 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -218,6 +218,8 @@ class Route } } else { if ($group) { + self::$rules[$type][$group]['option'] = $option; + self::$rules[$type][$group]['pattern'] = $pattern; self::$rules[$type][$group]['routes'][$rule] = $route; } else { self::$rules[$type][$rule] = ['route' => $route, 'option' => $option, 'pattern' => $pattern]; From 1fd7d87ee4393b8964145b424014711e5c1a1ea1 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 12:08:03 +0800 Subject: [PATCH 190/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E8=B7=AF=E7=94=B1=E5=88=86=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 8519cb46..35fe02cc 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -199,7 +199,6 @@ class Route self::rule($rule, $route, $val, $option, $pattern, $group); } } else { - $rules = []; if (is_array($rule)) { foreach ($rule as $key => $val) { if (is_numeric($key)) { @@ -218,9 +217,7 @@ class Route } } else { if ($group) { - self::$rules[$type][$group]['option'] = $option; - self::$rules[$type][$group]['pattern'] = $pattern; - self::$rules[$type][$group]['routes'][$rule] = $route; + self::$rules[$type][$group]['routes'][$rule] = [$route, $option, $pattern]; } else { self::$rules[$type][$rule] = ['route' => $route, 'option' => $option, 'pattern' => $pattern]; } From e07bb1a6fd98e44606ba99dd54f0fba2d70949c3 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 12:12:06 +0800 Subject: [PATCH 191/670] =?UTF-8?q?=E7=BB=A7=E7=BB=AD=E6=94=B9=E8=BF=9BRou?= =?UTF-8?q?te=E7=B1=BB=E7=9A=84=E5=88=86=E7=BB=84=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Route.php b/library/think/Route.php index 35fe02cc..a4fd5c76 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -210,7 +210,7 @@ class Route $result = ['route' => $val, 'option' => $option, 'pattern' => $pattern]; } if ($group) { - self::$rules[$type][$group]['routes'][$key] = $result['route']; + self::$rules[$type][$group]['routes'][$key] = [$result['route'], $result['option'], $result['pattern']]; } else { self::$rules[$type][$key] = $result; } From c7bc8d634736e1f45f9f30fc382f4b64ad4c1a95 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 12:17:00 +0800 Subject: [PATCH 192/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84scope=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index c5b11bad..e468d3a8 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -702,7 +702,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 命名范围 * @access public - * @param string|Closure $name 命名范围名称 逗号分隔 + * @param string|array|Closure $name 命名范围名称 逗号分隔 * @param mixed $params 参数调用 * @return \think\Model */ @@ -715,9 +715,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } elseif ($name instanceof Query) { return $name; } else { - $names = explode(',', $name); + if (is_string($name)) { + $names = explode(',', $name); + } foreach ($names as $scope) { - $method = 'scope' . $scope; + $method = 'scope' . trim($scope); if (method_exists($model, $method)) { $model->$method($query, $params); } From 82ddda45675d1f25a40f7f1007d18b9cc794c376 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 12:18:39 +0800 Subject: [PATCH 193/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Controller=E7=B1=BBfe?= =?UTF-8?q?tch=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Controller.php b/library/think/Controller.php index bd6676d9..c7086c64 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -97,7 +97,7 @@ class Controller */ public function fetch($template = '', $vars = [], $replace = [], $config = []) { - return $this->view->fetch($template, $vars, $replace, $config = []); + return $this->view->fetch($template, $vars, $replace, $config); } /** From 849058b89b02a5e8f20d6b47556e96f0e73446df Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 17:47:13 +0800 Subject: [PATCH 194/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3start.php?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- start.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/start.php b/start.php index 970fc937..be2b2ba9 100644 --- a/start.php +++ b/start.php @@ -21,10 +21,10 @@ if (is_file(ROOT_PATH . 'env' . EXT)) { $env = include ROOT_PATH . 'env' . EXT; foreach ($env as $key => $val) { $name = ENV_PREFIX . $key; - if(is_bool($val)){ + if (is_bool($val)) { $val = $val ? 1 : 0; } - putenv("$name=$var"); + putenv("$name=$val"); } } // 自动识别调试模式 From 5b62ac29a2cdf21bd3278ae95fe269f544543b6a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 18:23:23 +0800 Subject: [PATCH 195/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E7=B1=BB=E7=9A=84=E5=9C=BA=E6=99=AF=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Validate.php | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/library/think/Validate.php b/library/think/Validate.php index e9e532cc..70745ba3 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -237,6 +237,19 @@ class Validate // 分析验证规则 $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; + } + } + } foreach ($rules as $key => $item) { // field => rule1|rule2... field=>['rule1','rule2',...] @@ -264,8 +277,13 @@ class Validate if (!empty($scene)) { if ($scene instanceof \Closure && !call_user_func_array($scene, [$key, &$data])) { continue; - } elseif (is_array($scene) && !in_array($key, $scene)) { - continue; + } elseif (is_array($scene)) { + if (!in_array($key, $array)) { + continue; + } elseif (isset($change[$key])) { + // 重载某个验证规则 + $rule = $change[$key]; + } } } From 12f06f2467f7eb8f5f34a2a6af4d000388065b5f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 27 May 2016 18:58:15 +0800 Subject: [PATCH 196/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E7=9A=84isssl=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/library/think/Request.php b/library/think/Request.php index f863619f..0abfbba9 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -640,6 +640,8 @@ class Request return true; } elseif (isset($server['SERVER_PORT']) && ('443' == $server['SERVER_PORT'])) { return true; + } elseif (isset($server['HTTP_X_FORWARDED_PROTO']) && 'https' == $server['HTTP_X_FORWARDED_PROTO']) { + return true; } return false; } From 99d29eb48fafc4fc5c5a4c4479e90158eedf12b0 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 28 May 2016 11:20:45 +0800 Subject: [PATCH 197/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/view/driver/Php.php | 15 ++++++++------- library/think/view/driver/Think.php | 17 ++++++++++------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index 3063bc02..abd980f3 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -39,7 +39,7 @@ class Php */ public function exists($template) { - if (!is_file($template)) { + if ('' == pathinfo($template, PATHINFO_EXTENSION)) { // 获取模板文件名 $template = $this->parseTemplate($template); } @@ -55,7 +55,7 @@ class Php */ public function fetch($template, $data = []) { - if (!is_file($template)) { + if ('' == pathinfo($template, PATHINFO_EXTENSION)) { // 获取模板文件名 $template = $this->parseTemplate($template); } @@ -94,17 +94,17 @@ class Php $this->config['view_path'] = VIEW_PATH; } - $depr = $this->config['view_depr']; - $template = str_replace(['/', ':'], $depr, $template); if (strpos($template, '@')) { list($module, $template) = explode('@', $template); - $path = APP_PATH . (APP_MULTI_MODULE ? $module . DS : '') . VIEW_LAYER . DS; + $path = APP_PATH . $module . DS . VIEW_LAYER . DS; } else { $path = $this->config['view_path']; } // 分析模板文件规则 - if (defined('CONTROLLER_NAME')) { + if (defined('CONTROLLER_NAME') && 0 !== strpos($template, '/')) { + $depr = $this->config['view_depr']; + $template = str_replace(['/', ':'], $depr, $template); if ('' == $template) { // 如果模板文件名为空 按照默认规则定位 $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . ACTION_NAME; @@ -112,7 +112,8 @@ class Php $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . $template; } } - return $path . $template . '.' . ltrim($this->config['view_suffix'], '.'); + return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.'); + } } diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 8eb85e26..167bd36f 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -48,7 +48,7 @@ class Think */ public function exists($template) { - if (!is_file($template)) { + if ('' == pathinfo($template, PATHINFO_EXTENSION)) { // 获取模板文件名 $template = $this->parseTemplate($template); } @@ -65,7 +65,7 @@ class Think */ public function fetch($template, $data = [], $config = []) { - if (!is_file($template)) { + if ('' == pathinfo($template, PATHINFO_EXTENSION)) { // 获取模板文件名 $template = $this->parseTemplate($template); } @@ -99,17 +99,20 @@ class Think */ private function parseTemplate($template) { - $depr = $this->config['view_depr']; - $template = str_replace(['/', ':'], $depr, $template); + // 获取视图根目录 if (strpos($template, '@')) { + // 跨模块调用 list($module, $template) = explode('@', $template); - $path = APP_PATH . (APP_MULTI_MODULE ? $module . DS : '') . VIEW_LAYER . DS; + $path = APP_PATH . $module . DS . VIEW_LAYER . DS; } else { + // 当前视图目录 $path = $this->config['view_path']; } // 分析模板文件规则 - if (defined('CONTROLLER_NAME')) { + if (defined('CONTROLLER_NAME') && 0 !== strpos($template, '/')) { + $depr = $this->config['view_depr']; + $template = str_replace(['/', ':'], $depr, $template); if ('' == $template) { // 如果模板文件名为空 按照默认规则定位 $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . ACTION_NAME; @@ -117,7 +120,7 @@ class Think $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . $template; } } - return $path . $template . '.' . ltrim($this->config['view_suffix'], '.'); + return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.'); } public function __call($method, $params) From 506b587e56d99a0260db085899dc8714b1cc6af7 Mon Sep 17 00:00:00 2001 From: chunice Date: Sat, 28 May 2016 11:46:09 +0800 Subject: [PATCH 198/670] =?UTF-8?q?Console=E5=A2=9E=E5=8A=A0make:controlle?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/console/command/Make.php | 47 ++++++++++ .../think/console/command/make/Controller.php | 87 +++++++++++++++++-- tpl/make_controller.tpl | 17 ++++ 3 files changed, 143 insertions(+), 8 deletions(-) create mode 100644 library/think/console/command/Make.php create mode 100644 tpl/make_controller.tpl diff --git a/library/think/console/command/Make.php b/library/think/console/command/Make.php new file mode 100644 index 00000000..928976c2 --- /dev/null +++ b/library/think/console/command/Make.php @@ -0,0 +1,47 @@ + +// +---------------------------------------------------------------------- + +namespace think\console\command; + +class Make extends Command +{ + // 创建目录 + protected static function buildDir($dir) + { + if (!is_dir(APP_PATH . $dir)) { + mkdir(APP_PATH . strtolower($dir), 0777, true); + } + } + + // 创建文件 + protected static function buildFile($file, $content) + { + if (is_file(APP_PATH . $file)) { + exception('file already exists'); + } + file_put_contents(APP_PATH . $file, $content); + } + + protected static function formatNameSpace($namespace) + { + $namespace = explode('\\', $namespace); + + foreach ($namespace as $key => $value) { + if ($key == count($namespace) - 1) { + $newNameSpace[1] = $value; + } else { + $newNameSpace[0][$key] = $value; + } + } + + return $newNameSpace; + } +} diff --git a/library/think/console/command/make/Controller.php b/library/think/console/command/make/Controller.php index f5014fec..911c9b1f 100644 --- a/library/think/console/command/make/Controller.php +++ b/library/think/console/command/make/Controller.php @@ -2,22 +2,93 @@ // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- -// | Copyright (c) 2006~2015 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: yunwuxin <448901948@qq.com> +// | Author: 刘志淳 // +---------------------------------------------------------------------- namespace think\console\command\make; -use think\console\command\Command; +use think\console\Input; +use think\console\input\Argument; +use think\console\input\Option; +use think\console\Output; -class Controller extends Command +class Controller extends \think\console\command\Make { - - public function __construct() + /** + * {@inheritdoc} + */ + protected function configure() { - parent::__construct("make:controller"); + $this + ->setName('make:controller') + ->setDescription('Create a new controller class') + ->addArgument('namespace', Argument::OPTIONAL, null) + ->addOption('module', 'm', Option::VALUE_OPTIONAL, 'Module Name', null) + ->addOption('extend', 'e', Option::VALUE_OPTIONAL, 'Base on Controller class', null); } -} \ No newline at end of file + + protected function execute(Input $input, Output $output) + { + $namespace = $input->getArgument('namespace'); + $module = $input->getOption('module'); + + + // 处理命名空间 + if (!empty($module)) { + $namespace = APP_NAMESPACE . "\\" . $module . "\\" . 'controller' . "\\" . $namespace; + } + + // 处理继承 + $extend = $input->getOption('extend'); + + if (empty($extend)) { + $extend = "\\think\\Controller"; + } else { + if (!preg_match("/\\\/", $extend)) { + if (!empty($module)) { + $extend = "\\" . APP_NAMESPACE . "\\" . $module . "\\" . 'controller' . "\\" . $extend; + } + } + } + + + $result = $this->build($namespace, $extend); + $output->writeln("output:" . $result); + } + + private function build($namespace, $extend) + { + $tpl = file_get_contents(THINK_PATH . 'tpl' . DS . 'make_controller.tpl'); + + // comminute namespace + $allNamespace = self::formatNameSpace($namespace); + $namespace = implode('\\', $allNamespace[0]); + $className = ucwords($allNamespace[1]); + + // 处理内容 + $content = str_replace("{%extend%}", $extend, + str_replace("{%className%}", $className, + str_replace("{%namespace%}", $namespace, $tpl) + ) + ); + + // 处理文件夹 + $path = ''; + foreach ($allNamespace[0] as $key => $value) { + if ($key >= 1) { + self::buildDir($path . $value); + $path .= $value . "\\"; + } + } + + // 处理文件 + $file = $path . $className . '.php'; + self::buildFile($file, $content); + + return APP_PATH . $file; + } +} diff --git a/tpl/make_controller.tpl b/tpl/make_controller.tpl new file mode 100644 index 00000000..4254f5e2 --- /dev/null +++ b/tpl/make_controller.tpl @@ -0,0 +1,17 @@ + +// +---------------------------------------------------------------------- + +namespace {%namespace%}; + +class {%className%} extends {%extend%} +{ + +} From 8f7ff8894aa6b7d7fc7df3830ebd21fa50331145 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 10:58:15 +0800 Subject: [PATCH 199/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BTrace=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E9=A9=B1=E5=8A=A8=E6=98=BE=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/Trace.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index bd9c6ea4..7df777e1 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -41,7 +41,7 @@ class Trace */ public function save(array $log = []) { - if (IS_AJAX || IS_CLI || IS_API || (defined('RESPONSE_TYPE') && 'html' != RESPONSE_TYPE)) { + if (IS_AJAX || IS_CLI || IS_API || (defined('RESPONSE_TYPE') && in_array(RESPONSE_TYPE, ['html', 'view']))) { // ajax cli api方式下不输出 return false; } From 00cab3494598a39e3e7bbcefb7820510382b2931 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 11:11:11 +0800 Subject: [PATCH 200/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Bcontroller=E7=B1=BB?= =?UTF-8?q?=E7=9A=84redirect=E6=96=B9=E6=B3=95=E5=92=8C=E5=8A=A9=E6=89=8B?= =?UTF-8?q?=E5=87=BD=E6=95=B0redirect?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 8 ++++++-- library/traits/controller/Jump.php | 8 ++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/helper.php b/helper.php index 0a458e5b..f7ac2303 100644 --- a/helper.php +++ b/helper.php @@ -407,11 +407,15 @@ function xml($data = [], $code = 200, $options = []) /** * 获取\think\response\Redirect对象实例 * @param mixed $url 重定向地址 支持Url::build方法的地址 + * @param array|integer $params 额外参数 * @param integer $code 状态码 - * @param array $params 额外参数 * @return \think\response\Redirect */ -function redirect($url = [], $code = 302, $params = []) +function redirect($url = [], $params = [], $code = 302) { + if (is_integer($params)) { + $code = $params; + $params = []; + } return Response::create($url, 'redirect')->code($code)->params($params); } diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index 6d2b9967..ae5aaf90 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -105,13 +105,17 @@ trait Jump * URL重定向 * @access protected * @param string $url 跳转的URL表达式 + * @param array|integer $params 其它URL参数 * @param integer $code http code - * @param array $params 其它URL参数 * @return void */ - public function redirect($url, $code = 301, $params = []) + public function redirect($url, $params = [], $code = 302) { $response = new Redirect($url); + if (is_integer($params)) { + $code = $params; + $params = []; + } $response->code($code)->params($params); throw new HttpResponseException($response); } From 83e3604314977d1a5f3d5130fa080308f98d8371 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 11:20:22 +0800 Subject: [PATCH 201/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getPk=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 13 ++++++++----- library/think/db/Query.php | 8 ++++---- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index e468d3a8..e7fe067c 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -255,15 +255,18 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } /** - * 获取当前模型对象的主键 + * 获取模型对象的主键 * @access public - * @param string $table 数据表名 + * @param string $name 模型名 * @return mixed */ - public function getPk($table = '') + public function getPk($name = '') { - if (empty($this->pk)) { - $this->pk = $this->db()->getTableInfo($table, 'pk'); + if (!empty($name)) { + $table = $this->db()->getTable($name); + return $this->db()->getPk($table); + } elseif (empty($this->pk)) { + $this->pk = $this->db()->getPk(); } return $this->pk; } diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 99e2387b..6a064c6a 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -667,9 +667,9 @@ class Query $alias = $join; } $table = !empty($table) ? $table : $this->getTable($join); - if(true === $field){ + if (true === $field) { $fields = $alias . '.*'; - }else{ + } else { if (is_string($field)) { $field = explode(',', $field); } @@ -681,7 +681,7 @@ class Query $fields[] = $alias . '.' . $key . ' AS ' . $val; $this->options['map'][$val] = $alias . '.' . $key; } - } + } } $this->field($fields); if ($on) { @@ -1196,7 +1196,7 @@ class Query } /** - * 获取当前模型对象的主键 + * 获取当前数据表的主键 * @access public * @param string $table 数据表名 * @return string|array From f4e3a3466cd93b76027175d9bdfd3b81f51c0884 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 11:27:49 +0800 Subject: [PATCH 202/670] =?UTF-8?q?Query=E7=B1=BB=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=88=86=E8=A1=A8=E8=8E=B7=E5=8F=96=E6=96=B9=E6=B3=95=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E4=B8=8D=E5=90=8C=E7=9A=84=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 58 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 6a064c6a..1c124ac0 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -39,6 +39,8 @@ class Query protected $options = []; // 参数绑定 protected $bind = []; + // 分表规则 + protected $partition = []; /** * 架构函数 @@ -256,6 +258,62 @@ class Query return $this->connection->getConfig($name); } + /** + * 得到分表的的数据表名 + * @access public + * @param array $data 操作的数据 + * @return string + */ + public function getPartitionTableName($data = []) + { + // 对数据表进行分区 + if (isset($data[$this->partition['field']])) { + $field = $data[$this->partition['field']]; + switch ($this->partition['type']) { + case 'id': + // 按照id范围分表 + $step = $this->partition['expr']; + $seq = floor($field / $step) + 1; + break; + case 'year': + // 按照年份分表 + if (!is_numeric($field)) { + $field = strtotime($field); + } + $seq = date('Y', $field) - $this->partition['expr'] + 1; + break; + case 'mod': + // 按照id的模数分表 + $seq = ($field % $this->partition['num']) + 1; + break; + case 'md5': + // 按照md5的序列分表 + $seq = (ord(substr(md5($field), 0, 1)) % $this->partition['num']) + 1; + break; + default: + if (function_exists($this->partition['type'])) { + // 支持指定函数哈希 + $fun = $this->partition['type']; + $seq = (ord(substr($fun($field), 0, 1)) % $this->partition['num']) + 1; + } else { + // 按照字段的首字母的值分表 + $seq = (ord($field{0}) % $this->partition['num']) + 1; + } + } + return $this->getTable() . '_' . $seq; + } else { + // 当设置的分表字段不在查询条件或者数据中 + // 进行联合查询,必须设定 partition['num'] + $tableName = []; + for ($i = 0; $i < $this->partition['num']; $i++) { + $tableName[] = 'SELECT * FROM ' . $this->getTable() . '_' . ($i + 1); + } + + $tableName = '( ' . implode(" UNION ", $tableName) . ') AS ' . $this->name; + return $tableName; + } + } + /** * 获取当前的builder实例对象 * @access protected From 14de14a1ebbc49952a4ce782b27ac70987a15ce0 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 11:49:08 +0800 Subject: [PATCH 203/670] =?UTF-8?q?Query=E7=B1=BB=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=88=86=E8=A1=A8=E8=A7=84=E5=88=99=E6=96=B9=E6=B3=95partition?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 50 ++++++++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 1c124ac0..de2ea894 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -39,8 +39,6 @@ class Query protected $options = []; // 参数绑定 protected $bind = []; - // 分表规则 - protected $partition = []; /** * 架构函数 @@ -262,42 +260,44 @@ class Query * 得到分表的的数据表名 * @access public * @param array $data 操作的数据 + * @param string $field 分表依据的字段 + * @param array $rule 分表规则 * @return string */ - public function getPartitionTableName($data = []) + public function getPartitionTableName($data, $field, $rule = []) { // 对数据表进行分区 - if (isset($data[$this->partition['field']])) { - $field = $data[$this->partition['field']]; - switch ($this->partition['type']) { + if ($field && isset($data[$field])) { + $value = $data[$field]; + $type = $rule['type']; + switch ($type) { case 'id': // 按照id范围分表 - $step = $this->partition['expr']; - $seq = floor($field / $step) + 1; + $step = $rule['expr']; + $seq = floor($value / $step) + 1; break; case 'year': // 按照年份分表 - if (!is_numeric($field)) { - $field = strtotime($field); + if (!is_numeric($value)) { + $value = strtotime($value); } - $seq = date('Y', $field) - $this->partition['expr'] + 1; + $seq = date('Y', $value) - $rule['expr'] + 1; break; case 'mod': // 按照id的模数分表 - $seq = ($field % $this->partition['num']) + 1; + $seq = ($value % $rule['num']) + 1; break; case 'md5': // 按照md5的序列分表 - $seq = (ord(substr(md5($field), 0, 1)) % $this->partition['num']) + 1; + $seq = (ord(substr(md5($value), 0, 1)) % $rule['num']) + 1; break; default: - if (function_exists($this->partition['type'])) { + if (function_exists($type)) { // 支持指定函数哈希 - $fun = $this->partition['type']; - $seq = (ord(substr($fun($field), 0, 1)) % $this->partition['num']) + 1; + $seq = (ord(substr($type($value), 0, 1)) % $rule['num']) + 1; } else { // 按照字段的首字母的值分表 - $seq = (ord($field{0}) % $this->partition['num']) + 1; + $seq = (ord($value{0}) % $rule['num']) + 1; } } return $this->getTable() . '_' . $seq; @@ -305,7 +305,7 @@ class Query // 当设置的分表字段不在查询条件或者数据中 // 进行联合查询,必须设定 partition['num'] $tableName = []; - for ($i = 0; $i < $this->partition['num']; $i++) { + for ($i = 0; $i < $rule['num']; $i++) { $tableName[] = 'SELECT * FROM ' . $this->getTable() . '_' . ($i + 1); } @@ -751,6 +751,20 @@ class Query return $this; } + /** + * 设置分表规则 + * @access public + * @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; + } + /** * 指定查询条件 * @access public From c9846a51e131482b16a861ab028b3ff620893333 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 12:09:21 +0800 Subject: [PATCH 204/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRelation=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getRelation=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=9C=A8=E5=85=B3=E8=81=94=E5=AE=9A=E4=B9=89=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E4=B8=AD=E4=BD=BF=E7=94=A8where=E6=9D=A1=E4=BB=B6=E6=88=96?= =?UTF-8?q?=E8=80=85=E5=85=B6=E4=BB=96=E7=9A=84=E6=93=8D=E4=BD=9CQuery?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Relation.php | 73 +++++++++++++++----------------- 1 file changed, 35 insertions(+), 38 deletions(-) diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index fa97e260..ac88e6a0 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -78,48 +78,45 @@ class Relation $relation = $this->parent->$name(); $foreignKey = $this->foreignKey; $localKey = $this->localKey; - if ($relation instanceof Relation) { - // 判断关联类型执行查询 - 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->toArray() as $key => $val) { - if (strpos($key, '__')) { - list($name, $attr) = explode('__', $key, 2); - if ('pivot' == $name) { - $pivot[$attr] = $val; - unset($set->$key); - } + + // 判断关联类型执行查询 + 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->toArray() 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; - } else { - return $relation; + $set->pivot = new Pivot($pivot, $this->middle); + } + break; + default: + // 直接返回 + $result = $relation; } + return $result; } /** From 55f630b33e712a42b51ad3f182f23c3d8963482a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 17:09:35 +0800 Subject: [PATCH 205/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQueery=E7=B1=BB=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0whereXor=E6=96=B9=E6=B3=95=20=E5=8E=BB?= =?UTF-8?q?=E9=99=A4=20whereExist=20whereOrExist=20whereNotExist=20whereOr?= =?UTF-8?q?NotExist=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 84 ++++++++++++-------------------------- 1 file changed, 27 insertions(+), 57 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index de2ea894..78ebc07b 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -766,7 +766,7 @@ class Query } /** - * 指定查询条件 + * 指定AND查询条件 * @access public * @param mixed $field 查询字段 * @param mixed $op 查询表达式 @@ -782,7 +782,7 @@ class Query } /** - * 指定查询条件 + * 指定OR查询条件 * @access public * @param mixed $field 查询字段 * @param mixed $op 查询表达式 @@ -797,23 +797,41 @@ class Query return $this; } + /** + * 指定XOR查询条件 + * @access public + * @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; + } + /** * 分析查询表达式 * @access public + * @param string $logic 查询逻辑 * @param string|array|\Closure $field 查询字段 * @param mixed $op 查询表达式 * @param mixed $condition 查询条件 - * @param string $operator and or + * @param string $logic and or xor + * @param array $param 查询参数 * @return void */ - protected function parseWhereExp($operator, $field, $op, $condition, $param = []) + protected function parseWhereExp($logic, $field, $op, $condition, $param = []) { if ($field instanceof \Closure) { - $this->options['where'][$operator][] = $field; + $this->options['where'][$logic][] = is_string($op) ? [$op, $field] : $field; return; } - if (is_string($field) && !empty($this->options['via'])) { + if (is_string($field) && !empty($this->options['via']) && !strpos($field, '.')) { $field = $this->options['via'] . '.' . $field; } if (is_string($field) && preg_match('/[,=\>\<\'\"\(\s]/', $field)) { @@ -844,61 +862,13 @@ class Query $where[$field] = [$op, $condition]; } if (!empty($where)) { - if (!isset($this->options['where'][$operator])) { - $this->options['where'][$operator] = []; + if (!isset($this->options['where'][$logic])) { + $this->options['where'][$logic] = []; } - $this->options['where'][$operator] = array_merge($this->options['where'][$operator], $where); + $this->options['where'][$logic] = array_merge($this->options['where'][$logic], $where); } } - /** - * 指定查询条件 - * @access public - * @param mixed $where 条件表达式 - * @return $this - */ - public function whereExist($where) - { - $this->options['where']['AND'][] = ['EXISTS', $where]; - return $this; - } - - /** - * 指定查询条件 - * @access public - * @param mixed $where 条件表达式 - * @return $this - */ - public function whereOrExist($where) - { - $this->options['where']['OR'][] = ['EXISTS', $where]; - return $this; - } - - /** - * 指定查询条件 - * @access public - * @param mixed $where 条件表达式 - * @return $this - */ - public function whereNotExist($where) - { - $this->options['where']['AND'][] = ['NOT EXISTS', $where]; - return $this; - } - - /** - * 指定查询条件 - * @access public - * @param mixed $where 条件表达式 - * @return $this - */ - public function whereOrNotExist($where) - { - $this->options['where']['OR'][] = ['NOT EXISTS', $where]; - return $this; - } - /** * 指定查询数量 * @access public From 731ab2b35a0f977d8ebae7e72618a71baefbf32e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 17:20:30 +0800 Subject: [PATCH 206/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3console=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=E4=B8=8B=E9=9D=A2=E9=A1=B5=E9=9D=A2trace=E6=8A=A5?= =?UTF-8?q?=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mode/console/App.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mode/console/App.php b/mode/console/App.php index 7376a84a..9b97b58a 100644 --- a/mode/console/App.php +++ b/mode/console/App.php @@ -24,6 +24,8 @@ class App { self::init(); + define('IS_AJAX', false); + // 实例化console $console = new Console('Think Console', '0.1'); // 读取指令集 From eadaef642512aeed6d2ad9f2ab30c070eef0aec8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 17:28:52 +0800 Subject: [PATCH 207/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E9=A1=B5=E9=9D=A2Tra?= =?UTF-8?q?ce?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/Trace.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index 7df777e1..6c7dfa78 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -41,7 +41,7 @@ class Trace */ public function save(array $log = []) { - if (IS_AJAX || IS_CLI || IS_API || (defined('RESPONSE_TYPE') && in_array(RESPONSE_TYPE, ['html', 'view']))) { + if (IS_AJAX || IS_CLI || IS_API || (defined('RESPONSE_TYPE') && !in_array(RESPONSE_TYPE, ['html', 'view']))) { // ajax cli api方式下不输出 return false; } From d122bad9b6976eb12c1da8a493c7bf7af031669a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 23:07:24 +0800 Subject: [PATCH 208/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0http=E5=8A=A9?= =?UTF-8?q?=E6=89=8B=E5=87=BD=E6=95=B0=20=E6=94=B9=E8=BF=9BApp=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 11 +++++++++++ library/think/App.php | 5 +++-- library/think/Loader.php | 4 +++- library/think/log/driver/Trace.php | 2 +- mode/console/App.php | 2 -- 5 files changed, 18 insertions(+), 6 deletions(-) diff --git a/helper.php b/helper.php index f7ac2303..7f2084b0 100644 --- a/helper.php +++ b/helper.php @@ -419,3 +419,14 @@ function redirect($url = [], $params = [], $code = 302) } return Response::create($url, 'redirect')->code($code)->params($params); } + +/** + * 抛出HTTP异常 + * @param integer $code 状态码 + * @param string $message 错误信息 + * @param array $header 参数 + */ +function http($code, $message = null, $header = []) +{ + throw new \think\exception\HttpException($code, $message, null, $header); +} diff --git a/library/think/App.php b/library/think/App.php index 8aa14a43..4feae3fc 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -13,6 +13,7 @@ namespace think; use think\Config; use think\Exception; +use think\exception\HttpException; use think\exception\HttpResponseException; use think\Hook; use think\Lang; @@ -249,7 +250,7 @@ class App // 初始化模块 $config = self::initModule(MODULE_NAME, $config); } else { - throw new Exception('module [ ' . MODULE_NAME . ' ] not exists ', 10005); + throw new HttpException(404,'module [ ' . MODULE_NAME . ' ] not exists '); } } else { // 单一模块部署 @@ -383,7 +384,7 @@ class App $result = Route::check($request, $path, $depr, !IS_CLI ? $config['url_domain_deploy'] : false); if (APP_ROUTE_MUST && false === $result && $config['url_route_must']) { // 路由无效 - throw new Exception('route not define '); + throw new HttpException(404, 'Not Found'); } } if (false === $result) { diff --git a/library/think/Loader.php b/library/think/Loader.php index f271a6b4..f0416ffc 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -11,6 +11,8 @@ namespace think; +use think\exception\HttpException; + class Loader { // 类名映射 @@ -319,7 +321,7 @@ class Loader } elseif ($empty && class_exists($emptyClass = self::parseClass($module, $layer, $empty, $appendSuffix))) { return new $emptyClass(Request::instance()); } else { - throw new Exception('class [ ' . $class . ' ] not exists', 10001); + throw new HttpException(404, 'class [ ' . $class . ' ] not exists'); } } diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index 6c7dfa78..58f1f71d 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -41,7 +41,7 @@ class Trace */ public function save(array $log = []) { - if (IS_AJAX || IS_CLI || IS_API || (defined('RESPONSE_TYPE') && !in_array(RESPONSE_TYPE, ['html', 'view']))) { + if (IS_CLI || IS_AJAX || IS_API || (defined('RESPONSE_TYPE') && !in_array(RESPONSE_TYPE, ['html', 'view']))) { // ajax cli api方式下不输出 return false; } diff --git a/mode/console/App.php b/mode/console/App.php index 9b97b58a..7376a84a 100644 --- a/mode/console/App.php +++ b/mode/console/App.php @@ -24,8 +24,6 @@ class App { self::init(); - define('IS_AJAX', false); - // 实例化console $console = new Console('Think Console', '0.1'); // 读取指令集 From 34731dd519729866d694d67113abf7b010164494 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 23:12:48 +0800 Subject: [PATCH 209/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/App.php b/library/think/App.php index 4feae3fc..b5dc5963 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -293,7 +293,7 @@ class App $data = $method->invokeArgs($instance, [$action, '']); APP_DEBUG && Log::record('[ RUN ] ' . $method->getFileName(), 'info'); } else { - throw new Exception('method [ ' . (new \ReflectionClass($instance))->getName() . '->' . $action . ' ] not exists ', 10002); + throw new HttpException(404,'method [ ' . (new \ReflectionClass($instance))->getName() . '->' . $action . ' ] not exists '); } } return $data; From c81bd184f559da8c6ab4e73eba60ef270bbd4d0e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 23:14:29 +0800 Subject: [PATCH 210/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index b5dc5963..7173c2fa 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -250,7 +250,7 @@ class App // 初始化模块 $config = self::initModule(MODULE_NAME, $config); } else { - throw new HttpException(404,'module [ ' . MODULE_NAME . ' ] not exists '); + throw new HttpException(404, 'module [ ' . MODULE_NAME . ' ] not exists '); } } else { // 单一模块部署 @@ -293,7 +293,7 @@ class App $data = $method->invokeArgs($instance, [$action, '']); APP_DEBUG && Log::record('[ RUN ] ' . $method->getFileName(), 'info'); } else { - throw new HttpException(404,'method [ ' . (new \ReflectionClass($instance))->getName() . '->' . $action . ' ] not exists '); + throw new HttpException(404, 'method [ ' . (new \ReflectionClass($instance))->getName() . '->' . $action . ' ] not exists '); } } return $data; From 67a91a776d0969a465d0d7aeac44b0997edc40d7 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 29 May 2016 23:15:26 +0800 Subject: [PATCH 211/670] =?UTF-8?q?http=E5=87=BD=E6=95=B0=E6=94=B9?= =?UTF-8?q?=E5=AE=8Cabort?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helper.php b/helper.php index 7f2084b0..ce25b9e6 100644 --- a/helper.php +++ b/helper.php @@ -426,7 +426,7 @@ function redirect($url = [], $params = [], $code = 302) * @param string $message 错误信息 * @param array $header 参数 */ -function http($code, $message = null, $header = []) +function abort($code, $message = null, $header = []) { throw new \think\exception\HttpException($code, $message, null, $header); } From 309c79f8c02c43a8af5621826399556767c1d83c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 11:31:16 +0800 Subject: [PATCH 212/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BBuilder=E7=B1=BB?= =?UTF-8?q?=E7=9A=84insertAll=E6=96=B9=E6=B3=95=20=E8=BF=87=E6=BB=A4?= =?UTF-8?q?=E9=9D=9E=E6=A0=87=E9=87=8F=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Builder.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index cfc38ffa..cf926f63 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -578,8 +578,11 @@ abstract class Builder throw new Exception(' fields not exists :[' . $key . ']'); } unset($data[$key]); - } else { + } elseif (is_scalar($val)) { $data[$key] = $this->parseValue($val); + } else { + // 过滤掉非标量数据 + unset($data[$key]); } } $value = array_values($data); From c287745704851d5a8d932cf4f674aa8689e25dee Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 12:43:47 +0800 Subject: [PATCH 213/670] =?UTF-8?q?=E7=94=B1=E4=BA=8E=E6=97=A0=E6=B3=95?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=20=E6=96=B9=E6=B3=95=E7=9A=84=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E6=8F=90=E7=A4=BA=20Request=E7=B1=BB=E9=9D=99?= =?UTF-8?q?=E6=80=81=E8=B0=83=E7=94=A8=E4=BB=8D=E7=84=B6=E6=94=B9=E5=9B=9E?= =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=B0=83=E7=94=A8=20=E6=94=B9=E8=BF=9BModel?= =?UTF-8?q?=E7=B1=BB=E4=B8=80=E5=A4=84=E5=85=B3=E8=81=94=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- library/think/Request.php | 90 +++++++++++++++++---------------------- 2 files changed, 39 insertions(+), 53 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index e7fe067c..4867434b 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -939,7 +939,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 记录当前关联信息 $model = $this->parseModel($model); $name = Loader::parseName(basename(str_replace('\\', '/', $model))); - $table = $table ?: Db::name(Loader::parseName($this->name) . '_' . $name)->getTable(); + $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); diff --git a/library/think/Request.php b/library/think/Request.php index 0abfbba9..1bfaaf71 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -195,7 +195,7 @@ class Request * @param string $url URL地址 * @return string */ - protected function domain($domain = '') + public function domain($domain = '') { if (!empty($domain)) { $this->domain = $domain; @@ -213,7 +213,7 @@ class Request * @param bool $domain 是否需要域名 * @return string */ - protected function url($url = '') + public function url($url = '') { if (is_string($url) && !empty($url)) { $this->url = $url; @@ -234,7 +234,7 @@ class Request * @param string $url URL地址 * @return string */ - protected function baseUrl($url = '') + public function baseUrl($url = '') { if (is_string($url) && !empty($url)) { $this->baseUrl = $url; @@ -252,7 +252,7 @@ class Request * @param string $file 当前执行的文件 * @return string */ - protected function baseFile($file = '') + public function baseFile($file = '') { if (is_string($file) && !empty($file)) { $this->baseFile = $file; @@ -284,7 +284,7 @@ class Request * @param string $url URL地址 * @return string */ - protected function root($url = '') + public function root($url = '') { if (is_string($url) && !empty($url)) { $this->root = $url; @@ -304,7 +304,7 @@ class Request * @access public * @return string */ - protected function pathinfo() + public function pathinfo() { if (is_null($this->pathinfo)) { if (isset($_GET[Config::get('var_pathinfo')])) { @@ -336,7 +336,7 @@ class Request * @access public * @return string */ - protected function path() + public function path() { if (is_null($this->path)) { // 去除正常的URL后缀 @@ -350,7 +350,7 @@ class Request * @access public * @return string */ - protected function ext() + public function ext() { return pathinfo($this->pathinfo(), PATHINFO_EXTENSION); } @@ -361,7 +361,7 @@ class Request * @param bool $float 是否使用浮点类型 * @return integer|float */ - protected function time($float = false) + public function time($float = false) { return $float ? $_SERVER['REQUEST_TIME_FLOAT'] : $_SERVER['REQUEST_TIME']; } @@ -371,7 +371,7 @@ class Request * @access public * @return false|string */ - protected function type() + public function type() { $accept = isset($this->server['HTTP_ACCEPT']) ? $this->server['HTTP_ACCEPT'] : $_SERVER['HTTP_ACCEPT']; if (empty($accept)) { @@ -396,7 +396,7 @@ class Request * @param string $val 资源类型 * @return void */ - protected function mimeType($type, $val = '') + public function mimeType($type, $val = '') { if (is_array($type)) { $this->mimeType = array_merge($this->mimeType, $type); @@ -411,7 +411,7 @@ class Request * @param string $method 请求类型 * @return string */ - protected function method($method = '') + public function method($method = '') { if ($method) { $this->method = $method; @@ -427,7 +427,7 @@ class Request * @access public * @return bool */ - protected function isGet() + public function isGet() { return $this->method() == 'GET'; } @@ -437,7 +437,7 @@ class Request * @access public * @return bool */ - protected function isPost() + public function isPost() { return $this->method() == 'POST'; } @@ -447,7 +447,7 @@ class Request * @access public * @return bool */ - protected function isPut() + public function isPut() { return $this->method() == 'PUT'; } @@ -457,7 +457,7 @@ class Request * @access public * @return bool */ - protected function isDelete() + public function isDelete() { return $this->method() == 'DELETE'; } @@ -467,7 +467,7 @@ class Request * @access public * @return bool */ - protected function isCli() + public function isCli() { return PHP_SAPI == 'cli'; } @@ -477,7 +477,7 @@ class Request * @access public * @return bool */ - protected function isCgi() + public function isCgi() { return strpos(PHP_SAPI, 'cgi') === 0; } @@ -489,7 +489,7 @@ class Request * @param mixed $default 默认值 * @return mixed */ - protected function param($name = '', $default = null) + public function param($name = '', $default = null) { if (empty($this->param)) { $method = $this->method(); @@ -524,7 +524,7 @@ class Request * @param bool $checkEmpty 是否检测空值 * @return mixed */ - protected function has($name, $checkEmpty = false) + public function has($name, $checkEmpty = false) { if (empty($this->param)) { $param = $this->param(); @@ -544,7 +544,7 @@ class Request * @param string|array $name 变量名 * @return mixed */ - protected function only($name) + public function only($name) { $param = $this->param(); if (is_string($name)) { @@ -565,7 +565,7 @@ class Request * @param string|array $name 变量名 * @return mixed */ - protected function except($name) + public function except($name) { $param = $this->param(); if (is_string($name)) { @@ -585,7 +585,7 @@ class Request * @param string $name 变量名 * @return mixed */ - protected function session($name = '') + public function session($name = '') { if (PHP_SESSION_DISABLED == session_status()) { session_start(); @@ -599,7 +599,7 @@ class Request * @param string $name 变量名 * @return mixed */ - protected function cookie($name = '') + public function cookie($name = '') { return Input::data($this->cookie ?: $_COOKIE, $name); } @@ -610,7 +610,7 @@ class Request * @param string $name 变量名 * @return mixed */ - protected function server($name = '') + public function server($name = '') { return Input::data($this->server ?: $_SERVER, $name); } @@ -621,7 +621,7 @@ class Request * @param string $name 名称 * @return null|array|\think\File */ - protected function file($name = '') + public function file($name = '') { return Input::file($name, $this->file ?: $_FILES); } @@ -631,7 +631,7 @@ class Request * @access public * @return bool */ - protected function isSsl() + public function isSsl() { $server = array_merge($_SERVER, $this->server); if (isset($server['HTTPS']) && ('1' == $server['HTTPS'] || 'on' == strtolower($server['HTTPS']))) { @@ -651,7 +651,7 @@ class Request * @access public * @return bool */ - protected function isAjax() + public function isAjax() { return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false; } @@ -661,7 +661,7 @@ class Request * @access public * @return bool */ - protected function isPjax() + public function isPjax() { return (isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX']) ? true : false; } @@ -672,7 +672,7 @@ class Request * @param boolean $adv 是否进行高级模式获取(有可能被伪装) * @return mixed */ - protected function ip($type = 0, $adv = false) + public function ip($type = 0, $adv = false) { $type = $type ? 1 : 0; static $ip = null; @@ -708,7 +708,7 @@ class Request * @access public * @return string */ - protected function scheme() + public function scheme() { return $this->isSsl() ? 'https' : 'http'; } @@ -718,7 +718,7 @@ class Request * @access public * @return string */ - protected function query() + public function query() { return $this->server('QUERY_STRING'); } @@ -728,7 +728,7 @@ class Request * @access public * @return string */ - protected function host() + public function host() { return $this->server('HTTP_HOST'); } @@ -738,7 +738,7 @@ class Request * @access public * @return integer */ - protected function port() + public function port() { return $this->server('SERVER_PORT'); } @@ -748,7 +748,7 @@ class Request * @access public * @return integer */ - protected function protocol() + public function protocol() { return $this->server('SERVER_PROTOCOL'); } @@ -758,7 +758,7 @@ class Request * @access public * @return integer */ - protected function remotePort() + public function remotePort() { return $this->server('REMOTE_PORT'); } @@ -769,7 +769,7 @@ class Request * @param array $route 路由名称 * @return array */ - protected function route($route = []) + public function route($route = []) { if (!empty($route)) { $this->route = $route; @@ -784,7 +784,7 @@ class Request * @param array $dispatch 调度信息 * @return array */ - protected function dispatch($dispatch = []) + public function dispatch($dispatch = []) { if (!empty($dispatch)) { $this->dispatch = $dispatch; @@ -792,18 +792,4 @@ class Request return $this->dispatch; } - public static function __callStatic($method, $params) - { - if (is_null(self::$instance)) { - self::instance(); - } - return call_user_func_array([self::$instance, $method], $params); - } - - public function __call($method, $params) - { - if (method_exists($this, $method)) { - return call_user_func_array([$this, $method], $params); - } - } } From 42fe2d3025efb51e4edf8a7fd84182565a4d9b55 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 12:52:42 +0800 Subject: [PATCH 214/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3APP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/App.php b/library/think/App.php index 7173c2fa..c3f71ecb 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -164,7 +164,7 @@ class App { if (empty($vars)) { // 自动获取请求变量 - $vars = Request::param(); + $vars = Request::instance()->param(); } if (is_array($method)) { $class = is_object($method[0]) ? $method[0] : new $method[0]; From 031de8c99d6def383c65ac86f9c6a7b798f45de2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 15:19:52 +0800 Subject: [PATCH 215/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=5F=5Fisset=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E5=99=A8=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index 4867434b..0cb19cda 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -1151,7 +1151,13 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function __isset($name) { - return isset($this->data[$name]); + if (isset($this->data[$name])) { + return true; + } elseif ($this->__get($name)) { + return true; + } else { + return false; + } } /** From 7d72c6743f7c47a326173cbb26e3871e68bbb810 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 16:01:40 +0800 Subject: [PATCH 216/670] =?UTF-8?q?=E4=BC=98=E5=8C=96Model=E7=B1=BB?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 170 +++++++++++++++++++++++----------------- 1 file changed, 97 insertions(+), 73 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 0cb19cda..8ca196bb 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -1034,45 +1034,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = $this->$method($value, $this->data); } elseif (isset($this->type[$name])) { // 类型转换 - $type = $this->type[$name]; - if (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 'datetime': - if (!is_numeric($value)) { - $value = strtotime($value); - } - break; - case 'timestamp': - $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 'json': - case 'array': - if (is_array($value)) { - $value = json_encode($value, JSON_UNESCAPED_UNICODE); - } - break; - } + $value = $this->writeTransform($value, $this->type[$name]); } } @@ -1084,6 +1046,56 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->data[$name] = $value; } + /** + * 数据写入 类型转换 + * @access public + * @param mixed $value 值 + * @param string $type 要转换的类型 + * @return mixed + */ + protected function writeTransform($value, $type) + { + if (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 'datetime': + if (!is_numeric($value)) { + $value = strtotime($value); + } + break; + case 'timestamp': + $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 'json': + case 'array': + if (is_array($value)) { + $value = json_encode($value, JSON_UNESCAPED_UNICODE); + } + break; + } + return $value; + } + /** * 获取器 获取数据对象的值 * @access public @@ -1100,40 +1112,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $this->$method($value, $this->data); } elseif (!is_null($value) && isset($this->type[$name])) { // 类型转换 - $type = $this->type[$name]; - if (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 'datetime': - $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, $value); - break; - case 'timestamp': - $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, strtotime($value)); - break; - case 'json': - case 'array': - $value = json_decode($value, true); - break; - case 'object': - $value = json_decode($value); - break; - } + $value = $this->readTransform($value, $this->type[$name]); } elseif (is_null($value) && method_exists($this, $name)) { // 获取关联数据 $value = $this->relation()->getRelation($name); @@ -1143,6 +1122,51 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $value; } + /** + * 数据读取 类型转换 + * @access public + * @param mixed $value 值 + * @param string $type 要转换的类型 + * @return mixed + */ + protected function readTransform($value, $type) + { + if (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 'datetime': + $format = !empty($param) ? $param : $this->dateFormat; + $value = date($format, $value); + break; + case 'timestamp': + $format = !empty($param) ? $param : $this->dateFormat; + $value = date($format, strtotime($value)); + break; + case 'json': + case 'array': + $value = json_decode($value, true); + break; + case 'object': + $value = json_decode($value); + break; + } + return $value; + } + /** * 检测数据对象的值 * @access public From d36903bddc15ec4af4e409b785493e5ae4c92c93 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 16:28:53 +0800 Subject: [PATCH 217/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getTableInfo=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=AF=B9=E8=A1=A8=E5=90=8D=E7=9A=84=E7=89=B9=E6=AE=8A=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 78ebc07b..0f542ec8 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1202,10 +1202,14 @@ class Query if (is_array($tableName)) { $tableName = key($tableName) ?: current($tableName); } + if (strpos($tableName, ',')) { // 多表不获取字段信息 return false; + } else { + $tableName = $this->connection->parseSqlTable($tableName); } + $guid = md5($tableName); if (!isset($_info[$guid])) { $info = $this->connection->getFields($tableName); From 6858abef7cfd3f114e1bbcab728c8c075d026f53 Mon Sep 17 00:00:00 2001 From: trojanbox Date: Mon, 30 May 2016 18:14:18 +0800 Subject: [PATCH 218/670] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=83=A8=E5=88=86?= =?UTF-8?q?=E7=B1=BB=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 1 + library/think/cache/driver/File.php | 7 ++++--- library/think/cache/driver/Xcache.php | 1 + library/traits/controller/Jump.php | 2 +- library/traits/think/Instance.php | 4 +++- 5 files changed, 10 insertions(+), 5 deletions(-) diff --git a/library/think/Response.php b/library/think/Response.php index 5b86e940..a59e23e5 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -66,6 +66,7 @@ class Response * @param mixed $data 输出数据 * @param string $type 输出类型 * @param array $options 输出参数 + * @return Response */ public static function create($data = [], $type = '', $options = []) { diff --git a/library/think/cache/driver/File.php b/library/think/cache/driver/File.php index 2c0ddff1..d8487102 100644 --- a/library/think/cache/driver/File.php +++ b/library/think/cache/driver/File.php @@ -32,7 +32,7 @@ class File /** * 架构函数 - * @access public + * @param array $options */ public function __construct($options = []) { @@ -54,10 +54,11 @@ class File { // 创建项目缓存目录 if (!is_dir($this->options['path'])) { - if (!mkdir($this->options['path'], 0755, true)) { - return false; + if (mkdir($this->options['path'], 0755, true)) { + return true; } } + return false; } /** diff --git a/library/think/cache/driver/Xcache.php b/library/think/cache/driver/Xcache.php index a529bed3..00a0483f 100644 --- a/library/think/cache/driver/Xcache.php +++ b/library/think/cache/driver/Xcache.php @@ -30,6 +30,7 @@ class Xcache * 架构函数 * @param array $options 缓存参数 * @access public + * @throws Exception */ public function __construct($options = []) { diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index ae5aaf90..c0c6b1b0 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -29,7 +29,7 @@ trait Jump * @param string $url 跳转的URL地址 * @param mixed $data 返回的数据 * @param integer $wait 跳转等待时间 - * @return void + * @return array */ public function success($msg = '', $url = null, $data = '', $wait = 3) { diff --git a/library/traits/think/Instance.php b/library/traits/think/Instance.php index d85975b3..de123079 100644 --- a/library/traits/think/Instance.php +++ b/library/traits/think/Instance.php @@ -11,6 +11,8 @@ namespace traits\think; +use \think\Exception; + trait Instance { protected static $instance = null; @@ -37,7 +39,7 @@ trait Instance if (0 === strpos($method, '_') && is_callable([self::$instance, $call])) { return call_user_func_array([self::$instance, $call], $params); } else { - throw new \think\Exception("not exists method:" . $method); + throw new Exception("not exists method:" . $method); } } } From 3f138c0395e88b107c1e3db229e350926530458f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 18:16:53 +0800 Subject: [PATCH 219/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=5F=5Fisset=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index 8ca196bb..759484a2 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -1175,7 +1175,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function __isset($name) { - if (isset($this->data[$name])) { + if (array_key_exists($name, $this->data)) { return true; } elseif ($this->__get($name)) { return true; From 2f5db5f22258d77dba787013fe9aeaf9cd4469b8 Mon Sep 17 00:00:00 2001 From: trojanbox Date: Mon, 30 May 2016 18:35:19 +0800 Subject: [PATCH 220/670] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=83=A8=E5=88=86?= =?UTF-8?q?=E7=B1=BB=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 1 + library/think/controller/Rest.php | 6 ++---- library/think/db/Connection.php | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/library/think/Response.php b/library/think/Response.php index a59e23e5..31052b84 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -88,6 +88,7 @@ class Response * @access public * @param mixed $data 数据 * @return mixed + * @throws Exception */ public function send($data = []) { diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index e88826d9..ebf53be8 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -57,12 +57,10 @@ abstract class Rest /** * REST 调用 * @access public - * * @param string $method 方法名 * @param array $args 参数 - * * @return mixed - * @throws \think\Exception + * @throws \Exception */ public function _empty($method, $args) { @@ -88,7 +86,7 @@ abstract class Rest * @param mixed $data 要返回的数据 * @param String $type 返回类型 JSON XML * @param integer $code HTTP状态 - * @return void + * @return Response */ protected function response($data, $type = 'json', $code = 200) { diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index b7d94dfb..1b3de0a6 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -128,7 +128,7 @@ abstract class Connection * 创建指定模型的查询对象 * @access public * @param string $model 模型类名称 - * @return \think\Query + * @return \think\db\Query */ public function model($model) { From 69fa69dc3b8a63b87b51b6cf64c44da127326485 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 21:34:48 +0800 Subject: [PATCH 221/670] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=A1=A8=E5=8D=95?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E7=B1=BB=E5=9E=8B=E4=BC=AA=E8=A3=85=E6=94=AF?= =?UTF-8?q?=E6=8C=81=20=E9=BB=98=E8=AE=A4=E5=8F=98=E9=87=8F=E4=B8=BA=20=5F?= =?UTF-8?q?method?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 2 ++ library/think/Request.php | 7 ++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/convention.php b/convention.php index d958784b..25fab9ed 100644 --- a/convention.php +++ b/convention.php @@ -83,6 +83,8 @@ return [ 'url_controller_convert' => true, // 是否自动转换URL中的操作名 'url_action_convert' => true, + // 表单请求类型伪装变量 + 'method_var' => '_method', // +---------------------------------------------------------------------- // | 模板引擎设置 diff --git a/library/think/Request.php b/library/think/Request.php index 1bfaaf71..4c5f305d 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -417,7 +417,12 @@ class Request $this->method = $method; return; } elseif (!$this->method) { - $this->method = IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); + $mask = $this->param(Config::get('method_var')); + if ($mask) { + $this->method = $mask; + } else { + $this->method = IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); + } } return $this->method; } From d5e73c34634be11722ba5a669bb400614f4567aa Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 21:49:38 +0800 Subject: [PATCH 222/670] =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 2 +- library/think/Request.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/convention.php b/convention.php index 25fab9ed..c86e1ea5 100644 --- a/convention.php +++ b/convention.php @@ -84,7 +84,7 @@ return [ // 是否自动转换URL中的操作名 'url_action_convert' => true, // 表单请求类型伪装变量 - 'method_var' => '_method', + 'var_method' => '_method', // +---------------------------------------------------------------------- // | 模板引擎设置 diff --git a/library/think/Request.php b/library/think/Request.php index 4c5f305d..df023124 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -417,7 +417,7 @@ class Request $this->method = $method; return; } elseif (!$this->method) { - $mask = $this->param(Config::get('method_var')); + $mask = $this->param(Config::get('var_method')); if ($mask) { $this->method = $mask; } else { From 6599c8c758ded4e1ad0e6ca8a97ed265340cc8c8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 22:04:22 +0800 Subject: [PATCH 223/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Request=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index df023124..f483e6c3 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -413,7 +413,10 @@ class Request */ public function method($method = '') { - if ($method) { + if (true === $method) { + // 获取原始请求类型 + return IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); + } elseif ($method) { $this->method = $method; return; } elseif (!$this->method) { @@ -497,7 +500,7 @@ class Request public function param($name = '', $default = null) { if (empty($this->param)) { - $method = $this->method(); + $method = $this->method(true); // 自动获取请求变量 switch ($method) { case 'POST': From 4a974f52a9ede0877a90b706c56568b730ea8e0f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 30 May 2016 22:49:15 +0800 Subject: [PATCH 224/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0agent=E5=92=8CisMobile=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/library/think/Request.php b/library/think/Request.php index f483e6c3..e056c551 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -711,6 +711,36 @@ class Request return $ip[$type]; } + /** + * 获取用户agent信息 + * @access public + * @return string + */ + public function agent() + { + return $this->server('HTTP_USER_AGENT'); + } + + /** + * 检测是否使用手机访问 + * @access public + * @return bool + */ + public function isMobile() + { + if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) { + return true; + } elseif (strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML")) { + return true; + } elseif (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) { + return true; + } elseif (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'])) { + return true; + } else { + return false; + } + } + /** * 当前URL地址中的scheme参数 * @access public From bd17e3008e899631fdbf9a6044b23af80ad6c366 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 09:09:24 +0800 Subject: [PATCH 225/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index e056c551..41af2323 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -420,9 +420,10 @@ class Request $this->method = $method; return; } elseif (!$this->method) { - $mask = $this->param(Config::get('var_method')); - if ($mask) { - $this->method = $mask; + if (isset($_POST[Config::get('var_method')])) { + $this->method = strtoupper($_POST[Config::get('var_method')]); + } elseif (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { + $this->method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']); } else { $this->method = IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); } From a7b2dbe86fedf97a5d96b8d794d4e98b52b8347c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 13:24:02 +0800 Subject: [PATCH 226/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BBmetho?= =?UTF-8?q?d=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 41af2323..579ca74e 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -408,7 +408,7 @@ class Request /** * 当前的请求类型 * @access public - * @param string $method 请求类型 + * @param bool $method true 获取原始请求类型 * @return string */ public function method($method = '') @@ -416,9 +416,6 @@ class Request if (true === $method) { // 获取原始请求类型 return IS_CLI ? 'GET' : (isset($this->server['REQUEST_METHOD']) ? $this->server['REQUEST_METHOD'] : $_SERVER['REQUEST_METHOD']); - } elseif ($method) { - $this->method = $method; - return; } elseif (!$this->method) { if (isset($_POST[Config::get('var_method')])) { $this->method = strtoupper($_POST[Config::get('var_method')]); From 98f89d8f8a4986b0c550e6ed56d98f42f926c552 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 14:12:05 +0800 Subject: [PATCH 227/670] =?UTF-8?q?=E5=8F=82=E6=95=B0=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index 579ca74e..325d7625 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -411,7 +411,7 @@ class Request * @param bool $method true 获取原始请求类型 * @return string */ - public function method($method = '') + public function method($method = false) { if (true === $method) { // 获取原始请求类型 From ead3cdee852447f1e3ed2859ee520907da1957f4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 16:20:27 +0800 Subject: [PATCH 228/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 50 +++++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 325d7625..ff17f42b 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -709,16 +709,6 @@ class Request return $ip[$type]; } - /** - * 获取用户agent信息 - * @access public - * @return string - */ - public function agent() - { - return $this->server('HTTP_USER_AGENT'); - } - /** * 检测是否使用手机访问 * @access public @@ -739,6 +729,46 @@ class Request } } + /** + * 获取请求的user agent信息 + * @access public + * @return string + */ + public function agent() + { + return $this->server('HTTP_USER_AGENT'); + } + + /** + * 获取请求的accept encoding + * @access public + * @return string + */ + public function encode() + { + return $this->server('HTTP_ACCEPT_ENCODING'); + } + + /** + * 获取请求的accept language + * @access public + * @return string + */ + public function language() + { + return $this->server('HTTP_ACCEPT_LANGUAGE'); + } + + /** + * 获取请求的cache control + * @access public + * @return string + */ + public function cache() + { + return $this->server('HTTP_CACHE_CONTROL'); + } + /** * 当前URL地址中的scheme参数 * @access public From 923c6657ad7bfe43b57f592d22e486a8aeb07bfd Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 16:52:20 +0800 Subject: [PATCH 229/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84lock=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81=E4=B8=BB?= =?UTF-8?q?=E4=BB=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 0f542ec8..bf883a83 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1051,7 +1051,8 @@ class Query */ public function lock($lock = false) { - $this->options['lock'] = $lock; + $this->options['lock'] = $lock; + $this->options['master'] = true; return $this; } From bf59fd8097144348583bf7d1a9c42528f98d44ab Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 17:37:04 +0800 Subject: [PATCH 230/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BConnection=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 1b3de0a6..20afc263 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -38,8 +38,6 @@ abstract class Connection protected $lastInsID; // 返回或者影响记录数 protected $numRows = 0; - // 事务的数据库连接 - protected $transPDO; // 事务指令数 protected $transTimes = 0; // 事务标识 @@ -52,6 +50,8 @@ abstract class Connection /** @var PDO 当前连接ID */ protected $linkID; + protected $linkRead; + protected $linkWrite; // 查询结果类型 protected $resultSetType = Db::RESULTSET_ARRAY; @@ -568,9 +568,6 @@ abstract class Connection if (0 == $this->transTimes) { $this->transLabel = $label; $this->linkID->beginTransaction(); - if (1 == $this->config['deploy']) { - $this->transPDO = $this->linkID; - } } $this->transTimes++; return null; @@ -585,13 +582,11 @@ abstract class Connection */ public function commit($label = '') { + $this->initConnect(true); if ($this->transTimes > 0 && $label == $this->transLabel) { try { $this->linkID->commit(); $this->transTimes = 0; - if (1 == $this->config['deploy']) { - $this->transPDO = null; - } } catch (\PDOException $e) { throw new PDOException($e, $this->config, $this->queryStr); } @@ -607,13 +602,11 @@ abstract class Connection */ public function rollback() { + $this->initConnect(true); if ($this->transTimes > 0) { try { $this->linkID->rollback(); $this->transTimes = 0; - if (1 == $this->config['deploy']) { - $this->transPDO = null; - } } catch (\PDOException $e) { throw new PDOException($e, $this->config, $this->queryStr); } @@ -820,12 +813,17 @@ abstract class Connection protected function initConnect($master = true) { if (!empty($this->config['deploy'])) { - if ($this->transPDO) { - // 使用事务连接 - $this->linkID = $this->transPDO; + // 采用分布式数据库 + if ($master) { + if (!$this->linkWrite) { + $this->linkWrite = $this->multiConnect(true); + } + $this->linkID = $this->linkWrite; } else { - // 采用分布式数据库 - $this->linkID = $this->multiConnect($master); + if (!$this->linkRead) { + $this->linkRead = $this->multiConnect(false); + } + $this->linkID = $this->linkRead; } } elseif (!$this->linkID) { // 默认单数据库 From c3d673dab42de39a10bcb933021e2e2d2de9d420 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 18:03:48 +0800 Subject: [PATCH 231/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BConnection=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E4=BA=8B=E5=8A=A1=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 20afc263..b3680d0a 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -545,9 +545,9 @@ abstract class Connection } $this->commit($label); return $result; - } catch (\PDOException $e) { + } catch (\Exception $e) { $this->rollback(); - return false; + throw $e; } } @@ -570,7 +570,7 @@ abstract class Connection $this->linkID->beginTransaction(); } $this->transTimes++; - return null; + return; } /** From 28254c8126bc5ec450340ccc979cde9071e2565c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 18:46:27 +0800 Subject: [PATCH 232/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Query=E7=B1=BB?= =?UTF-8?q?=E7=9A=84inserGetId=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index bf883a83..fd1f6c4a 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1437,16 +1437,18 @@ class Query * @param mixed $data 数据 * @param boolean $replace 是否replace * @param boolean $getLastInsID 是否获取自增ID + * @param string $sequence 自增序列名 * @return integer */ - public function insert(array $data, $replace = false, $getLastInsID = false) + public function insert(array $data, $replace = false, $getLastInsID = false, $sequence = null) { // 分析查询表达式 $options = $this->parseExpress(); // 生成SQL语句 - $sql = $this->builder()->insert($data, $options, $replace); + $sql = $this->builder()->insert($data, $options, $replace); + $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null); // 执行操作 - return $this->execute($sql, $this->getBind(), $options['fetch_sql'], $getLastInsID, isset($options['sequence']) ? $options['sequence'] : null); + return $this->execute($sql, $this->getBind(), $options['fetch_sql'], $getLastInsID, $sequence); } /** From dae42e9fa7b7a910862adc540536ebad2d21a88e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 21:57:12 +0800 Subject: [PATCH 233/670] =?UTF-8?q?Db=E7=B1=BB=E6=B3=A8=E9=87=8A=E5=AE=8C?= =?UTF-8?q?=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Db.php | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/library/think/Db.php b/library/think/Db.php index 18e5874c..bac2a063 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -11,8 +11,21 @@ namespace think; +use think\db\Query; + /** - * ThinkPHP 数据库中间层实现类 + * Class Db + * @package think + * @method Query table(string $table) static 指定数据表(含前缀) + * @method Query name(string $name) static 指定数据表(不含前缀) + * @method Query name(string $name) static 指定数据表(不含前缀) + * @method Query where($field, $op = null, $condition = null) static 查询条件 + * @method Query join($join, $condition = null, $type = 'INNER') static JOIN查询 + * @method Query union($union, $all = false) static UNION查询 + * @method Query limit($offset, $length = null) static 查询LIMIT + * @method Query order($field, $order = null) static 查询ORDER + * @method mixed query($sql, $bind = [], $fetch = false, $master = false, $class = false) static SQL查询 + * @method integer execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) static SQL执行 */ class Db { From a730f8152231004e5600b7c48c18c26405d17314 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 22:02:56 +0800 Subject: [PATCH 234/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Db.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/library/think/Db.php b/library/think/Db.php index bac2a063..06362951 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -18,14 +18,14 @@ use think\db\Query; * @package think * @method Query table(string $table) static 指定数据表(含前缀) * @method Query name(string $name) static 指定数据表(不含前缀) - * @method Query name(string $name) static 指定数据表(不含前缀) - * @method Query where($field, $op = null, $condition = null) static 查询条件 - * @method Query join($join, $condition = null, $type = 'INNER') static JOIN查询 - * @method Query union($union, $all = false) static UNION查询 - * @method Query limit($offset, $length = null) static 查询LIMIT - * @method Query order($field, $order = null) static 查询ORDER - * @method mixed query($sql, $bind = [], $fetch = false, $master = false, $class = false) static SQL查询 - * @method integer execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) static SQL执行 + * @method Query where(array|string $field, string $op = null, mixed $condition = null) static 查询条件 + * @method Query join(array|string $join, mixed $condition = null, string $type = 'INNER') static JOIN查询 + * @method Query union(string|array $union, boolean $all = false) static UNION查询 + * @method Query limit(string|integer $offset, integer $length = null) static 查询LIMIT + * @method Query order(string|array $field, string $order = null) static 查询ORDER + * @method mixed query(string $sql, array $bind = [], boolean $fetch = false, boolean $master = false, mixed $class = 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, boolean $simple = false, array $config = []) static 分页查询 */ class Db { From d69cd6308dc30af12494d605ac1463cfe5763c98 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 22:16:21 +0800 Subject: [PATCH 235/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BBisMob?= =?UTF-8?q?ile=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index ff17f42b..21f92ad7 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -722,7 +722,7 @@ class Request return true; } elseif (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) { return true; - } elseif (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 (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'])) { return true; } else { return false; From 6248dff43beaba9a2b57b35d1943115b0a19ae0b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 31 May 2016 23:01:21 +0800 Subject: [PATCH 236/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 58 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 4 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 21f92ad7..f5810ac0 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -192,7 +192,7 @@ class Request /** * 获取当前包含协议的域名 * @access public - * @param string $url URL地址 + * @param string $domain 域名 * @return string */ public function domain($domain = '') @@ -209,8 +209,7 @@ class Request /** * 获取当前完整URL 包括QUERY_STRING * @access public - * @param string $url URL地址 - * @param bool $domain 是否需要域名 + * @param string|true $url URL地址 true 带域名获取 * @return string */ public function url($url = '') @@ -221,8 +220,14 @@ class Request } elseif (!$this->url) { if (IS_CLI) { $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'] : ''); } else { - $this->url = $_SERVER[Config::get('url_request_uri')]; + $this->url = ''; } } return true === $url ? $this->domain() . $this->url : $this->url; @@ -468,6 +473,36 @@ class Request return $this->method() == 'DELETE'; } + /** + * 是否为HEAD请求 + * @access public + * @return bool + */ + public function isHead() + { + return $this->method() == 'HEAD'; + } + + /** + * 是否为PATCH请求 + * @access public + * @return bool + */ + public function isPatch() + { + return $this->method() == 'PATCH'; + } + + /** + * 是否为OPTIONS请求 + * @access public + * @return bool + */ + public function isOptions() + { + return $this->method() == 'OPTIONS'; + } + /** * 是否为cli * @access public @@ -769,6 +804,21 @@ class Request return $this->server('HTTP_CACHE_CONTROL'); } + /** + * 获取当前请求的content type + * @access public + * @return string + */ + public function getContentType() + { + if (isset($_SERVER["CONTENT_TYPE"])) { + return $_SERVER["CONTENT_TYPE"]; + } elseif (isset($_SERVER["HTTP_CONTENT_TYPE"])) { + return $_SERVER["HTTP_CONTENT_TYPE"]; + } + return null; + } + /** * 当前URL地址中的scheme参数 * @access public From 431c5d1a28e0495f0f512e9544db182f5e7e4af9 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 08:34:04 +0800 Subject: [PATCH 237/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84chunk=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81=E5=8F=82?= =?UTF-8?q?=E6=95=B0=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index fd1f6c4a..b7a2ee65 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1720,6 +1720,7 @@ class Query { $column = $column ?: $this->getPk(); $options = $this->getOptions(); + $bind = $this->bind; $resultSet = $this->limit($count)->order($column, 'asc')->select(); while (!empty($resultSet)) { @@ -1730,6 +1731,7 @@ class Query $lastId = is_array($end) ? $end[$column] : $end->$column; $resultSet = $this->options($options) ->limit($count) + ->bind($bind) ->where($column, '>', $lastId) ->order($column, 'asc') ->select(); From 83cb8093aa0fa081d28865a26abdcd93132aeaa4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 10:47:30 +0800 Subject: [PATCH 238/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Db.php | 6 ++++++ library/think/db/Query.php | 30 ++++++++++++++++-------------- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/library/think/Db.php b/library/think/Db.php index 06362951..232fde4f 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -11,7 +11,9 @@ namespace think; +use think\Collection; use think\db\Query; +use think\Model; /** * Class Db @@ -23,6 +25,10 @@ use think\db\Query; * @method Query union(string|array $union, boolean $all = false) static UNION查询 * @method Query limit(string|integer $offset, integer $length = null) static 查询LIMIT * @method Query order(string|array $field, string $order = null) static 查询ORDER + * @method mixed value(string $field) static 获取某个字段的值 + * @method array column(string $field, string $key = '') static 获取某个列的值 + * @method array|false|\PDOStatement|string|Model find(mixed $data = []) static 查询单个记录 + * @method Collection|false|\PDOStatement|string select(mixed $data = []) static 查询多个记录 * @method mixed query(string $sql, array $bind = [], boolean $fetch = false, boolean $master = false, mixed $class = 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, boolean $simple = false, array $config = []) static 分页查询 diff --git a/library/think/db/Query.php b/library/think/db/Query.php index b7a2ee65..52347859 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -16,8 +16,11 @@ use think\Cache; use think\Collection; use think\Config; use think\Db; +use think\db\Builder; +use think\db\Connection; use think\Exception; use think\exception\DbException; +use think\exception\PDOException; use think\Loader; use think\Model; use think\model\Relation; @@ -43,11 +46,10 @@ class Query /** * 架构函数 * @access public - * @param \think\db\Connection|string $connection 数据库对象实例 + * @param Connection $connection 数据库对象实例 * @param string $model 模型名 - * @throws Exception */ - public function __construct($connection = '', $model = '') + public function __construct(Connection $connection = null, $model = '') { $this->connection = $connection ?: Db::connect([], true); $this->driver = $this->connection->getDriverName(); @@ -83,7 +85,7 @@ class Query /** * 获取当前的数据库Connection对象 * @access public - * @return \think\db\Connection + * @return Connection */ public function getConnection() { @@ -115,7 +117,7 @@ class Query } /** - * 得到当前的数据表 + * 得到当前或者指定名称的数据表 * @access public * @param string $name * @return string @@ -317,7 +319,7 @@ class Query /** * 获取当前的builder实例对象 * @access protected - * @return \think\db\Builder + * @return Builder */ protected function builder() { @@ -1395,7 +1397,7 @@ class Query /** * 把主键值转换为查询条件 支持复合主键 * @access public - * @param array $data 主键数据 + * @param array|string $data 主键数据 * @param mixed $options 表达式参数 * @return void * @throws \think\Exception @@ -1489,7 +1491,7 @@ class Query * @param string $fields 要插入的数据表字段名 * @param string $table 要插入的数据表名 * @return int - * @throws \think\exception\PDOException + * @throws PDOException */ public function selectInsert($fields, $table) { @@ -1507,7 +1509,7 @@ class Query * @param mixed $data 数据 * @return int * @throws Exception - * @throws \think\exception\PDOException + * @throws PDOException */ public function update(array $data) { @@ -1549,11 +1551,11 @@ class Query /** * 查找记录 * @access public - * @param array $data + * @param array|string|Query|\Closure $data * @return Collection|false|\PDOStatement|string * @throws DbException * @throws Exception - * @throws \think\exception\PDOException + * @throws PDOException */ public function select($data = []) { @@ -1632,11 +1634,11 @@ class Query /** * 查找单条记录 * @access public - * @param array $data 表达式 + * @param array|string|Query|\Closure $data * @return array|false|\PDOStatement|string|Model * @throws DbException * @throws Exception - * @throws \think\exception\PDOException + * @throws PDOException */ public function find($data = []) { @@ -1769,7 +1771,7 @@ class Query * @param array $data 表达式 * @return int * @throws Exception - * @throws \think\exception\PDOException + * @throws PDOException */ public function delete($data = []) { From 994b15944effa5687fe9d049be408f8cb3d87858 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 11:10:53 +0800 Subject: [PATCH 239/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Db.php | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/library/think/Db.php b/library/think/Db.php index 232fde4f..bd537399 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -13,22 +13,21 @@ namespace think; use think\Collection; use think\db\Query; -use think\Model; /** * Class Db * @package think * @method Query table(string $table) static 指定数据表(含前缀) * @method Query name(string $name) static 指定数据表(不含前缀) - * @method Query where(array|string $field, string $op = null, mixed $condition = null) static 查询条件 - * @method Query join(array|string $join, mixed $condition = null, string $type = 'INNER') static JOIN查询 - * @method Query union(string|array $union, boolean $all = false) static UNION查询 - * @method Query limit(string|integer $offset, integer $length = null) static 查询LIMIT - * @method Query order(string|array $field, string $order = null) static 查询ORDER + * @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 mixed value(string $field) static 获取某个字段的值 * @method array column(string $field, string $key = '') static 获取某个列的值 - * @method array|false|\PDOStatement|string|Model find(mixed $data = []) static 查询单个记录 - * @method Collection|false|\PDOStatement|string select(mixed $data = []) static 查询多个记录 + * @method mixed find(mixed $data = []) static 查询单个记录 + * @method mixed select(mixed $data = []) static 查询多个记录 * @method mixed query(string $sql, array $bind = [], boolean $fetch = false, boolean $master = false, mixed $class = 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, boolean $simple = false, array $config = []) static 分页查询 From ec8234d5b641097c4d5ae08368e7f05d04a1147b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 12:14:26 +0800 Subject: [PATCH 240/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 2 +- library/think/Config.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/helper.php b/helper.php index ce25b9e6..d796aa48 100644 --- a/helper.php +++ b/helper.php @@ -84,7 +84,7 @@ function lang($name, $vars = [], $lang = '') /** * 获取和设置配置参数 - * @param string $name 参数名 + * @param string|array $name 参数名 * @param mixed $value 参数值 * @param string $range 作用域 * @return mixed diff --git a/library/think/Config.php b/library/think/Config.php index 2c833111..ed1f1e7b 100644 --- a/library/think/Config.php +++ b/library/think/Config.php @@ -136,7 +136,7 @@ class Config /** * 设置配置参数 name为数组则为批量设置 - * @param string $name 配置参数名(支持二级配置 .号分割) + * @param string|array $name 配置参数名(支持二级配置 .号分割) * @param mixed $value 配置值 * @param string $range 作用域 * @return mixed From 4d00aa539fc30eb42b234795368a4acb137222fd Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 12:27:28 +0800 Subject: [PATCH 241/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E6=94=B9=E8=BF=9B=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0Json=E9=85=8D=E7=BD=AE=E9=A9=B1=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Config.php | 8 ++++++-- library/think/config/driver/Json.php | 24 ++++++++++++++++++++++++ library/think/db/Builder.php | 10 ++++++---- library/think/db/Connection.php | 3 ++- library/think/model/Relation.php | 4 ++-- 5 files changed, 40 insertions(+), 9 deletions(-) create mode 100644 library/think/config/driver/Json.php diff --git a/library/think/Config.php b/library/think/Config.php index ed1f1e7b..774a58a4 100644 --- a/library/think/Config.php +++ b/library/think/Config.php @@ -177,7 +177,11 @@ class Config */ public static function reset($range = '') { - $range = $range ?: self::$range; - true === $range ? self::$config = [] : self::$config[$range] = []; + $range = $range ?: self::$range; + if (true === $range) { + self::$config = []; + } else { + self::$config[$range] = []; + } } } diff --git a/library/think/config/driver/Json.php b/library/think/config/driver/Json.php new file mode 100644 index 00000000..ec2419f9 --- /dev/null +++ b/library/think/config/driver/Json.php @@ -0,0 +1,24 @@ + +// +---------------------------------------------------------------------- + +namespace think\config\driver; + +class Json +{ + public function parse($config) + { + if (is_file($config)) { + $config = file_get_contents($config); + } + $result = json_decode($config, true); + return $result; + } +} diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index cf926f63..e9d22eff 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -13,6 +13,8 @@ namespace think\db; use PDO; use think\Db; +use think\db\Connection; +use think\db\Query; use think\Exception; abstract class Builder @@ -38,9 +40,9 @@ abstract class Builder /** * 架构函数 * @access public - * @param \think\db\Connection $connection 数据库连接对象实例 + * @param Connection $connection 数据库连接对象实例 */ - public function __construct($connection) + public function __construct(Connection $connection) { $this->connection = $connection; } @@ -48,10 +50,10 @@ abstract class Builder /** * 设置当前的Query对象实例 * @access protected - * @param \think\db\Query $query 当前查询对象实例 + * @param Query $query 当前查询对象实例 * @return void */ - public function setQuery($query) + public function setQuery(Query $query) { $this->query = $query; } diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index b3680d0a..ddcfbe4b 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -15,6 +15,7 @@ use PDO; use PDOStatement; use think\Collection; use think\Db; +use think\db\Query; use think\Debug; use think\Exception; use think\exception\DbBindParamException; @@ -128,7 +129,7 @@ abstract class Connection * 创建指定模型的查询对象 * @access public * @param string $model 模型类名称 - * @return \think\db\Query + * @return Query */ public function model($model) { diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index ac88e6a0..03e2a04d 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -45,9 +45,9 @@ class Relation /** * 架构函数 * @access public - * @param \think\Model $model 上级模型对象 + * @param Model $model 上级模型对象 */ - public function __construct($model) + public function __construct(Model $model) { $this->parent = $model; } From c6595f23aa3fe6d7fe70f13573d27758f4e38bee Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 12:42:51 +0800 Subject: [PATCH 242/670] =?UTF-8?q?Connection=E7=B1=BB=E7=9A=84parseSqlTab?= =?UTF-8?q?le=E6=96=B9=E6=B3=95=E7=A7=BB=E5=8A=A8=E5=88=B0Query=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Builder.php | 2 +- library/think/db/Connection.php | 17 ----------------- library/think/db/Query.php | 28 ++++++++++++++++++++++++---- 3 files changed, 25 insertions(+), 22 deletions(-) diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index e9d22eff..bde2b930 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -66,7 +66,7 @@ abstract class Builder */ protected function parseSqlTable($sql) { - return $this->connection->parseSqlTable($sql); + return $this->query->parseSqlTable($sql); } /** diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index ddcfbe4b..31f3e1f0 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -643,23 +643,6 @@ abstract class Connection return true; } - /** - * 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写) - * @access public - * @param string $sql sql语句 - * @return string - */ - public function parseSqlTable($sql) - { - if (false !== strpos($sql, '__')) { - $prefix = $this->config['prefix']; - $sql = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) { - return $prefix . strtolower($match[1]); - }, $sql); - } - return $sql; - } - /** * 获得查询次数 * @access public diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 52347859..eb738c9d 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -38,6 +38,8 @@ class Query protected $table = ''; // 当前数据表名称(不含前缀) protected $name = ''; + // 当前数据表前缀 + protected $prefix = ''; // 查询参数 protected $options = []; // 参数绑定 @@ -53,6 +55,7 @@ class Query { $this->connection = $connection ?: Db::connect([], true); $this->driver = $this->connection->getDriverName(); + $this->prefix = $this->connection->getConfig('prefix'); $this->model = $model; } @@ -126,7 +129,7 @@ class Query { if ($name || empty($this->table)) { $name = $name ?: $this->name; - $tableName = $this->getConfig('prefix'); + $tableName = $this->prefix; if ($name) { $tableName .= Loader::parseName($name); } @@ -136,6 +139,23 @@ class Query return $tableName; } + /** + * 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写) + * @access public + * @param string $sql sql语句 + * @return string + */ + public function parseSqlTable($sql) + { + 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); + } + return $sql; + } + /** * 执行查询 返回数据集 * @access public @@ -603,7 +623,7 @@ class Query } } } else { - $prefix = $this->getConfig('prefix'); + $prefix = $this->prefix; // 传入的表名为数组 if (is_array($join)) { if (0 !== $key = key($join)) { @@ -622,7 +642,7 @@ class Query } else { $join = trim($join); if (0 === strpos($join, '__')) { - $table = $this->connection->parseSqlTable($join); + $table = $this->parseSqlTable($join); } elseif (false === strpos($join, '(') && false === strpos($join, '.') && !empty($prefix) && 0 !== strpos($join, $prefix)) { // 传入的表名中不带有'('并且不以默认的表前缀开头时加上默认的表前缀 $table = $prefix . $join; @@ -1210,7 +1230,7 @@ class Query // 多表不获取字段信息 return false; } else { - $tableName = $this->connection->parseSqlTable($tableName); + $tableName = $this->parseSqlTable($tableName); } $guid = md5($tableName); From 3420eb5f60c517f2cfcb7a8e63f686857009fc67 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 12:56:22 +0800 Subject: [PATCH 243/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index eb738c9d..99b4ebe9 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -526,7 +526,7 @@ class Query * @param integer $step 增长值 * @param integer $lazyTime 延时时间(s) * @return integer|true - * @throws \think\Exception + * @throws Exception */ public function setInc($field, $step = 1, $lazyTime = 0) { @@ -553,7 +553,7 @@ class Query * @param integer $step 减少值 * @param integer $lazyTime 延时时间(s) * @return integer|true - * @throws \think\Exception + * @throws Exception */ public function setDec($field, $step = 1, $lazyTime = 0) { @@ -1420,7 +1420,7 @@ class Query * @param array|string $data 主键数据 * @param mixed $options 表达式参数 * @return void - * @throws \think\Exception + * @throws Exception */ protected function parsePkWhere($data, &$options) { From dfa5143dad9123e04ecf7bf5b7bd9cefe504fc9c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 14:13:21 +0800 Subject: [PATCH 244/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0url=5Fparam=5Ftype?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=8F=82=E6=95=B0=20=E7=94=A8=E4=BA=8E?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E6=93=8D=E4=BD=9C=E6=96=B9=E6=B3=95=E7=9A=84?= =?UTF-8?q?=E5=8F=82=E6=95=B0=E7=BB=91=E5=AE=9A=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 4 ++-- helper.php | 4 ++-- library/think/App.php | 2 +- library/think/Route.php | 18 ++++++++++++------ 4 files changed, 17 insertions(+), 11 deletions(-) diff --git a/convention.php b/convention.php index c86e1ea5..37a316a7 100644 --- a/convention.php +++ b/convention.php @@ -63,14 +63,14 @@ return [ 'pathinfo_fetch' => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'], // pathinfo分隔符 'pathinfo_depr' => '/', - // 获取当前页面地址的系统变量 默认为REQUEST_URI - 'url_request_uri' => 'REQUEST_URI', // URL伪静态后缀 'url_html_suffix' => 'html', // URL普通方式参数 用于自动生成 'url_common_param' => false, //url禁止访问的后缀 'url_deny_suffix' => 'ico|png|gif|jpg', + // URL参数方式 0 按名称成对解析 1 按顺序解析 + 'url_param_type' => 0, // 是否开启路由 'url_route_on' => true, // 是否强制使用路由 diff --git a/helper.php b/helper.php index d796aa48..ee301b07 100644 --- a/helper.php +++ b/helper.php @@ -337,7 +337,7 @@ function trace($log = '[think]', $level = 'log') /** * 获取当前Request对象实例 - * @return \think\Request + * @return Request */ function request() { @@ -349,7 +349,7 @@ function request() * @param mixed $data 输出数据 * @param string $type 输出类型 * @param array $options 参数 - * @return \think\Response + * @return Response */ function response($data = [], $type = '', $options = []) { diff --git a/library/think/App.php b/library/think/App.php index c3f71ecb..9b0f613a 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -389,7 +389,7 @@ class App } if (false === $result) { // 路由无效 解析模块/控制器/操作/参数... 支持控制器自动搜索 - $result = Route::parseUrl($path, $depr, $config['controller_auto_search']); + $result = Route::parseUrl($path, $depr, $config['controller_auto_search'], $config['url_param_type']); } //保证$_REQUEST正常取值 $_REQUEST = array_merge($_POST, $_GET, $_COOKIE); diff --git a/library/think/Route.php b/library/think/Route.php index a4fd5c76..804b7ead 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -827,9 +827,10 @@ class Route * @param string $url URL地址 * @param string $depr URL分隔符 * @param bool $autoSearch 是否自动深度搜索控制器 + * @param integer $paramType URL参数解析方式 0 名称解析 1 顺序解析 * @return array */ - public static function parseUrl($url, $depr = '/', $autoSearch = false) + public static function parseUrl($url, $depr = '/', $autoSearch = false, $paramType = 0) { if (isset(self::$bind['module'])) { // 如果有模块/控制器绑定 @@ -840,7 +841,7 @@ class Route $url = str_replace($depr, '/', $url); } - $result = self::parseRoute($url, $autoSearch, true); + $result = self::parseRoute($url, $autoSearch, true, $paramType); if (!empty($result['var'])) { $_GET = array_merge($result['var'], $_GET); @@ -854,9 +855,10 @@ class Route * @param string $url URL地址 * @param bool $autoSearch 是否自动深度搜索控制器 * @param bool $reverse 是否反转解析URL + * @param integer $paramType URL参数解析方式 0 名称解析 1 顺序解析 * @return array */ - private static function parseRoute($url, $autoSearch = false, $reverse = false) + private static function parseRoute($url, $autoSearch = false, $reverse = false, $paramType = 0) { $url = trim($url, '/'); $var = []; @@ -901,9 +903,13 @@ class Route $action = !empty($path) ? array_shift($path) : null; // 解析额外参数 if (!empty($path)) { - preg_replace_callback('/([^\/]+)\/([^\/]+)/', function ($match) use (&$var) { - $var[strtolower($match[1])] = strip_tags($match[2]); - }, implode('/', $path)); + if ($paramType) { + $var += $path; + } else { + preg_replace_callback('/([^\/]+)\/([^\/]+)/', function ($match) use (&$var) { + $var[strtolower($match[1])] = strip_tags($match[2]); + }, implode('/', $path)); + } } } else { $action = array_pop($path); From 48ab620b342e3e35856892a966d85660ea518d72 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 14:16:37 +0800 Subject: [PATCH 245/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84saveAll=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 1 + 1 file changed, 1 insertion(+) diff --git a/library/think/Model.php b/library/think/Model.php index 759484a2..47ff150c 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -411,6 +411,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function saveAll($dataSet) { + $result = 0; foreach ($dataSet as $data) { $result = $this->isUpdate(false)->save($data, [], false); } From bebe73e5a79d8c8b360bf6da4b6e967653ab35b8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 14:40:11 +0800 Subject: [PATCH 246/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E7=9A=84=E5=8F=82=E6=95=B0=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 804b7ead..db6f4748 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -1061,9 +1061,13 @@ class Route private static function parseUrlParams($url, $var) { if ($url) { - preg_replace_callback('/(\w+)\/([^\/]+)/', function ($match) use (&$var) { - $var[strtolower($match[1])] = strip_tags($match[2]); - }, $url); + if (Config::get('url_param_type')) { + $var += explode('/', $url); + } else { + preg_replace_callback('/(\w+)\/([^\/]+)/', function ($match) use (&$var) { + $var[strtolower($match[1])] = strip_tags($match[2]); + }, $url); + } } $_GET = array_merge($var, $_GET); } From 5ab7f81c4473595f5dd1fcad3a556988b13f31a8 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 1 Jun 2016 16:32:31 +0800 Subject: [PATCH 247/670] =?UTF-8?q?=E5=AE=8C=E5=96=84=E8=A1=8C=E4=B8=BA?= =?UTF-8?q?=E6=89=A9=E5=B1=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Hook.php | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/library/think/Hook.php b/library/think/Hook.php index 82834542..838ab100 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -88,13 +88,15 @@ class Hook /** * 监听标签的行为 - * @param string $tag 标签名称 - * @param mixed $params 传入参数 - * @param mixed $extra 额外参数 - * @return void + * @param string $tag 标签名称 + * @param mixed $params 传入参数 + * @param mixed $extra 额外参数 + * @param bool $once 只获取一个有效返回值 + * @return bool|mixed|void */ - public static function listen($tag, &$params = null,$extra=null) { - $result = true; + public static function listen($tag, &$params = null, $extra = null, $once = false) + { + $results = []; if (isset(self::$tags[$tag])) { foreach (self::$tags[$tag] as $name) { @@ -102,7 +104,11 @@ class Hook Debug::remark('behavior_start', 'time'); } - $result = self::exec($name, $tag, $params,$extra); + $result = self::exec($name, $tag, $params, $extra); + + if (!is_null($result) && $once) { + return $result; + } if (APP_DEBUG) { Debug::remark('behavior_end', 'time'); @@ -115,11 +121,12 @@ class Hook } if (false === $result) { // 如果返回false 则中断行为执行 - return; + break; } + $results[] = $result; } } - return $result; + return $once ? null : $results; } /** From 96992e9f7b39b38c5078a725995f58cee6570f13 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 1 Jun 2016 16:33:02 +0800 Subject: [PATCH 248/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Hook.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Hook.php b/library/think/Hook.php index 838ab100..0a1fe9e4 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -92,7 +92,7 @@ class Hook * @param mixed $params 传入参数 * @param mixed $extra 额外参数 * @param bool $once 只获取一个有效返回值 - * @return bool|mixed|void + * @return mixed */ public static function listen($tag, &$params = null, $extra = null, $once = false) { From 12196d21b8c616480a03ebcd0d820de39edc68b5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 16:34:24 +0800 Subject: [PATCH 249/670] =?UTF-8?q?=E5=8F=96=E6=B6=88=20CONTROLLER=5FLAYER?= =?UTF-8?q?=20MODEL=5FLAYER=20VIEW=5FLAYER=20VALIDATE=5FLAYER=20=E5=B8=B8?= =?UTF-8?q?=E9=87=8F=20=E5=A2=9E=E5=8A=A0url=5Fcontroller=5Flayer=20?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 22 ++++++++-------------- convention.php | 2 ++ helper.php | 6 +++--- library/think/App.php | 6 +++--- library/think/Build.php | 10 +++++----- library/think/Loader.php | 12 ++++++------ library/think/Route.php | 4 ++-- library/think/db/Builder.php | 6 +++++- library/think/view/driver/Php.php | 2 +- library/think/view/driver/Think.php | 2 +- tests/thinkphp/baseTest.php | 3 --- 11 files changed, 36 insertions(+), 39 deletions(-) diff --git a/base.php b/base.php index 272fd268..f418428d 100644 --- a/base.php +++ b/base.php @@ -9,21 +9,20 @@ // | Author: liu21st // +---------------------------------------------------------------------- -// 开始运行时间和内存使用 +define('THINK_VERSION', '5.0.0 RC3'); define('START_TIME', microtime(true)); define('START_MEM', memory_get_usage()); -// 版本信息 -define('THINK_VERSION', '5.0.0 RC3'); -// 系统常量 -defined('DS') or define('DS', DIRECTORY_SEPARATOR); +define('EXT', '.php'); +define('DS', DIRECTORY_SEPARATOR); defined('THINK_PATH') or define('THINK_PATH', dirname(__FILE__) . DS); +define('LIB_PATH', THINK_PATH . 'library' . DS); +define('MODE_PATH', THINK_PATH . 'mode' . 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(APP_PATH) . DS); -defined('LIB_PATH') or define('LIB_PATH', THINK_PATH . 'library' . DS); defined('EXTEND_PATH') or define('EXTEND_PATH', ROOT_PATH . 'extend' . DS); -defined('MODE_PATH') or define('MODE_PATH', THINK_PATH . 'mode' . DS); // 系统应用模式目录 -defined('CORE_PATH') or define('CORE_PATH', LIB_PATH . 'think' . DS); -defined('TRAIT_PATH') or define('TRAIT_PATH', LIB_PATH . 'traits' . DS); defined('APP_NAMESPACE') or define('APP_NAMESPACE', 'app'); defined('COMMON_MODULE') or define('COMMON_MODULE', 'common'); defined('RUNTIME_PATH') or define('RUNTIME_PATH', ROOT_PATH . 'runtime' . DS); @@ -31,13 +30,8 @@ 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('VENDOR_PATH') or define('VENDOR_PATH', ROOT_PATH . 'vendor' . DS); -defined('EXT') or define('EXT', '.php'); defined('CONF_PATH') or define('CONF_PATH', APP_PATH); // 配置文件目录 defined('CONF_EXT') or define('CONF_EXT', EXT); // 配置文件后缀 -defined('MODEL_LAYER') or define('MODEL_LAYER', 'model'); -defined('VIEW_LAYER') or define('VIEW_LAYER', 'view'); -defined('CONTROLLER_LAYER') or define('CONTROLLER_LAYER', 'controller'); -defined('VALIDATE_LAYER') or define('VALIDATE_LAYER', 'validate'); defined('APP_MULTI_MODULE') or define('APP_MULTI_MODULE', true); // 是否多模块 defined('ENV_PREFIX') or define('ENV_PREFIX', 'PHP_'); // 环境变量的配置前缀 defined('IS_API') or define('IS_API', false); // 是否API接口 diff --git a/convention.php b/convention.php index 37a316a7..1cb33eb6 100644 --- a/convention.php +++ b/convention.php @@ -83,6 +83,8 @@ return [ 'url_controller_convert' => true, // 是否自动转换URL中的操作名 'url_action_convert' => true, + // 默认的访问控制器层 + 'url_controller_layer' => 'controller', // 表单请求类型伪装变量 'var_method' => '_method', diff --git a/helper.php b/helper.php index ee301b07..e1443931 100644 --- a/helper.php +++ b/helper.php @@ -146,7 +146,7 @@ function widget($name, $data = []) * @param string $layer 业务层名称 * @return \think\Model */ -function model($name = '', $layer = MODEL_LAYER) +function model($name = '', $layer = 'model') { return Loader::model($name, $layer); } @@ -168,7 +168,7 @@ function db($name = '', $config = []) * @param string $layer 控制层名称 * @return \think\Controller */ -function controller($name, $layer = CONTROLLER_LAYER) +function controller($name, $layer = 'controller') { return Loader::controller($name, $layer); } @@ -180,7 +180,7 @@ function controller($name, $layer = CONTROLLER_LAYER) * @param string $layer 要调用的控制层名称 * @return mixed */ -function action($url, $vars = [], $layer = CONTROLLER_LAYER) +function action($url, $vars = [], $layer = 'controller') { return Loader::action($url, $vars, $layer); } diff --git a/library/think/App.php b/library/think/App.php index 9b0f613a..5e8dc4b7 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -246,7 +246,7 @@ class App // 模块初始化 if (MODULE_NAME && $available) { define('MODULE_PATH', APP_PATH . MODULE_NAME . DS); - define('VIEW_PATH', MODULE_PATH . VIEW_LAYER . DS); + define('VIEW_PATH', MODULE_PATH . 'view' . DS); // 初始化模块 $config = self::initModule(MODULE_NAME, $config); } else { @@ -256,7 +256,7 @@ class App // 单一模块部署 define('MODULE_NAME', ''); define('MODULE_PATH', APP_PATH); - define('VIEW_PATH', MODULE_PATH . VIEW_LAYER . DS); + define('VIEW_PATH', MODULE_PATH . 'view' . DS); } // 获取控制器名 @@ -272,7 +272,7 @@ class App // 安全检测 throw new Exception('illegal controller name:' . CONTROLLER_NAME, 10000); } - $instance = Loader::controller(CONTROLLER_NAME, '', $config['use_controller_suffix'], $config['empty_controller']); + $instance = Loader::controller(CONTROLLER_NAME, $config['url_controller_layer'], $config['use_controller_suffix'], $config['empty_controller']); // 获取当前操作名 $action = ACTION_NAME . $config['action_suffix']; diff --git a/library/think/Build.php b/library/think/Build.php index ada56595..0f23a113 100644 --- a/library/think/Build.php +++ b/library/think/Build.php @@ -132,13 +132,13 @@ class Build $namespace = APP_NAMESPACE . '\\' . ($module ? $module . '\\' : '') . $path; $class = $val . (CLASS_APPEND_SUFFIX ? ucfirst($path) : ''); switch ($path) { - case CONTROLLER_LAYER: // 控制器 + case 'controller': // 控制器 $content = "parseValue($data[0]) . ' AND ' . $this->parseValue($data[1]); } elseif (in_array($exp, ['NOT EXISTS', 'EXISTS'])) { // EXISTS 查询 - $whereStr .= $exp . ' ' . $this->parseClosure($value); + if ($value instanceof \Closure) { + $whereStr .= $exp . ' ' . $this->parseClosure($value); + } else { + $whereStr .= $exp . ' (' . $value . ')'; + } } return $whereStr; } diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index abd980f3..9019d7cc 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -96,7 +96,7 @@ class Php if (strpos($template, '@')) { list($module, $template) = explode('@', $template); - $path = APP_PATH . $module . DS . VIEW_LAYER . DS; + $path = APP_PATH . $module . DS . 'view' . DS; } else { $path = $this->config['view_path']; } diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 167bd36f..c70d8d52 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -103,7 +103,7 @@ class Think if (strpos($template, '@')) { // 跨模块调用 list($module, $template) = explode('@', $template); - $path = APP_PATH . $module . DS . VIEW_LAYER . DS; + $path = APP_PATH . $module . DS . 'view' . DS; } else { // 当前视图目录 $path = $this->config['view_path']; diff --git a/tests/thinkphp/baseTest.php b/tests/thinkphp/baseTest.php index 85f63a2e..0e0f1e05 100644 --- a/tests/thinkphp/baseTest.php +++ b/tests/thinkphp/baseTest.php @@ -35,9 +35,6 @@ class baseTest extends \PHPUnit_Framework_TestCase $this->assertNotEmpty(TEMP_PATH); $this->assertNotEmpty(VENDOR_PATH); $this->assertNotEmpty(EXT); - $this->assertNotEmpty(MODEL_LAYER); - $this->assertNotEmpty(VIEW_LAYER); - $this->assertNotEmpty(CONTROLLER_LAYER); $this->assertTrue(is_bool(APP_DEBUG)); $this->assertNotEmpty(ENV_PREFIX); $this->assertTrue(is_bool(IS_API)); From ac0cb9be421d403c05ec169eaebfa837415a4a40 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 18:34:36 +0800 Subject: [PATCH 250/670] =?UTF-8?q?=E5=8E=BB=E9=99=A4=20MODULE=5FNAME=20CO?= =?UTF-8?q?NTROLLER=5FNAME=20ACTION=5FNAME=20=E5=B8=B8=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 7 ++- library/think/App.php | 49 ++++++++++--------- library/think/Console.php | 22 ++++----- library/think/Controller.php | 4 +- library/think/Loader.php | 9 ++-- library/think/Request.php | 48 ++++++++++++++++++ library/think/Url.php | 10 ++-- library/think/controller/Rest.php | 2 +- library/think/view/driver/Php.php | 9 ++-- library/think/view/driver/Think.php | 9 ++-- .../thinkphp/library/think/controllerTest.php | 13 ++--- 11 files changed, 123 insertions(+), 59 deletions(-) diff --git a/base.php b/base.php index f418428d..e7766050 100644 --- a/base.php +++ b/base.php @@ -19,17 +19,16 @@ define('LIB_PATH', THINK_PATH . 'library' . DS); define('MODE_PATH', THINK_PATH . 'mode' . 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(APP_PATH) . DS); defined('EXTEND_PATH') or define('EXTEND_PATH', ROOT_PATH . 'extend' . DS); -defined('APP_NAMESPACE') or define('APP_NAMESPACE', 'app'); -defined('COMMON_MODULE') or define('COMMON_MODULE', 'common'); +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('VENDOR_PATH') or define('VENDOR_PATH', ROOT_PATH . 'vendor' . DS); +defined('APP_NAMESPACE') or define('APP_NAMESPACE', 'app'); +defined('COMMON_MODULE') or define('COMMON_MODULE', 'common'); defined('CONF_PATH') or define('CONF_PATH', APP_PATH); // 配置文件目录 defined('CONF_EXT') or define('CONF_EXT', EXT); // 配置文件后缀 defined('APP_MULTI_MODULE') or define('APP_MULTI_MODULE', true); // 是否多模块 diff --git a/library/think/App.php b/library/think/App.php index 5e8dc4b7..7e8f8d14 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -228,63 +228,68 @@ class App } if (APP_MULTI_MODULE) { // 多模块部署 - $module = strtolower($result[0] ?: $config['default_module']); - // 获取模块名称 - define('MODULE_NAME', strip_tags($module)); + $module = strip_tags(strtolower($result[0] ?: $config['default_module'])); $bind = Route::bind('module'); $available = false; if ($bind) { // 绑定模块 list($bindModule) = explode('/', $bind); - if (MODULE_NAME == $bindModule) { + if ($module == $bindModule) { $available = true; } - } elseif (!in_array(MODULE_NAME, $config['deny_module_list']) && is_dir(APP_PATH . MODULE_NAME)) { + } elseif (!in_array($module, $config['deny_module_list']) && is_dir(APP_PATH . $module)) { $available = true; } // 模块初始化 - if (MODULE_NAME && $available) { - define('MODULE_PATH', APP_PATH . MODULE_NAME . DS); + if ($module && $available) { + define('MODULE_PATH', APP_PATH . $module . DS); define('VIEW_PATH', MODULE_PATH . 'view' . DS); // 初始化模块 - $config = self::initModule(MODULE_NAME, $config); + $config = self::initModule($module, $config); } else { - throw new HttpException(404, 'module [ ' . MODULE_NAME . ' ] not exists '); + throw new HttpException(404, 'module [ ' . $module . ' ] not exists '); } } else { // 单一模块部署 - define('MODULE_NAME', ''); + $module = ''; define('MODULE_PATH', APP_PATH); define('VIEW_PATH', MODULE_PATH . 'view' . DS); } // 获取控制器名 - $controllerName = strip_tags($result[1] ?: $config['default_controller']); - defined('CONTROLLER_NAME') or define('CONTROLLER_NAME', $config['url_controller_convert'] ? strtolower($controllerName) : $controllerName); + $controller = strip_tags($result[1] ?: $config['default_controller']); + $controller = $config['url_controller_convert'] ? strtolower($controller) : $controller; // 获取操作名 $actionName = strip_tags($result[2] ?: $config['default_action']); - defined('ACTION_NAME') or define('ACTION_NAME', $config['url_action_convert'] ? strtolower($actionName) : $actionName); + $actionName = $config['url_action_convert'] ? strtolower($actionName) : $actionName; // 执行操作 - if (!preg_match('/^[A-Za-z](\/|\.|\w)*$/', CONTROLLER_NAME)) { + if (!preg_match('/^[A-Za-z](\/|\.|\w)*$/', $controller)) { // 安全检测 - throw new Exception('illegal controller name:' . CONTROLLER_NAME, 10000); + throw new Exception('illegal controller name:' . $controller, 10000); } - $instance = Loader::controller(CONTROLLER_NAME, $config['url_controller_layer'], $config['use_controller_suffix'], $config['empty_controller']); - // 获取当前操作名 - $action = ACTION_NAME . $config['action_suffix']; + + // 设置当前请求的模块、控制器、操作 + $request = Request::instance(); + $request->module($module); + $request->controller($controller); + $request->action($actionName); try { - // 操作方法开始监听 - $call = [$instance, $action]; - Hook::listen('action_begin', $call); + // 获取当前操作名 + $action = $actionName . $config['action_suffix']; if (!preg_match('/^[A-Za-z](\w)*$/', $action)) { // 非法操作 - throw new \ReflectionException('illegal action name :' . ACTION_NAME); + throw new \ReflectionException('illegal action name :' . $actionName); } + $instance = Loader::controller($controller, $config['url_controller_layer'], $config['use_controller_suffix'], $config['empty_controller']); + // 执行操作方法 + $call = [$instance, $action]; + Hook::listen('action_begin', $call); + $data = self::invokeMethod($call); } catch (\ReflectionException $e) { // 操作不存在 diff --git a/library/think/Console.php b/library/think/Console.php index 6e5ad424..c4d96f59 100644 --- a/library/think/Console.php +++ b/library/think/Console.php @@ -38,7 +38,7 @@ class Console private $runningCommand; private $catchExceptions = true; - private $autoExit = true; + private $autoExit = true; private $definition; private $helperSet; private $terminalDimensions; @@ -49,7 +49,7 @@ class Console "think\\console\\command\\Lists", "think\\console\\command\\Build", "think\\console\\command\\make\\Controller", - "think\\console\\command\\make\\Model" + "think\\console\\command\\make\\Model", ]; public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN') @@ -90,7 +90,7 @@ class Console $exitCode = $e->getCode(); if (is_numeric($exitCode)) { - $exitCode = (int)$exitCode; + $exitCode = (int) $exitCode; if (0 === $exitCode) { $exitCode = 1; } @@ -201,7 +201,7 @@ class Console */ public function setCatchExceptions($boolean) { - $this->catchExceptions = (bool)$boolean; + $this->catchExceptions = (bool) $boolean; } /** @@ -211,7 +211,7 @@ class Console */ public function setAutoExit($boolean) { - $this->autoExit = (bool)$boolean; + $this->autoExit = (bool) $boolean; } /** @@ -379,7 +379,7 @@ class Console $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]) . '[^:]*'; }, $namespace); - $namespaces = preg_grep('{^' . $expr . '}', $allNamespaces); + $namespaces = preg_grep('{^' . $expr . '}', $allNamespaces); if (empty($namespaces)) { $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace); @@ -417,7 +417,7 @@ class Console $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]) . '[^:]*'; }, $name); - $commands = preg_grep('{^' . $expr . '}', $allCommands); + $commands = preg_grep('{^' . $expr . '}', $allCommands); if (empty($commands) || count(preg_grep('{^' . $expr . '$}', $commands)) < 1) { if (false !== $pos = strrpos($name, ':')) { @@ -606,19 +606,19 @@ class Console if ('\\' === DS) { if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) { - return [(int)$matches[1], (int)$matches[2]]; + return [(int) $matches[1], (int) $matches[2]]; } if (preg_match('/^(\d+)x(\d+)$/', $this->getConsoleMode(), $matches)) { - return [(int)$matches[1], (int)$matches[2]]; + return [(int) $matches[1], (int) $matches[2]]; } } if ($sttyString = $this->getSttyColumns()) { if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) { - return [(int)$matches[2], (int)$matches[1]]; + return [(int) $matches[2], (int) $matches[1]]; } if (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) { - return [(int)$matches[2], (int)$matches[1]]; + return [(int) $matches[2], (int) $matches[1]]; } } diff --git a/library/think/Controller.php b/library/think/Controller.php index c7086c64..5920d7c0 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -69,14 +69,14 @@ class Controller if (is_string($options['only'])) { $options['only'] = explode(',', $options['only']); } - if (!in_array(ACTION_NAME, $options['only'])) { + if (!in_array($this->request->action(), $options['only'])) { return; } } elseif (isset($options['except'])) { if (is_string($options['except'])) { $options['except'] = explode(',', $options['except']); } - if (in_array(ACTION_NAME, $options['except'])) { + if (in_array($this->request->action(), $options['except'])) { return; } } diff --git a/library/think/Loader.php b/library/think/Loader.php index c41f8eee..8353dfae 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -12,6 +12,7 @@ namespace think; use think\exception\HttpException; +use think\Request; class Loader { @@ -276,7 +277,7 @@ class Loader if (strpos($name, '/')) { list($module, $name) = explode('/', $name, 2); } else { - $module = APP_MULTI_MODULE ? MODULE_NAME : ''; + $module = APP_MULTI_MODULE ? Request::instance()->module() : ''; } $class = self::parseClass($module, $layer, $name, $appendSuffix); if (class_exists($class)) { @@ -311,7 +312,7 @@ class Loader if (strpos($name, '/')) { list($module, $name) = explode('/', $name); } else { - $module = APP_MULTI_MODULE ? MODULE_NAME : ''; + $module = APP_MULTI_MODULE ? Request::instance()->module() : ''; } $class = self::parseClass($module, $layer, $name, $appendSuffix); if (class_exists($class)) { @@ -346,7 +347,7 @@ class Loader if (strpos($name, '/')) { list($module, $name) = explode('/', $name); } else { - $module = APP_MULTI_MODULE ? MODULE_NAME : ''; + $module = APP_MULTI_MODULE ? Request::instance()->module() : ''; } $class = self::parseClass($module, $layer, $name, $appendSuffix); if (class_exists($class)) { @@ -385,7 +386,7 @@ class Loader { $info = pathinfo($url); $action = $info['basename']; - $module = '.' != $info['dirname'] ? $info['dirname'] : CONTROLLER_NAME; + $module = '.' != $info['dirname'] ? $info['dirname'] : Request::instance()->controller(); $class = self::controller($module, $layer, $appendSuffix); if ($class) { if (is_scalar($vars)) { diff --git a/library/think/Request.php b/library/think/Request.php index f5810ac0..601edf47 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -67,6 +67,10 @@ class Request */ protected $dispatch = []; + protected $module; + protected $controller; + protected $action; + /** * @var array 请求参数 */ @@ -908,4 +912,48 @@ class Request return $this->dispatch; } + /** + * 设置或者获取当前的模块名 + * @access public + * @param string $module 模块名 + * @return string + */ + public function module($module = null) + { + if (!is_null($module)) { + $this->module = $module; + } else { + return $this->module ?: ''; + } + } + + /** + * 设置或者获取当前的控制器名 + * @access public + * @param string $controller 控制器名 + * @return string + */ + public function controller($controller = null) + { + if (!is_null($controller)) { + $this->controller = $controller; + } else { + return $this->controller ?: ''; + } + } + + /** + * 设置或者获取当前的操作名 + * @access public + * @param string $action 操作名 + * @return string + */ + public function action($action = null) + { + if (!is_null($action)) { + $this->action = $action; + } else { + return $this->action ?: ''; + } + } } diff --git a/library/think/Url.php b/library/think/Url.php index de222ea5..998a1f64 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -13,6 +13,7 @@ namespace think; use think\Cache; use think\Config; +use think\Request; use think\Route; class Url @@ -118,6 +119,7 @@ class Url // 直接解析URL地址 protected static function parseUrl($url) { + $request = Request::instance(); if (0 === strpos($url, '/')) { // 直接作为路由地址解析 $url = substr($url, 1); @@ -129,14 +131,16 @@ class Url $url = substr($url, 1); } else { // 解析到 模块/控制器/操作 - $module = MODULE_NAME ? MODULE_NAME . '/' : ''; + $module = $request->module(); + $module = $module ? $module . '/' : ''; + $controller = $request->controller(); if ('' == $url) { // 空字符串输出当前的 模块/控制器/操作 - $url = $module . CONTROLLER_NAME . '/' . ACTION_NAME; + $url = $module . $controller . '/' . $request->action(); } else { $path = explode('/', $url); $action = array_pop($path); - $controller = empty($path) ? CONTROLLER_NAME : (Config::get('url_controller_convert') ? Loader::parseName(array_pop($path)) : array_pop($path)); + $controller = empty($path) ? $controller : (Config::get('url_controller_convert') ? Loader::parseName(array_pop($path)) : array_pop($path)); $module = empty($path) ? $module : array_pop($path) . '/'; $url = $module . $controller . '/' . $action; } diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index ebf53be8..c31e9287 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -76,7 +76,7 @@ abstract class Rest return $this->$fun(); } else { // 抛出异常 - throw new \Exception('error action :' . ACTION_NAME); + throw new \Exception('error action :' . $method); } } diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index 9019d7cc..ac101ea5 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -13,6 +13,7 @@ namespace think\view\driver; use think\Exception; use think\Log; +use think\Request; class Php { @@ -102,14 +103,16 @@ class Php } // 分析模板文件规则 - if (defined('CONTROLLER_NAME') && 0 !== strpos($template, '/')) { + $request = Request::instance(); + $controller = $request->controller(); + if ($controller && 0 !== strpos($template, '/')) { $depr = $this->config['view_depr']; $template = str_replace(['/', ':'], $depr, $template); if ('' == $template) { // 如果模板文件名为空 按照默认规则定位 - $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . ACTION_NAME; + $template = str_replace('.', DS, $controller) . $depr . $request->action(); } elseif (false === strpos($template, $depr)) { - $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . $template; + $template = str_replace('.', DS, $controller) . $depr . $template; } } return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.'); diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index c70d8d52..ddc3e7b7 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -13,6 +13,7 @@ namespace think\view\driver; use think\Exception; use think\Log; +use think\Request; use think\Template; class Think @@ -110,14 +111,16 @@ class Think } // 分析模板文件规则 - if (defined('CONTROLLER_NAME') && 0 !== strpos($template, '/')) { + $request = Request::instance(); + $controller = $request->controller(); + if ($controller && 0 !== strpos($template, '/')) { $depr = $this->config['view_depr']; $template = str_replace(['/', ':'], $depr, $template); if ('' == $template) { // 如果模板文件名为空 按照默认规则定位 - $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . ACTION_NAME; + $template = str_replace('.', DS, $controller) . $depr . $request->action(); } elseif (false === strpos($template, $depr)) { - $template = str_replace('.', DS, CONTROLLER_NAME) . $depr . $template; + $template = str_replace('.', DS, $controller) . $depr . $template; } } return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.'); diff --git a/tests/thinkphp/library/think/controllerTest.php b/tests/thinkphp/library/think/controllerTest.php index 5a4a8397..dbf60d8e 100644 --- a/tests/thinkphp/library/think/controllerTest.php +++ b/tests/thinkphp/library/think/controllerTest.php @@ -18,6 +18,7 @@ namespace tests\thinkphp\library\think; use ReflectionClass; use think\Controller; +use think\Request; use think\View; require_once CORE_PATH . '../../helper.php'; @@ -93,16 +94,16 @@ class controllerTest extends \PHPUnit_Framework_TestCase { public function testInitialize() { - $foo = new Foo; + $foo = new Foo(Request::instance()); $this->assertEquals('abcd', $foo->test); } public function testBeforeAction() { - $obj = new Bar; + $obj = new Bar(Request::instance()); $this->assertEquals(7, $obj->test); - $obj = new Baz; + $obj = new Baz(Request::instance()); $this->assertEquals(19, $obj->test); } @@ -118,7 +119,7 @@ class controllerTest extends \PHPUnit_Framework_TestCase public function testFetch() { - $controller = new Foo; + $controller = new Foo(Request::instance()); $view = $this->getView($controller); $template = dirname(__FILE__) . '/display.html'; $viewFetch = $view->fetch($template, ['name' => 'ThinkPHP']); @@ -138,7 +139,7 @@ class controllerTest extends \PHPUnit_Framework_TestCase public function testAssign() { - $controller = new Foo; + $controller = new Foo(Request::instance()); $view = $this->getView($controller); $controller->assign('abcd', 'dcba'); $controller->assign(['key1' => 'value1', 'key2' => 'value2']); @@ -148,7 +149,7 @@ class controllerTest extends \PHPUnit_Framework_TestCase public function testValidate() { - $controller = new Foo; + $controller = new Foo(Request::instance()); $data = [ 'username' => 'username', 'nickname' => 'nickname', From 3a154657e34c26aa61239418ac80bb0f7517fb4d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 18:47:37 +0800 Subject: [PATCH 251/670] =?UTF-8?q?=E5=8E=BB=E6=8E=89=20VIEW=5FPATH=20?= =?UTF-8?q?=E5=B8=B8=E9=87=8F=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 6 ++---- library/think/view/driver/Php.php | 4 ++-- library/think/view/driver/Think.php | 4 ++-- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 7e8f8d14..082e8737 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -243,8 +243,6 @@ class App // 模块初始化 if ($module && $available) { - define('MODULE_PATH', APP_PATH . $module . DS); - define('VIEW_PATH', MODULE_PATH . 'view' . DS); // 初始化模块 $config = self::initModule($module, $config); } else { @@ -253,9 +251,9 @@ class App } else { // 单一模块部署 $module = ''; - define('MODULE_PATH', APP_PATH); - define('VIEW_PATH', MODULE_PATH . 'view' . DS); } + // 当前模块路径 + define('MODULE_PATH', APP_PATH . ($module ? $module . DS : '')); // 获取控制器名 $controller = strip_tags($result[1] ?: $config['default_controller']); diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index ac101ea5..5eda4faf 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -91,8 +91,8 @@ class Php */ private function parseTemplate($template) { - if (empty($this->config['view_path']) && defined('VIEW_PATH')) { - $this->config['view_path'] = VIEW_PATH; + if (empty($this->config['view_path']) && defined('MODULE_PATH')) { + $this->config['view_path'] = MODULE_PATH . 'view' . DS; } if (strpos($template, '@')) { diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index ddc3e7b7..10ef587d 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -35,8 +35,8 @@ class Think public function __construct($config = []) { $this->config = array_merge($this->config, $config); - if (empty($this->config['view_path']) && defined('VIEW_PATH')) { - $this->config['view_path'] = VIEW_PATH; + if (empty($this->config['view_path']) && defined('MODULE_PATH')) { + $this->config['view_path'] = MODULE_PATH . 'view' . DS; } $this->template = new Template($this->config); } From dd906ccaf2530e05f6310051e8bced7c968c528b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 21:13:52 +0800 Subject: [PATCH 252/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0module=5Finit?= =?UTF-8?q?=E6=A0=87=E7=AD=BE=E4=BD=8D=E7=94=A8=E4=BA=8E=E6=89=A9=E5=B1=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/library/think/App.php b/library/think/App.php index 082e8737..2efc4f68 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -275,6 +275,9 @@ class App $request->controller($controller); $request->action($actionName); + // 监听module_init + Hook::listen('module_init', $request); + try { // 获取当前操作名 $action = $actionName . $config['action_suffix']; From 357d5c0e008c6eb31472641f395397780a9fce20 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 21:19:07 +0800 Subject: [PATCH 253/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 4 +--- library/think/Request.php | 13 ++++++++----- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 2efc4f68..e4ffba12 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -271,9 +271,7 @@ class App // 设置当前请求的模块、控制器、操作 $request = Request::instance(); - $request->module($module); - $request->controller($controller); - $request->action($actionName); + $request->module($module)->controller($controller)->action($actionName); // 监听module_init Hook::listen('module_init', $request); diff --git a/library/think/Request.php b/library/think/Request.php index 601edf47..8d9c95fe 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -203,7 +203,7 @@ class Request { if (!empty($domain)) { $this->domain = $domain; - return; + return $this; } elseif (!$this->domain) { $this->domain = $this->scheme() . '://' . $this->host(); } @@ -220,7 +220,7 @@ class Request { if (is_string($url) && !empty($url)) { $this->url = $url; - return; + return $this; } elseif (!$this->url) { if (IS_CLI) { $this->url = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : ''; @@ -247,7 +247,7 @@ class Request { if (is_string($url) && !empty($url)) { $this->baseUrl = $url; - return; + return $this; } elseif (!$this->baseUrl) { $str = $this->url(); $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str; @@ -265,7 +265,7 @@ class Request { if (is_string($file) && !empty($file)) { $this->baseFile = $file; - return; + return $this; } elseif (!$this->baseFile) { $url = ''; if (!IS_CLI) { @@ -297,7 +297,7 @@ class Request { if (is_string($url) && !empty($url)) { $this->root = $url; - return; + return $this; } elseif (!$this->root) { $file = $this->baseFile(); if ($file && 0 !== strpos($this->url(), $file)) { @@ -922,6 +922,7 @@ class Request { if (!is_null($module)) { $this->module = $module; + return $this; } else { return $this->module ?: ''; } @@ -937,6 +938,7 @@ class Request { if (!is_null($controller)) { $this->controller = $controller; + return $this; } else { return $this->controller ?: ''; } @@ -952,6 +954,7 @@ class Request { if (!is_null($action)) { $this->action = $action; + return $this; } else { return $this->action ?: ''; } From 8deabb737af7ab34b08b9a2e277be0f1c701935d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 1 Jun 2016 21:36:51 +0800 Subject: [PATCH 254/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BApp=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 49 ++++++++++++++++++++++--------------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index e4ffba12..49a304a8 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -69,31 +69,32 @@ class App // 设置系统时区 date_default_timezone_set($config['default_timezone']); - // 监听app_init - Hook::listen('app_init'); - - // 开启多语言机制 - if ($config['lang_switch_on']) { - // 获取当前语言 - defined('LANG_SET') or define('LANG_SET', Lang::range()); - // 加载系统语言包 - Lang::load(THINK_PATH . 'lang' . DS . LANG_SET . EXT); - if (!APP_MULTI_MODULE) { - Lang::load(APP_PATH . 'lang' . DS . LANG_SET . EXT); - } - } - - // 获取当前请求的调度信息 - $dispatch = $request->dispatch(); - if (empty($dispatch)) { - // 未指定调度类型 则进行URL路由检测 - $dispatch = self::route($request, $config); - } - // 记录路由信息 - APP_DEBUG && Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info'); - // 监听app_begin - Hook::listen('app_begin', $dispatch); try { + // 监听app_init + Hook::listen('app_init'); + + // 开启多语言机制 + if ($config['lang_switch_on']) { + // 获取当前语言 + defined('LANG_SET') or define('LANG_SET', Lang::range()); + // 加载系统语言包 + Lang::load(THINK_PATH . 'lang' . DS . LANG_SET . EXT); + if (!APP_MULTI_MODULE) { + Lang::load(APP_PATH . 'lang' . DS . LANG_SET . EXT); + } + } + + // 获取当前请求的调度信息 + $dispatch = $request->dispatch(); + if (empty($dispatch)) { + // 未指定调度类型 则进行URL路由检测 + $dispatch = self::route($request, $config); + } + // 记录路由信息 + APP_DEBUG && Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info'); + // 监听app_begin + Hook::listen('app_begin', $dispatch); + switch ($dispatch['type']) { case 'redirect': // 执行重定向跳转 From bf7e974faec1050f208752d5be2872c2c00843ff Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 2 Jun 2016 10:51:10 +0800 Subject: [PATCH 255/670] =?UTF-8?q?=E5=8E=BB=E6=8E=89=20COMMON=5FMODULE=20?= =?UTF-8?q?=E5=B8=B8=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 1 - convention.php | 2 +- library/think/App.php | 10 +++++----- library/think/Loader.php | 16 +++++++++------- tests/thinkphp/baseTest.php | 1 - 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/base.php b/base.php index e7766050..333f81b5 100644 --- a/base.php +++ b/base.php @@ -28,7 +28,6 @@ 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('APP_NAMESPACE') or define('APP_NAMESPACE', 'app'); -defined('COMMON_MODULE') or define('COMMON_MODULE', 'common'); defined('CONF_PATH') or define('CONF_PATH', APP_PATH); // 配置文件目录 defined('CONF_EXT') or define('CONF_EXT', EXT); // 配置文件后缀 defined('APP_MULTI_MODULE') or define('APP_MULTI_MODULE', true); // 是否多模块 diff --git a/convention.php b/convention.php index 1cb33eb6..cfed3f30 100644 --- a/convention.php +++ b/convention.php @@ -39,7 +39,7 @@ return [ // 默认模块名 'default_module' => 'index', // 禁止访问模块 - 'deny_module_list' => [COMMON_MODULE], + 'deny_module_list' => ['common'], // 默认控制器名 'default_controller' => 'Index', // 默认操作名 diff --git a/library/think/App.php b/library/think/App.php index 49a304a8..fe07ebbe 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -48,8 +48,8 @@ class App define('IS_AJAX', $request->isAjax()); define('__EXT__', $request->ext()); - // 初始化应用(公共模块) - $config = self::initModule(COMMON_MODULE, Config::get()); + // 初始化应用 + $config = self::init('', Config::get()); // 注册根命名空间 if (!empty($config['root_namespace'])) { @@ -305,16 +305,16 @@ class App } /** - * 初始化模块 + * 初始化应用或模块 * @access public * @param string $module 模块名 * @param array $config 配置参数 * @return void */ - private static function initModule($module, $config) + private static function init($module, $config) { // 定位模块目录 - $module = (COMMON_MODULE == $module || !APP_MULTI_MODULE) ? '' : $module . DS; + $module = ($module && APP_MULTI_MODULE) ? $module . DS : ''; // 加载初始化文件 if (is_file(APP_PATH . $module . 'init' . EXT)) { diff --git a/library/think/Loader.php b/library/think/Loader.php index 8353dfae..e54b7ed3 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -266,9 +266,10 @@ class Loader * @param string $name Model名称 * @param string $layer 业务层名称 * @param bool $appendSuffix 是否添加类名后缀 + * @param string $common 公共模块名 * @return Object */ - public static function model($name = '', $layer = 'model', $appendSuffix = false) + public static function model($name = '', $layer = 'model', $appendSuffix = false, $common = 'common') { static $_model = []; if (isset($_model[$name . $layer])) { @@ -277,13 +278,13 @@ class Loader if (strpos($name, '/')) { list($module, $name) = explode('/', $name, 2); } else { - $module = APP_MULTI_MODULE ? Request::instance()->module() : ''; + $module = Request::instance()->module(); } $class = self::parseClass($module, $layer, $name, $appendSuffix); if (class_exists($class)) { $model = new $class(); } else { - $class = str_replace('\\' . $module . '\\', '\\' . COMMON_MODULE . '\\', $class); + $class = str_replace('\\' . $module . '\\', '\\' . $common . '\\', $class); if (class_exists($class)) { $model = new $class(); } else { @@ -312,7 +313,7 @@ class Loader if (strpos($name, '/')) { list($module, $name) = explode('/', $name); } else { - $module = APP_MULTI_MODULE ? Request::instance()->module() : ''; + $module = Request::instance()->module(); } $class = self::parseClass($module, $layer, $name, $appendSuffix); if (class_exists($class)) { @@ -331,9 +332,10 @@ class Loader * @param string $name 资源地址 * @param string $layer 验证层名称 * @param bool $appendSuffix 是否添加类名后缀 + * @param string $common 公共模块名 * @return Object|false */ - public static function validate($name = '', $layer = 'validate', $appendSuffix = false) + public static function validate($name = '', $layer = 'validate', $appendSuffix = false, $common = 'common') { $name = $name ?: Config::get('default_validate'); if (empty($name)) { @@ -347,13 +349,13 @@ class Loader if (strpos($name, '/')) { list($module, $name) = explode('/', $name); } else { - $module = APP_MULTI_MODULE ? Request::instance()->module() : ''; + $module = Request::instance()->module(); } $class = self::parseClass($module, $layer, $name, $appendSuffix); if (class_exists($class)) { $validate = new $class; } else { - $class = str_replace('\\' . $module . '\\', '\\' . COMMON_MODULE . '\\', $class); + $class = str_replace('\\' . $module . '\\', '\\' . $common . '\\', $class); if (class_exists($class)) { $validate = new $class; } else { diff --git a/tests/thinkphp/baseTest.php b/tests/thinkphp/baseTest.php index 0e0f1e05..43ea2a62 100644 --- a/tests/thinkphp/baseTest.php +++ b/tests/thinkphp/baseTest.php @@ -28,7 +28,6 @@ class baseTest extends \PHPUnit_Framework_TestCase $this->assertNotEmpty(TRAIT_PATH); $this->assertNotEmpty(APP_PATH); $this->assertNotEmpty(APP_NAMESPACE); - $this->assertNotEmpty(COMMON_MODULE); $this->assertNotEmpty(RUNTIME_PATH); $this->assertNotEmpty(LOG_PATH); $this->assertNotEmpty(CACHE_PATH); From ee9d5df56f322ae6b9be122079cd297da8138cbb Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 2 Jun 2016 11:10:19 +0800 Subject: [PATCH 256/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3App=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/App.php b/library/think/App.php index fe07ebbe..37e664b9 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -245,7 +245,7 @@ class App // 模块初始化 if ($module && $available) { // 初始化模块 - $config = self::initModule($module, $config); + $config = self::init($module, $config); } else { throw new HttpException(404, 'module [ ' . $module . ' ] not exists '); } From 8099a001e2657f6fee6eb322111195afe38bf50f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 2 Jun 2016 12:13:00 +0800 Subject: [PATCH 257/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BResponse=E7=B1=BB?= =?UTF-8?q?=E7=9A=84send=E6=96=B9=E6=B3=95=20=E5=8E=BB=E9=99=A4=20REQUEST?= =?UTF-8?q?=5FMETHOD=20IS=5FGET=20IS=5FPOST=20IS=5FPUT=20IS=5FDELETE=20IS?= =?UTF-8?q?=5FAJAX=20=5F=5FEXT=5F=5F=20=E5=B8=B8=E9=87=8F=20=E7=94=B1?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E8=87=AA=E5=B7=B1=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 16 +++++----------- library/think/Response.php | 26 +++++++++++++++++++------- library/think/Route.php | 19 +++++++++++++------ library/think/Validate.php | 4 +++- library/think/controller/Rest.php | 11 +++++++---- library/think/log/driver/Trace.php | 4 +++- library/traits/controller/Jump.php | 15 +++++++++++++-- 7 files changed, 63 insertions(+), 32 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 37e664b9..9c417d6b 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -32,22 +32,14 @@ class App /** * 执行应用程序 * @access public - * @param null|\think\Request $request Request对象 + * @param Request $request Request对象 * @return mixed * @throws Exception */ - public static function run($request = null) + public static function run(Request $request = null) { is_null($request) && $request = Request::instance(); - define('REQUEST_METHOD', $request->method()); - define('IS_GET', REQUEST_METHOD == 'GET' ? true : false); - define('IS_POST', REQUEST_METHOD == 'POST' ? true : false); - define('IS_PUT', REQUEST_METHOD == 'PUT' ? true : false); - define('IS_DELETE', REQUEST_METHOD == 'DELETE' ? true : false); - define('IS_AJAX', $request->isAjax()); - define('__EXT__', $request->ext()); - // 初始化应用 $config = self::init('', Config::get()); @@ -133,7 +125,9 @@ class App if ($data instanceof Response) { return $data->send(); } elseif (!is_null($data)) { - $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); + // 默认自动识别响应输出类型 + $isAjax = $request->isAjax(); + $type = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type'); return Response::create($data, $type)->send(); } } diff --git a/library/think/Response.php b/library/think/Response.php index 31052b84..5e817368 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -11,6 +11,9 @@ namespace think; +use think\Hook; +use think\Request; + class Response { // 输出类型的实例化对象 @@ -48,16 +51,20 @@ class Response public function __construct($data = [], $type = '', $options = []) { $this->data = $data; - $this->type = strtolower($type ?: (IS_AJAX ? 'json' : 'html')); + if (empty($type)) { + $isAjax = Request::instance()->isAjax(); + $type = $isAjax ? 'json' : 'html'; + } + $this->type = strtolower($type); if (isset($this->contentTypes[$this->type])) { $this->contentType($this->contentTypes[$this->type]); } - if(!empty($options)){ + if (!empty($options)) { $this->options = array_merge($this->options, $options); } // 方便获取某个类型的实例 - self::$instance[$this->type] = $this; + self::$instance[$this->type] = $this; } /** @@ -70,7 +77,12 @@ class Response */ public static function create($data = [], $type = '', $options = []) { - $type = strtolower($type ?: (IS_AJAX ? 'json' : 'html')); + if (empty($type)) { + $isAjax = Request::instance()->isAjax(); + $type = $isAjax ? 'json' : 'html'; + } + $type = strtolower($type); + if (!isset(self::$instance[$type])) { $class = (isset($options['namespace']) ? $options['namespace'] : '\\think\\response\\') . ucfirst($type); if (class_exists($class)) { @@ -90,9 +102,9 @@ class Response * @return mixed * @throws Exception */ - public function send($data = []) + public function send($data = null) { - $data = $data ?: $this->data; + $data = !is_null($data) ?: $this->data; if (isset($this->contentType)) { $this->contentType($this->contentType); @@ -102,7 +114,7 @@ class Response $data = call_user_func_array($this->transform, [$data]); } - defined('RESPONSE_TYPE') or define('RESPONSE_TYPE',$this->type); + defined('RESPONSE_TYPE') or define('RESPONSE_TYPE', $this->type); // 处理输出数据 $data = $this->output($data); diff --git a/library/think/Route.php b/library/think/Route.php index 962d733b..1ddcc933 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -11,6 +11,12 @@ namespace think; +use think\Config; +use think\Hook; +use think\Log; +use think\Request; +use think\Response; + class Route { // 路由规则 @@ -600,7 +606,7 @@ class Route } // 获取当前请求类型的路由规则 - $rules = self::$rules[REQUEST_METHOD]; + $rules = self::$rules[$request->method()]; if (!empty(self::$rules['*'])) { // 合并任意请求的路由规则 @@ -747,8 +753,8 @@ class Route private static function checkOption($option, $url, $request) { // 请求类型检测 - if ((isset($option['method']) && false === stripos($option['method'], REQUEST_METHOD)) - || (isset($option['ext']) && false === stripos($option['ext'], __EXT__)) // 伪静态后缀检测 + if ((isset($option['method']) && false === stripos($option['method'], $request->method())) + || (isset($option['ext']) && false === stripos($option['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)) // 行为检测 @@ -915,12 +921,13 @@ class Route $action = array_pop($path); $controller = !empty($path) ? array_pop($path) : null; $module = APP_MULTI_MODULE && !empty($path) ? array_pop($path) : null; + $method = Request::instance()->method(); // REST 操作方法支持 if ('[rest]' == $action) { - $action = REQUEST_METHOD; - } elseif (Config::get('use_action_prefix') && !empty(self::$methodPrefix[REQUEST_METHOD])) { + $action = $method; + } elseif (Config::get('use_action_prefix') && !empty(self::$methodPrefix[$method])) { // 操作方法前缀支持 - $action = 0 !== strpos($action, self::$methodPrefix[REQUEST_METHOD]) ? self::$methodPrefix[REQUEST_METHOD] . $action : $action; + $action = 0 !== strpos($action, self::$methodPrefix[$method]) ? self::$methodPrefix[$method] . $action : $action; } } // 封装路由 diff --git a/library/think/Validate.php b/library/think/Validate.php index 70745ba3..2b732dd9 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -12,6 +12,7 @@ namespace think; use think\Input; +use think\Request; class Validate { @@ -684,7 +685,8 @@ class Validate */ protected function method($value, $rule) { - return REQUEST_METHOD == strtoupper($rule); + $method = Request::instance()->method(); + return $method == strtoupper($rule); } /** diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index c31e9287..4193e5e0 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -12,6 +12,7 @@ namespace think\controller; use think\Response; +use think\Request; abstract class Rest { @@ -36,17 +37,19 @@ abstract class Rest public function __construct() { // 资源类型检测 - if ('' == __EXT__) { + $request = Request::instance(); + $ext = $request->ext(); + if ('' == $ext) { // 自动检测资源类型 $this->_type = $this->getAcceptType(); - } elseif (!preg_match('/\(' . $this->restTypeList . '\)$/i', __EXT__)) { + } elseif (!preg_match('/\(' . $this->restTypeList . '\)$/i', $ext)) { // 资源类型非法 则用默认资源类型访问 $this->_type = $this->restDefaultType; } else { - $this->_type = __EXT__; + $this->_type = $ext; } // 请求方式检测 - $method = strtolower(REQUEST_METHOD); + $method = strtolower($request->method()); if (false === stripos($this->restMethodList, $method)) { // 请求方式非法 则用默认请求方法 $method = $this->restDefaultMethod; diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index 58f1f71d..dd640e6a 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -15,6 +15,7 @@ use think\Cache; use think\Config; use think\Db; use think\Debug; +use think\Request; /** * 页面Trace调试 @@ -41,10 +42,11 @@ class Trace */ public function save(array $log = []) { - if (IS_CLI || IS_AJAX || IS_API || (defined('RESPONSE_TYPE') && !in_array(RESPONSE_TYPE, ['html', 'view']))) { + if (IS_CLI || IS_API || Request::instance()->isAjax() || (defined('RESPONSE_TYPE') && !in_array(RESPONSE_TYPE, ['html', 'view']))) { // ajax cli api方式下不输出 return false; } + // 获取基本信息 $runtime = microtime(true) - START_TIME; $reqs = number_format(1 / number_format($runtime, 8), 2); diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index c0c6b1b0..45e2e2dd 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -16,6 +16,7 @@ namespace traits\controller; use think\Config; use think\exception\HttpResponseException; +use think\Request; use think\Response; use think\response\Redirect; use think\View as ViewTemplate; @@ -46,7 +47,7 @@ trait Jump 'wait' => $wait, ]; - $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); + $type = $this->getResponseType(); if ('html' == strtolower($type)) { $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str')) ->fetch(Config::get('dispatch_success_tmpl'), $result); @@ -78,7 +79,7 @@ trait Jump 'wait' => $wait, ]; - $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); + $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); @@ -120,4 +121,14 @@ trait Jump throw new HttpResponseException($response); } + /** + * 获取当前的response 输出类型 + * @access public + * @return string + */ + public function getResponseType() + { + $isAjax = Request::instance()->isAjax(); + return $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type'); + } } From d65882e20c4a943ad9ad4a8e7ebb620983cab116 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 2 Jun 2016 12:21:36 +0800 Subject: [PATCH 258/670] =?UTF-8?q?=E5=8E=BB=E9=99=A4=20IS=5FCGI=20IS=5FMA?= =?UTF-8?q?C=20NOW=5FTIME=20=E5=B8=B8=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 7 ++----- library/think/Model.php | 8 ++++---- library/think/Response.php | 2 +- library/think/Validate.php | 2 +- library/think/db/Query.php | 4 ++-- tests/thinkphp/baseTest.php | 1 - tests/thinkphp/library/think/debugTest.php | 2 +- 7 files changed, 11 insertions(+), 15 deletions(-) diff --git a/base.php b/base.php index 333f81b5..64ed27a3 100644 --- a/base.php +++ b/base.php @@ -40,8 +40,5 @@ defined('CLASS_APPEND_SUFFIX') or define('CLASS_APPEND_SUFFIX', false); // 是 defined('APP_MODE') or define('APP_MODE', 'common'); // 应用模式 默认为普通模式 // 环境常量 -define('IS_CGI', strpos(PHP_SAPI, 'cgi') === 0 ? 1 : 0); -define('IS_CLI', PHP_SAPI == 'cli' ? 1 : 0); -define('IS_WIN', strstr(PHP_OS, 'WIN') ? 1 : 0); -define('IS_MAC', strstr(PHP_OS, 'Darwin') ? 1 : 0); -define('NOW_TIME', $_SERVER['REQUEST_TIME']); +define('IS_CLI', PHP_SAPI == 'cli' ? true : false); +define('IS_WIN', strstr(PHP_OS, 'WIN') ? true : false); diff --git a/library/think/Model.php b/library/think/Model.php index 47ff150c..e1f9a7a0 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -1017,16 +1017,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess switch ($type) { case 'timestamp': $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, NOW_TIME); + $value = date($format, $_SERVER['REQUEST_TIME']); break; case 'datetime': - $value = NOW_TIME; + $value = $_SERVER['REQUEST_TIME']; break; } } elseif (isset($this->fieldType[$name]) && preg_match('/(datetime|timestamp)/is', $this->fieldType[$name])) { - $value = date($this->dateFormat, NOW_TIME); + $value = date($this->dateFormat, $_SERVER['REQUEST_TIME']); } else { - $value = NOW_TIME; + $value = $_SERVER['REQUEST_TIME']; } } else { // 检测修改器 diff --git a/library/think/Response.php b/library/think/Response.php index 5e817368..91ab6d8b 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -207,7 +207,7 @@ class Response $result = [ 'code' => $code, 'msg' => $msg, - 'time' => NOW_TIME, + 'time' => $_SERVER['REQUEST_TIME'], 'data' => $data, ]; return $this->data($result); diff --git a/library/think/Validate.php b/library/think/Validate.php index 2b732dd9..a83a3134 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -976,7 +976,7 @@ class Validate if (!is_numeric($end)) { $end = strtotime($end); } - return NOW_TIME >= $start && NOW_TIME <= $end; + return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end; } /** diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 99b4ebe9..f2625335 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -586,7 +586,7 @@ class Query { if (false !== ($value = Cache::get($guid))) { // 存在缓存写入数据 - if (NOW_TIME > Cache::get($guid . '_time') + $lazyTime) { + if ($_SERVER['REQUEST_TIME'] > Cache::get($guid . '_time') + $lazyTime) { // 延时更新时间到了,删除缓存数据 并实际写入数据库 Cache::rm($guid); Cache::rm($guid . '_time'); @@ -600,7 +600,7 @@ class Query // 没有缓存数据 Cache::set($guid, $step, 0); // 计时开始 - Cache::set($guid . '_time', NOW_TIME, 0); + Cache::set($guid . '_time', $_SERVER['REQUEST_TIME'], 0); return false; } } diff --git a/tests/thinkphp/baseTest.php b/tests/thinkphp/baseTest.php index 43ea2a62..b61ad444 100644 --- a/tests/thinkphp/baseTest.php +++ b/tests/thinkphp/baseTest.php @@ -38,7 +38,6 @@ class baseTest extends \PHPUnit_Framework_TestCase $this->assertNotEmpty(ENV_PREFIX); $this->assertTrue(is_bool(IS_API)); $this->assertNotEmpty(APP_MODE); - $this->assertTrue(!is_null(IS_CGI)); $this->assertTrue(!is_null(IS_WIN)); $this->assertTrue(!is_null(IS_CLI)); } diff --git a/tests/thinkphp/library/think/debugTest.php b/tests/thinkphp/library/think/debugTest.php index 8a9ac863..12ff815f 100644 --- a/tests/thinkphp/library/think/debugTest.php +++ b/tests/thinkphp/library/think/debugTest.php @@ -170,7 +170,7 @@ class debugTest extends \PHPUnit_Framework_TestCase $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 (IS_MAC) { + } 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)); From 5048f7c767ef67294983646b0e1c5ce46a4e5894 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 2 Jun 2016 12:26:05 +0800 Subject: [PATCH 259/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Response=E7=B1=BB?= =?UTF-8?q?=E7=9A=84send=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Response.php b/library/think/Response.php index 91ab6d8b..d3d6d7eb 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -104,7 +104,7 @@ class Response */ public function send($data = null) { - $data = !is_null($data) ?: $this->data; + $data = !is_null($data) ? $data : $this->data; if (isset($this->contentType)) { $this->contentType($this->contentType); From 625a8767c5e29398f5e945fdb6bab02a8ca6e9ca Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 2 Jun 2016 14:18:18 +0800 Subject: [PATCH 260/670] =?UTF-8?q?Model=E7=B1=BB=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=85=A8=E5=B1=80=E6=9F=A5=E8=AF=A2=E8=8C=83=E5=9B=B4=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=20=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 5 ++++- library/think/db/Query.php | 16 +++++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index e1f9a7a0..4a7cc7e6 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -964,7 +964,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } else { $query->name($this->name); } - + // 全局作用域 + if (method_exists($this, 'base')) { + call_user_func_array([$this, 'base'], [ & $query]); + } self::$links[$model] = $query; } // 返回当前模型的数据库查询对象 diff --git a/library/think/db/Query.php b/library/think/db/Query.php index f2625335..1f61f856 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1437,7 +1437,6 @@ class Query } else { $where[$key] = strpos($data, ',') ? ['IN', $data] : $data; } - $options['where']['AND'] = $where; } elseif (is_array($pk) && is_array($data) && !empty($data)) { // 根据复合主键查询 foreach ($pk as $key) { @@ -1448,7 +1447,14 @@ class Query throw new Exception('miss complex primary data'); } } - $options['where']['AND'] = $where; + } + + if (!empty($where)) { + if (isset($options['where']['AND'])) { + $options['where']['AND'] = array_merge($options['where']['AND'], $where); + } else { + $options['where']['AND'] = $where; + } } return; } @@ -1590,7 +1596,7 @@ class Query if (false === $data) { // 用于子查询 不查询只返回SQL $options['fetch_sql'] = true; - } elseif (empty($options['where']) && !empty($data)) { + } elseif (!empty($data)) { // 主键条件分析 $this->parsePkWhere($data, $options); } @@ -1670,7 +1676,7 @@ class Query // 分析查询表达式 $options = $this->parseExpress(); - if (empty($options['where']) && (!empty($data) || 0 == $data)) { + if (!empty($data) || 0 == $data) { // AR模式分析主键条件 $this->parsePkWhere($data, $options); } @@ -1798,7 +1804,7 @@ class Query // 分析查询表达式 $options = $this->parseExpress(); - if (empty($options['where']) && !empty($data)) { + if (!empty($data)) { // AR模式分析主键条件 $this->parsePkWhere($data, $options); } From 378cdf3403861de047a703173f9a2f283c9ed194 Mon Sep 17 00:00:00 2001 From: tsingsun Date: Thu, 2 Jun 2016 17:24:51 +0800 Subject: [PATCH 261/670] =?UTF-8?q?=E5=AE=8C=E5=96=84=E5=AF=B9appError?= =?UTF-8?q?=E7=9A=84=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充记录error的记录 --- library/think/Error.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/Error.php b/library/think/Error.php index 9de97c88..140fbb24 100644 --- a/library/think/Error.php +++ b/library/think/Error.php @@ -63,9 +63,12 @@ class Error */ public static function appError($errno, $errstr, $errfile = '', $errline = 0, $errcontext = []) { + $exception = new ErrorException($errno, $errstr, $errfile, $errline, $errcontext); if (error_reporting() & $errno) { // 将错误信息托管至 think\exception\ErrorException - throw new ErrorException($errno, $errstr, $errfile, $errline, $errcontext); + throw $exception; + }else{ + self::getExceptionHandler()->report($exception); } } From 50810bef0c08d3cf1ef34f3d575121b1528324e9 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 2 Jun 2016 20:59:52 +0800 Subject: [PATCH 262/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84find=E5=92=8Cselect=E6=96=B9=E6=B3=95=E5=AF=B9cache?= =?UTF-8?q?=E7=9A=84=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 1f61f856..fbebd4e6 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1602,7 +1602,7 @@ class Query } $resultSet = false; - if (!empty($options['cache'])) { + if (empty($options['fetch_sql']) && !empty($options['cache'])) { // 判断查询缓存 $cache = $options['cache']; $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options)); @@ -1683,7 +1683,7 @@ class Query $options['limit'] = 1; $result = false; - if (!empty($options['cache'])) { + if (empty($options['fetch_sql']) && !empty($options['cache'])) { // 判断查询缓存 $cache = $options['cache']; $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options)); From 661a470e5dbeafddc050e0e87273956019f8440c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 10:26:53 +0800 Subject: [PATCH 263/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 1 - library/think/Request.php | 20 ++++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 4a7cc7e6..de63a594 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -755,7 +755,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess case Relation::HAS_MANY_THROUGH: // TODO } - } /** diff --git a/library/think/Request.php b/library/think/Request.php index 8d9c95fe..a87e7848 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -199,9 +199,9 @@ class Request * @param string $domain 域名 * @return string */ - public function domain($domain = '') + public function domain($domain = null) { - if (!empty($domain)) { + if (!is_null($domain)) { $this->domain = $domain; return $this; } elseif (!$this->domain) { @@ -216,9 +216,9 @@ class Request * @param string|true $url URL地址 true 带域名获取 * @return string */ - public function url($url = '') + public function url($url = null) { - if (is_string($url) && !empty($url)) { + if (!is_null($url) && true !== $url) { $this->url = $url; return $this; } elseif (!$this->url) { @@ -243,9 +243,9 @@ class Request * @param string $url URL地址 * @return string */ - public function baseUrl($url = '') + public function baseUrl($url = null) { - if (is_string($url) && !empty($url)) { + if (!is_null($url) && true !== $url) { $this->baseUrl = $url; return $this; } elseif (!$this->baseUrl) { @@ -261,9 +261,9 @@ class Request * @param string $file 当前执行的文件 * @return string */ - public function baseFile($file = '') + public function baseFile($file = null) { - if (is_string($file) && !empty($file)) { + if (!is_null($file) && true !== $file) { $this->baseFile = $file; return $this; } elseif (!$this->baseFile) { @@ -293,9 +293,9 @@ class Request * @param string $url URL地址 * @return string */ - public function root($url = '') + public function root($url = null) { - if (is_string($url) && !empty($url)) { + if (!is_null($url) && true !== $url) { $this->root = $url; return $this; } elseif (!$this->root) { From e37cf2cc1761d5518e964821146e60abd42d2446 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 12:12:45 +0800 Subject: [PATCH 264/670] =?UTF-8?q?=E6=B7=BB=E5=8A=A0validate=E5=8A=A9?= =?UTF-8?q?=E6=89=8B=E5=87=BD=E6=95=B0=20=E7=94=A8=E4=BA=8E=E5=AE=9E?= =?UTF-8?q?=E4=BE=8B=E5=8C=96=E9=AA=8C=E8=AF=81=E5=99=A8=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/helper.php b/helper.php index e1443931..18d8c86e 100644 --- a/helper.php +++ b/helper.php @@ -151,6 +151,17 @@ function model($name = '', $layer = 'model') return Loader::model($name, $layer); } +/** + * 实例化验证器 + * @param string $name 验证器名称 + * @param string $layer 业务层名称 + * @return \think\Validate + */ +function validate($name = '', $layer = 'validate') +{ + return Loader::validate($name, $layer); +} + /** * 实例化数据库类 * @param string $name 操作的数据表名称(不含前缀) From f05e7427d96936c391d9d10cd51342924017ca2c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 12:20:18 +0800 Subject: [PATCH 265/670] =?UTF-8?q?=E5=8E=BB=E6=8E=89=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E9=A9=B1=E5=8A=A8=E7=9A=84length=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/cache/driver/Apc.php | 1 - library/think/cache/driver/File.php | 1 - library/think/cache/driver/Memcache.php | 1 - library/think/cache/driver/Memcached.php | 1 - library/think/cache/driver/Redis.php | 3 +-- library/think/cache/driver/Redisd.php | 31 ++++++++++++------------ library/think/cache/driver/Sae.php | 1 - library/think/cache/driver/Secache.php | 1 - library/think/cache/driver/Sqlite.php | 1 - library/think/cache/driver/Wincache.php | 1 - library/think/cache/driver/Xcache.php | 1 - 11 files changed, 16 insertions(+), 27 deletions(-) diff --git a/library/think/cache/driver/Apc.php b/library/think/cache/driver/Apc.php index ebe163cc..b622762a 100644 --- a/library/think/cache/driver/Apc.php +++ b/library/think/cache/driver/Apc.php @@ -23,7 +23,6 @@ class Apc protected $options = [ 'expire' => 0, 'prefix' => '', - 'length' => 0, ]; /***************************** 需要支持apc_cli模式 diff --git a/library/think/cache/driver/File.php b/library/think/cache/driver/File.php index d8487102..267fabdd 100644 --- a/library/think/cache/driver/File.php +++ b/library/think/cache/driver/File.php @@ -25,7 +25,6 @@ class File 'cache_subdir' => false, 'path_level' => 1, 'prefix' => '', - 'length' => 0, 'path' => CACHE_PATH, 'data_compress' => false, ]; diff --git a/library/think/cache/driver/Memcache.php b/library/think/cache/driver/Memcache.php index fbfbb08a..370c6415 100644 --- a/library/think/cache/driver/Memcache.php +++ b/library/think/cache/driver/Memcache.php @@ -23,7 +23,6 @@ class Memcache 'expire' => 0, 'timeout' => 0, // 超时时间(单位:毫秒) 'persistent' => true, - 'length' => 0, 'prefix' => '', ]; diff --git a/library/think/cache/driver/Memcached.php b/library/think/cache/driver/Memcached.php index f82500f5..e413b06f 100644 --- a/library/think/cache/driver/Memcached.php +++ b/library/think/cache/driver/Memcached.php @@ -22,7 +22,6 @@ class Memcached 'port' => 11211, 'expire' => 0, 'timeout' => 0, // 超时时间(单位:毫秒) - 'length' => 0, 'prefix' => '', ]; diff --git a/library/think/cache/driver/Redis.php b/library/think/cache/driver/Redis.php index 23455a1d..403229ff 100644 --- a/library/think/cache/driver/Redis.php +++ b/library/think/cache/driver/Redis.php @@ -17,7 +17,7 @@ use think\Exception; /** * Redis缓存驱动,适合单机部署、有前端代理实现高可用的场景,性能最好 * 有需要在业务层实现读写分离、或者使用RedisCluster的需求,请使用Redisd驱动 - * + * * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis * @author 尘缘 <130775@qq.com> */ @@ -31,7 +31,6 @@ class Redis 'timeout' => 0, 'expire' => 0, 'persistent' => false, - 'length' => 0, 'prefix' => '', ]; diff --git a/library/think/cache/driver/Redisd.php b/library/think/cache/driver/Redisd.php index 67058975..d32dbaca 100644 --- a/library/think/cache/driver/Redisd.php +++ b/library/think/cache/driver/Redisd.php @@ -18,21 +18,21 @@ use think\Log; /** 配置参数: 'cache' => [ - 'type' => 'Redisd' - 'host' => 'A:6379,B:6379', //redis服务器ip,多台用逗号隔开;读写分离开启时,默认写A,当A主挂时,再尝试写B - 'slave' => 'B:6379,C:6379', //redis服务器ip,多台用逗号隔开;读写分离开启时,所有IP随机读,其中一台挂时,尝试读其它节点,可以配置权重 - 'port' => 6379, //默认的端口号 - 'password' => '', //AUTH认证密码,当redis服务直接暴露在外网时推荐 - 'timeout' => 10, //连接超时时间 - 'expire' => false, //默认过期时间,默认为永不过期 - 'prefix' => '', //缓存前缀,不宜过长 - 'persistent' => false, //是否长连接 false=短连接,推荐长连接 +'type' => 'Redisd' +'host' => 'A:6379,B:6379', //redis服务器ip,多台用逗号隔开;读写分离开启时,默认写A,当A主挂时,再尝试写B +'slave' => 'B:6379,C:6379', //redis服务器ip,多台用逗号隔开;读写分离开启时,所有IP随机读,其中一台挂时,尝试读其它节点,可以配置权重 +'port' => 6379, //默认的端口号 +'password' => '', //AUTH认证密码,当redis服务直接暴露在外网时推荐 +'timeout' => 10, //连接超时时间 +'expire' => false, //默认过期时间,默认为永不过期 +'prefix' => '', //缓存前缀,不宜过长 +'persistent' => false, //是否长连接 false=短连接,推荐长连接 ], 单例获取: - $redis = \think\Cache::connect(Config::get('cache')); - $redis->master(true)->setnx('key'); - $redis->master(false)->get('key'); +$redis = \think\Cache::connect(Config::get('cache')); +$redis->master(true)->setnx('key'); +$redis->master(false)->get('key'); */ /** @@ -70,7 +70,6 @@ class Redisd 'timeout' => 10, 'expire' => false, 'persistent' => false, - 'length' => 0, 'prefix' => '', 'serialize' => \Redis::SERIALIZER_PHP, ]; @@ -136,7 +135,7 @@ class Redisd //发生错误则摘掉当前节点 try { $result = $this->handler->$func($host, $port, $this->options['timeout']); - if($result === false) { + if (false === $result) { $this->handler->getLastError(); } @@ -145,7 +144,7 @@ class Redisd } $this->handler->setOption(\Redis::OPT_SERIALIZER, $this->options['serialize']); - if(strlen($this->options['prefix'])) { + if (strlen($this->options['prefix'])) { $this->handler->setOption(\Redis::OPT_PREFIX, $this->options['prefix']); } @@ -288,7 +287,7 @@ class Redisd $this->master(true); return $this->handler->flushDB(); } - + /** * 返回句柄对象,可执行其它高级方法 * 需要先执行 $redis->master() 连接到 DB diff --git a/library/think/cache/driver/Sae.php b/library/think/cache/driver/Sae.php index 4bead286..03b70735 100644 --- a/library/think/cache/driver/Sae.php +++ b/library/think/cache/driver/Sae.php @@ -27,7 +27,6 @@ class Sae 'expire' => 0, 'timeout' => false, 'persistent' => false, - 'length' => 0, 'prefix' => '', ]; diff --git a/library/think/cache/driver/Secache.php b/library/think/cache/driver/Secache.php index 13613bfe..67966f21 100644 --- a/library/think/cache/driver/Secache.php +++ b/library/think/cache/driver/Secache.php @@ -25,7 +25,6 @@ class Secache 'path' => '', 'expire' => 0, 'prefix' => '', - 'length' => 0, ]; /** diff --git a/library/think/cache/driver/Sqlite.php b/library/think/cache/driver/Sqlite.php index 89a24e96..6144a366 100644 --- a/library/think/cache/driver/Sqlite.php +++ b/library/think/cache/driver/Sqlite.php @@ -26,7 +26,6 @@ class Sqlite implements CacheInterface 'table' => 'sharedmemory', 'prefix' => '', 'expire' => 0, - 'length' => 0, 'persistent' => false, ]; diff --git a/library/think/cache/driver/Wincache.php b/library/think/cache/driver/Wincache.php index e77b53a2..66972a48 100644 --- a/library/think/cache/driver/Wincache.php +++ b/library/think/cache/driver/Wincache.php @@ -23,7 +23,6 @@ class Wincache protected $options = [ 'prefix' => '', 'expire' => 0, - 'length' => 0, ]; /** diff --git a/library/think/cache/driver/Xcache.php b/library/think/cache/driver/Xcache.php index 00a0483f..3fea3296 100644 --- a/library/think/cache/driver/Xcache.php +++ b/library/think/cache/driver/Xcache.php @@ -23,7 +23,6 @@ class Xcache protected $options = [ 'prefix' => '', 'expire' => 0, - 'length' => 0, ]; /** From c6b8cecc8906d9a6c33c84e1736c1870a05a0e86 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 14:00:08 +0800 Subject: [PATCH 266/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BDb=E7=B1=BB=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Db.php | 5 +++++ library/think/db/Query.php | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/library/think/Db.php b/library/think/Db.php index bd537399..4331be12 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -28,6 +28,11 @@ use think\db\Query; * @method array column(string $field, string $key = '') static 获取某个列的值 * @method mixed find(mixed $data = []) static 查询单个记录 * @method mixed select(mixed $data = []) static 查询多个记录 + * @method integer insert(array $data, boolean $replace = false, boolean $getLastInsID = false, string $sequence = null) static 插入一条记录 + * @method integer insertAll(array $dataSet) static 插入多条记录 + * @method integer update(array $data) static 更新记录 + * @method integer delete(mixed $data = []) 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 integer execute(string $sql, array $bind = [], boolean $fetch = false, boolean $getLastInsID = false, string $sequence = null) static SQL执行 * @method PaginatorCollection paginate(integer $listRows = 15, boolean $simple = false, array $config = []) static 分页查询 diff --git a/library/think/db/Query.php b/library/think/db/Query.php index fbebd4e6..be13475c 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1742,7 +1742,7 @@ class Query * @param integer $count 每次处理的数据数量 * @param callable $callback 处理回调方法 * @param string $column 分批处理的字段名 - * @return array + * @return boolean */ public function chunk($count, $callback, $column = null) { From 8af18e3527086b0bdcacd24acc078a7a08dd1905 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 14:27:14 +0800 Subject: [PATCH 267/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84parseExpress=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 37 +++++++++++++++---------------------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index be13475c..0e1ce67d 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1836,23 +1836,20 @@ class Query if (!isset($options['where'])) { $options['where'] = []; } elseif (isset($options['view'])) { - if (isset($options['where']['AND'])) { - foreach ($options['where']['AND'] as $key => $val) { - if (array_key_exists($key, $options['map'])) { - $options['where']['AND'][$options['map'][$key]] = $val; - unset($options['where']['AND'][$key]); - } - } - } - if (isset($options['where']['OR'])) { - foreach ($options['where']['OR'] as $key => $val) { - if (array_key_exists($key, $options['map'])) { - $options['where']['OR'][$options['map'][$key]] = $val; - unset($options['where']['OR'][$key]); + // 视图查询条件处理 + 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']); } @@ -1864,17 +1861,13 @@ class Query $options['order'][$options['map'][$field]] = $sort; unset($options['order'][$key]); } - } else { - if (array_key_exists($val, $options['map'])) { - $options['order'][$options['map'][$val]] = 'asc'; - unset($options['order'][$key]); - } - } - } else { - if (array_key_exists($key, $options['map'])) { - $options['order'][$options['map'][$key]] = $val; + } 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]); } } } From 99acf3d0b0bdfd66cc7f96820e9867bd25a5a3e2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 14:28:35 +0800 Subject: [PATCH 268/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 0e1ce67d..31bec497 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1821,10 +1821,10 @@ class Query /** * 分析表达式(可用于查询或者写入操作) - * @access public + * @access protected * @return array */ - public function parseExpress() + protected function parseExpress() { $options = $this->options; From 57e72fcee02af7e244fb829b3c0ce5d9a473e9ce Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 16:07:07 +0800 Subject: [PATCH 269/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E6=8D=AE=E9=AA=8C=E8=AF=81=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index de63a594..de3c9142 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -299,6 +299,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function save($data = [], $where = [], $getId = true) { if (!empty($data)) { + // 数据自动验证 + if (!$this->validateData($data)) { + return false; + } // 数据对象赋值 foreach ($data as $key => $value) { $this->__set($key, $value); @@ -307,10 +311,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->isUpdate = true; } } - // 数据自动验证 - if (!$this->validateData()) { - return false; - } // 检测字段 if (!empty($this->field)) { @@ -517,9 +517,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 自动验证当前数据对象值 * @access public + * @param array $data 验证数据 * @return bool */ - public function validateData() + public function validateData($data) { if (!empty($this->validate)) { $info = $this->validate; @@ -537,7 +538,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $validate->scene($scene); } } - if (!$validate->check($this->data)) { + if (!$validate->check($data)) { $this->error = $validate->getError(); return false; } From 87d1fddfe516de740b27fcaf8814165331f23cfc Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 16:12:09 +0800 Subject: [PATCH 270/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index de3c9142..79eb1be1 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -515,12 +515,12 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } /** - * 自动验证当前数据对象值 - * @access public + * 自动验证数据 + * @access protected * @param array $data 验证数据 * @return bool */ - public function validateData($data) + protected function validateData($data) { if (!empty($this->validate)) { $info = $this->validate; From 40f113b05ffe3ec8ff9f54e94b237087e1393e23 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 16:16:50 +0800 Subject: [PATCH 271/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84validateData=E6=96=B9=E6=B3=95=20=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E5=BC=95=E7=94=A8=E4=BC=A0=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index 79eb1be1..b9c359c3 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -520,7 +520,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param array $data 验证数据 * @return bool */ - protected function validateData($data) + protected function validateData(&$data) { if (!empty($this->validate)) { $info = $this->validate; From bd498a587e28577bdec0d7974378858529a3e655 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 16:45:55 +0800 Subject: [PATCH 272/670] =?UTF-8?q?=E9=AA=8C=E8=AF=81=E7=B1=BB=E7=9A=84che?= =?UTF-8?q?ck=E6=96=B9=E6=B3=95=20=E5=92=8C=20=E6=A8=A1=E5=9E=8B=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=20validateData=20=E6=96=B9=E6=B3=95=20=E5=8F=96?= =?UTF-8?q?=E6=B6=88=E5=BC=95=E7=94=A8=E4=BC=A0=E5=8F=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- library/think/Validate.php | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index b9c359c3..79eb1be1 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -520,7 +520,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param array $data 验证数据 * @return bool */ - protected function validateData(&$data) + protected function validateData($data) { if (!empty($this->validate)) { $info = $this->validate; diff --git a/library/think/Validate.php b/library/think/Validate.php index a83a3134..ed772d95 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -227,7 +227,7 @@ class Validate * @param string $scene 验证场景 * @return bool */ - public function check(&$data, $rules = [], $scene = '') + public function check($data, $rules = [], $scene = '') { $this->error = []; @@ -276,7 +276,7 @@ class Validate // 场景检测 if (!empty($scene)) { - if ($scene instanceof \Closure && !call_user_func_array($scene, [$key, &$data])) { + if ($scene instanceof \Closure && !call_user_func_array($scene, [$key, $data])) { continue; } elseif (is_array($scene)) { if (!in_array($key, $array)) { @@ -323,11 +323,11 @@ class Validate * @param array $msg 提示信息 * @return mixed */ - protected function checkItem($field, $value, $rules, &$data, $title = '', $msg = []) + protected function checkItem($field, $value, $rules, $data, $title = '', $msg = []) { if ($rules instanceof \Closure) { // 匿名函数验证 支持传入当前字段和所有字段两个数据 - $result = call_user_func_array($rules, [$value, &$data]); + $result = call_user_func_array($rules, [$value, $data]); } else { // 支持多规则验证 require|in:a,b,c|... 或者 ['require','in'=>'a,b,c',...] if (is_string($rules)) { @@ -336,7 +336,7 @@ class Validate $i = 0; foreach ($rules as $key => $rule) { if ($rule instanceof \Closure) { - $result = call_user_func_array($rule, [$value, &$data]); + $result = call_user_func_array($rule, [$value, $data]); } else { // 判断验证类型 if (is_numeric($key) && strpos($rule, ':')) { @@ -358,7 +358,7 @@ class Validate // 验证类型 $callback = isset(self::$type[$type]) ? self::$type[$type] : [$this, $type]; // 验证数据 - $result = call_user_func_array($callback, [$value, $rule, &$data, $field]); + $result = call_user_func_array($callback, [$value, $rule, $data, $field]); } else { $result = true; } @@ -686,7 +686,7 @@ class Validate protected function method($value, $rule) { $method = Request::instance()->method(); - return $method == strtoupper($rule); + return strtoupper($rule) == $method; } /** From fa0e85983c6d713d77bfaa2fb45bec015e5caf05 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 17:33:52 +0800 Subject: [PATCH 273/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E4=BF=AE=E6=94=B9=E5=99=A8=E6=9C=BA=E5=88=B6=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20setAttr=E5=92=8C=20getAttr=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 354 +++++++++++++++++-------------- library/think/model/Merge.php | 15 +- library/think/model/Relation.php | 10 +- 3 files changed, 203 insertions(+), 176 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 79eb1be1..2ef689fa 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -111,6 +111,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->name = basename(str_replace('\\', '/', $this->class)); } + if (empty($this->fieldType)) { + // 获取字段类型信息并缓存 + $this->fieldType = $this->db()->getTableInfo('', 'type'); + } + if (is_null($this->autoWriteTimestamp)) { $this->autoWriteTimestamp = $this->db()->getConfig('auto_timestamp'); } @@ -122,7 +127,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 获取关联模型实例 * @access protected - * @return \think\model\Relation + * @return Relation */ protected function relation() { @@ -155,7 +160,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess {} /** - * 设置数据对象值 + * 批量设置数据对象值 * @access public * @param mixed $data 数据 * @return $this @@ -171,6 +176,178 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $this; } + /** + * 修改器 设置数据对象值 + * @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, $this->deleteTime])) { + // 自动写入的时间戳字段 + if (isset($this->type[$name])) { + $type = $this->type[$name]; + if (strpos($type, ':')) { + list($type, $param) = explode(':', $type, 2); + } + switch ($type) { + case 'timestamp': + $format = !empty($param) ? $param : $this->dateFormat; + $value = date($format, $_SERVER['REQUEST_TIME']); + break; + case 'datetime': + $value = $_SERVER['REQUEST_TIME']; + break; + } + } elseif (isset($this->fieldType[$name]) && preg_match('/(datetime|timestamp)/is', $this->fieldType[$name])) { + $value = date($this->dateFormat, $_SERVER['REQUEST_TIME']); + } else { + $value = $_SERVER['REQUEST_TIME']; + } + } 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 (!isset($this->data[$name]) || ($this->data[$name] != $value && !in_array($name, $this->change))) { + $this->change[] = $name; + } + // 设置数据对象属性 + $this->data[$name] = $value; + return $this; + } + + /** + * 数据写入 类型转换 + * @access public + * @param mixed $value 值 + * @param string $type 要转换的类型 + * @return mixed + */ + protected function writeTransform($value, $type) + { + if (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 'datetime': + if (!is_numeric($value)) { + $value = strtotime($value); + } + break; + case 'timestamp': + $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 'json': + case 'array': + if (is_array($value)) { + $value = json_encode($value, JSON_UNESCAPED_UNICODE); + } + break; + } + return $value; + } + + /** + * 获取器 获取数据对象的值 + * @access public + * @param string $name 名称 + * @return mixed + */ + public function getAttr($name) + { + $value = isset($this->data[$name]) ? $this->data[$name] : null; + + // 检测属性获取器 + $method = 'get' . Loader::parseName($name, 1) . 'Attr'; + if (method_exists($this, $method)) { + return $this->$method($value, $this->data); + } elseif (!is_null($value) && isset($this->type[$name])) { + // 类型转换 + $value = $this->readTransform($value, $this->type[$name]); + } elseif (is_null($value) && method_exists($this, $name)) { + // 获取关联数据 + $value = $this->relation()->getRelation($name); + // 保存关联对象值 + $this->data[$name] = $value; + } + return $value; + } + + /** + * 数据读取 类型转换 + * @access public + * @param mixed $value 值 + * @param string $type 要转换的类型 + * @return mixed + */ + protected function readTransform($value, $type) + { + if (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 'datetime': + $format = !empty($param) ? $param : $this->dateFormat; + $value = date($format, $value); + break; + case 'timestamp': + $format = !empty($param) ? $param : $this->dateFormat; + $value = date($format, strtotime($value)); + break; + case 'json': + case 'array': + $value = json_decode($value, true); + break; + case 'object': + $value = json_decode($value); + break; + } + return $value; + } + /** * 获取对象原始数据 * @access public @@ -216,7 +393,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $item = []; if (!empty($this->append)) { foreach ($this->append as $name) { - $item[$name] = $this->__get($name); + $item[$name] = $this->getAttr($name); } } foreach ($this->data as $key => $val) { @@ -237,7 +414,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $item[$key] = $data; } else { // 模型属性 - $item[$key] = $this->__get($key); + $item[$key] = $this->getAttr($key); } } return !empty($item) ? $item : []; @@ -305,7 +482,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } // 数据对象赋值 foreach ($data as $key => $value) { - $this->__set($key, $value); + $this->setAttr($key, $value); } if (!empty($where)) { $this->isUpdate = true; @@ -326,7 +503,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 自动写入更新时间 if ($this->autoWriteTimestamp && $this->updateTime) { - $this->__set($this->updateTime, null); + $this->setAttr($this->updateTime, null); } // 事件回调 @@ -372,7 +549,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 自动写入创建时间 if ($this->autoWriteTimestamp && $this->createTime) { - $this->__set($this->createTime, null); + $this->setAttr($this->createTime, null); } if (false === $this->trigger('before_insert', $this)) { @@ -460,7 +637,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = null; } if (!in_array($field, $this->change)) { - $this->__set($field, isset($this->data[$field]) ? $this->data[$field] : $value); + $this->setAttr($field, isset($this->data[$field]) ? $this->data[$field] : $value); } } } @@ -1006,98 +1183,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function __set($name, $value) { - if (empty($this->fieldType)) { - // 获取字段类型信息并缓存 - $this->fieldType = $this->db()->getTableInfo('', 'type'); - } - if (is_null($value) && $this->autoWriteTimestamp && in_array($name, [$this->createTime, $this->updateTime, $this->deleteTime])) { - // 自动写入的时间戳字段 - if (isset($this->type[$name])) { - $type = $this->type[$name]; - if (strpos($type, ':')) { - list($type, $param) = explode(':', $type, 2); - } - switch ($type) { - case 'timestamp': - $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, $_SERVER['REQUEST_TIME']); - break; - case 'datetime': - $value = $_SERVER['REQUEST_TIME']; - break; - } - } elseif (isset($this->fieldType[$name]) && preg_match('/(datetime|timestamp)/is', $this->fieldType[$name])) { - $value = date($this->dateFormat, $_SERVER['REQUEST_TIME']); - } else { - $value = $_SERVER['REQUEST_TIME']; - } - } else { - // 检测修改器 - $method = 'set' . Loader::parseName($name, 1) . 'Attr'; - if (method_exists($this, $method)) { - $value = $this->$method($value, $this->data); - } elseif (isset($this->type[$name])) { - // 类型转换 - $value = $this->writeTransform($value, $this->type[$name]); - } - } - - // 标记字段更改 - if (!isset($this->data[$name]) || ($this->data[$name] != $value && !in_array($name, $this->change))) { - $this->change[] = $name; - } - // 设置数据对象属性 - $this->data[$name] = $value; - } - - /** - * 数据写入 类型转换 - * @access public - * @param mixed $value 值 - * @param string $type 要转换的类型 - * @return mixed - */ - protected function writeTransform($value, $type) - { - if (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 'datetime': - if (!is_numeric($value)) { - $value = strtotime($value); - } - break; - case 'timestamp': - $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 'json': - case 'array': - if (is_array($value)) { - $value = json_encode($value, JSON_UNESCAPED_UNICODE); - } - break; - } - return $value; + $this->setAttr($name, $value); } /** @@ -1108,67 +1194,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function __get($name) { - $value = isset($this->data[$name]) ? $this->data[$name] : null; - - // 检测属性获取器 - $method = 'get' . Loader::parseName($name, 1) . 'Attr'; - if (method_exists($this, $method)) { - return $this->$method($value, $this->data); - } elseif (!is_null($value) && isset($this->type[$name])) { - // 类型转换 - $value = $this->readTransform($value, $this->type[$name]); - } elseif (is_null($value) && method_exists($this, $name)) { - // 获取关联数据 - $value = $this->relation()->getRelation($name); - // 保存关联对象值 - $this->data[$name] = $value; - } - return $value; - } - - /** - * 数据读取 类型转换 - * @access public - * @param mixed $value 值 - * @param string $type 要转换的类型 - * @return mixed - */ - protected function readTransform($value, $type) - { - if (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 'datetime': - $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, $value); - break; - case 'timestamp': - $format = !empty($param) ? $param : $this->dateFormat; - $value = date($format, strtotime($value)); - break; - case 'json': - case 'array': - $value = json_decode($value, true); - break; - case 'object': - $value = json_decode($value); - break; - } - return $value; + return $this->getAttr($name); } /** @@ -1181,7 +1207,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess { if (array_key_exists($name, $this->data)) { return true; - } elseif ($this->__get($name)) { + } elseif ($this->getAttr($name)) { return true; } else { return false; @@ -1213,7 +1239,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // ArrayAccess public function offsetSet($name, $value) { - $this->__set($name, $value); + $this->setAttr($name, $value); } public function offsetExists($name) @@ -1228,7 +1254,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function offsetGet($name) { - return $this->__get($name); + return $this->getAttr($name); } /** diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index f34d8d3a..b26c8494 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -150,24 +150,25 @@ class Merge extends Model public function save($data = [], $where = [], $getId = true) { if (!empty($data)) { + // 数据自动验证 + if (!$this->validateData()) { + return false; + } // 数据对象赋值 foreach ($data as $key => $value) { - $this->__set($key, $value); + $this->setAttr($key, $value); } if (!empty($where)) { $this->isUpdate = true; } } - // 数据自动验证 - if (!$this->validateData()) { - return false; - } + // 数据自动完成 $this->autoCompleteData($this->auto); // 自动写入更新时间 if ($this->autoWriteTimestamp && $this->updateTime) { - $this->__set($this->updateTime, null); + $this->setAttr($this->updateTime, null); } $db = $this->db(); @@ -203,7 +204,7 @@ class Merge extends Model // 自动写入创建时间 if ($this->autoWriteTimestamp && $this->createTime) { - $this->__set($this->createTime, null); + $this->setAttr($this->createTime, null); } if (false === $this->trigger('before_insert', $this)) { diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index 03e2a04d..c32fe733 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -177,7 +177,7 @@ class Relation if (!isset($data[$result->$localKey])) { $data[$result->$localKey] = []; } - $result->__set($relation, $this->resultSetBuild($data[$result->$localKey], $class)); + $result->setAttr($relation, $this->resultSetBuild($data[$result->$localKey], $class)); } } break; @@ -206,7 +206,7 @@ class Relation $data[$result->$pk] = []; } - $result->__set($relation, $this->resultSetBuild($data[$result->$pk], $class)); + $result->setAttr($relation, $this->resultSetBuild($data[$result->$pk], $class)); } } break; @@ -266,7 +266,7 @@ class Relation if (!isset($data[$result->$localKey])) { $data[$result->$localKey] = []; } - $result->__set($relation, $this->resultSetBuild($data[$result->$localKey], $class)); + $result->setAttr($relation, $this->resultSetBuild($data[$result->$localKey], $class)); } break; case self::BELONGS_TO_MANY: @@ -280,7 +280,7 @@ class Relation if (!isset($data[$pk])) { $data[$pk] = []; } - $result->__set($relation, $this->resultSetBuild($data[$pk], $class)); + $result->setAttr($relation, $this->resultSetBuild($data[$pk], $class)); } break; @@ -315,7 +315,7 @@ class Relation // 设置关联模型属性 $list[$modelName] = []; } - $result->__set($relation, new $model($list[$modelName])); + $result->setAttr($relation, new $model($list[$modelName])); } /** From e54a81d720116ba4b3c956caf3c8403ff0389024 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 3 Jun 2016 18:12:47 +0800 Subject: [PATCH 274/670] =?UTF-8?q?Model=E7=B1=BB=E7=9A=84data=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=94=AF=E6=8C=81=E8=AE=BE=E7=BD=AE=E6=9F=90=E4=B8=AA?= =?UTF-8?q?=E5=B1=9E=E6=80=A7=E7=9A=84=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 2ef689fa..97e614e0 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -160,19 +160,21 @@ abstract class Model implements \JsonSerializable, \ArrayAccess {} /** - * 批量设置数据对象值 + * 设置数据对象值(不进行修改器处理) * @access public - * @param mixed $data 数据 + * @param mixed $data 数据或者属性名 + * @param mixed $value 值 * @return $this */ - public function data($data = '') + public function data($data, $value = null) { if (is_object($data)) { - $data = get_object_vars($data); - } elseif (!is_array($data)) { - throw new Exception('data type invalid', 10300); + $this->data = get_object_vars($data); + } elseif (is_array($data)) { + $this->data = $data; + } else { + $this->data[$data] = $value; } - $this->data = $data; return $this; } From e0005ea5ad12048400f9c2ec5e2982e02560ebda Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 10:07:10 +0800 Subject: [PATCH 275/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E6=A8=A1=E5=9E=8B(Mo?= =?UTF-8?q?del)=E5=B1=9E=E6=80=A7=E8=8E=B7=E5=8F=96=E5=80=BC=E6=97=B6?= =?UTF-8?q?=E4=B8=8EModel=E7=B1=BB=E7=9A=84=E6=96=B9=E6=B3=95=E5=86=B2?= =?UTF-8?q?=E7=AA=81BUG=20fix=20#105?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 97e614e0..77d4a3bf 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -292,11 +292,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 检测属性获取器 $method = 'get' . Loader::parseName($name, 1) . 'Attr'; if (method_exists($this, $method)) { - return $this->$method($value, $this->data); + $value = $this->$method($value, $this->data); } elseif (!is_null($value) && isset($this->type[$name])) { // 类型转换 $value = $this->readTransform($value, $this->type[$name]); - } elseif (is_null($value) && method_exists($this, $name)) { + } elseif (is_null($value) && !isset($this->fieldType[$name]) && method_exists($this, $name)) { // 获取关联数据 $value = $this->relation()->getRelation($name); // 保存关联对象值 From e9b60d1e4d78b761554837500dbff855aa057b87 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 10:55:21 +0800 Subject: [PATCH 276/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getData=E6=96=B9=E6=B3=95=E5=92=8CgetAttr=E6=96=B9?= =?UTF-8?q?=E6=B3=95=20=E5=A2=9E=E5=8A=A0autoFetchFieldType=E5=B1=9E?= =?UTF-8?q?=E6=80=A7=20=E7=94=A8=E4=BA=8E=E8=AE=BE=E7=BD=AE=E6=98=AF?= =?UTF-8?q?=E5=90=A6=E8=87=AA=E5=8A=A8=E8=8E=B7=E5=8F=96=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=20=E9=BB=98=E8=AE=A4=E4=B8=BAtrue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 50 ++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 77d4a3bf..b3eea262 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -63,6 +63,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $insert = []; // 更新自动完成列表 protected $update = []; + // 是否自动获取字段类型信息 + protected $autoFetchFieldType = true; // 是否需要自动写入时间戳 protected $autoWriteTimestamp; // 创建时间字段 @@ -108,15 +110,17 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->class = get_class($this); if (empty($this->name)) { + // 当前模型名 $this->name = basename(str_replace('\\', '/', $this->class)); } - if (empty($this->fieldType)) { - // 获取字段类型信息并缓存 + if ($this->autoFetchFieldType && empty($this->fieldType)) { + // 获取字段类型信息 $this->fieldType = $this->db()->getTableInfo('', 'type'); } if (is_null($this->autoWriteTimestamp)) { + // 自动写入时间戳 $this->autoWriteTimestamp = $this->db()->getConfig('auto_timestamp'); } @@ -178,6 +182,23 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $this; } + /** + * 获取对象原始数据 如果不存在指定字段返回false + * @access public + * @param string $name 字段名 留空获取全部 + * @return mixed + */ + public function getData($name = null) + { + if (is_null($name)) { + return $this->data; + } elseif (array_key_exists($name, $this->data)) { + return $this->data[$name]; + } else { + return false; + } + } + /** * 修改器 设置数据对象值 * @access public @@ -287,17 +308,17 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function getAttr($name) { - $value = isset($this->data[$name]) ? $this->data[$name] : null; + $value = $this->getData($name); // 检测属性获取器 $method = 'get' . Loader::parseName($name, 1) . 'Attr'; if (method_exists($this, $method)) { $value = $this->$method($value, $this->data); - } elseif (!is_null($value) && isset($this->type[$name])) { + } elseif (isset($this->type[$name])) { // 类型转换 $value = $this->readTransform($value, $this->type[$name]); - } elseif (is_null($value) && !isset($this->fieldType[$name]) && method_exists($this, $name)) { - // 获取关联数据 + } elseif (false === $value && method_exists($this, $name)) { + // 不存在该字段 获取关联数据 $value = $this->relation()->getRelation($name); // 保存关联对象值 $this->data[$name] = $value; @@ -350,17 +371,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $value; } - /** - * 获取对象原始数据 - * @access public - * @param string $name 字段名 留空获取全部 - * @return array - */ - public function getData($name = '') - { - return array_key_exists($name, $this->data) ? $this->data[$name] : $this->data; - } - /** * 设置需要追加的输出属性 * @access public @@ -374,7 +384,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } /** - * 设置需要隐藏的属性 + * 设置需要隐藏的输出属性 * @access public * @param array $hidden 属性列表 * @return $this @@ -662,9 +672,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } /** - * 设置自动完成的字段 + * 设置自动完成的字段( 规则通过修改器定义) * @access public - * @param array $fields 需要自动完成的字段( 规则通过修改器定义) + * @param array $fields 需要自动完成的字段 * @return $this */ public function auto($fields) From 150a3fe190bbf9e0aebda617f48c767908ecadfd Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 11:59:16 +0800 Subject: [PATCH 277/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BValidate=E7=B1=BB=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E9=9D=99=E6=80=81=E8=B0=83=E7=94=A8=20?= =?UTF-8?q?=E5=8F=AF=E7=94=A8=E4=BA=8E=E5=8D=95=E7=8B=AC=E7=9A=84=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Validate.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/library/think/Validate.php b/library/think/Validate.php index ed772d95..69081dab 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -11,6 +11,7 @@ namespace think; +use think\Exception; use think\Input; use think\Request; @@ -1107,4 +1108,14 @@ class Validate } return $scene; } + + public static function __callStatic($method, $params) + { + $class = new static; + if (method_exists($class, $method)) { + return call_user_func_array([$class, $method], $params); + } else { + throw new Exception(__CLASS__ . ':' . $method . ' method not exist'); + } + } } From 4dbc959a8969780552b59a5c227c2774bbec6d50 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 12:03:52 +0800 Subject: [PATCH 278/670] =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E7=B1=BB=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96=E9=BB=98=E8=AE=A4=E4=B8=8D=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E5=AD=97=E6=AE=B5=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index b3eea262..86c33325 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -64,7 +64,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 更新自动完成列表 protected $update = []; // 是否自动获取字段类型信息 - protected $autoFetchFieldType = true; + protected $autoFetchFieldType = false; // 是否需要自动写入时间戳 protected $autoWriteTimestamp; // 创建时间字段 From 6dd242ab4bf12c3b230e4e6a909f042e55edcbf7 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 13:41:00 +0800 Subject: [PATCH 279/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB=20?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E8=A7=84=E5=88=99=E6=A3=80=E6=B5=8B=E7=9A=84?= =?UTF-8?q?=E6=97=B6=E5=80=99=E5=8E=BB=E9=99=A4=E5=BC=80=E5=A4=B4=E7=9A=84?= =?UTF-8?q?/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/library/think/Route.php b/library/think/Route.php index 1ddcc933..19467985 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -786,6 +786,8 @@ class Route $url = str_replace($depr, '/', $url); $rule = str_replace($depr, '/', $rule); } + + $rule = ltrim($rule, '/'); $len1 = substr_count($url, '/'); $len2 = substr_count($rule, '/'); // 多余参数是否合并 From 40b8b30dc72b43763abba2ea04fc6cafa0d28d57 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 14:01:02 +0800 Subject: [PATCH 280/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84value=E6=96=B9=E6=B3=95=20=E6=B7=BB=E5=8A=A0default?= =?UTF-8?q?=E5=8F=82=E6=95=B0=20=E6=94=B9=E8=BF=9B=E8=81=9A=E5=90=88?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 31bec497..3d757d99 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -358,11 +358,12 @@ class Query * 得到某个字段的值 * @access public * @param string $field 字段名 + * @param mixed $default 默认值 * @return mixed */ - public function value($field) + public function value($field, $default = null) { - $result = false; + $result = null; if (!empty($this->options['cache'])) { // 判断查询缓存 $cache = $this->options['cache']; @@ -383,7 +384,7 @@ class Query // 清空查询条件 $this->options = []; } - return $result; + return !is_null($result) ? $result : $default; } /** @@ -450,7 +451,7 @@ class Query */ public function count($field = '*') { - return $this->value('COUNT(' . $field . ') AS tp_count'); + return $this->value('COUNT(' . $field . ') AS tp_count', 0); } /** @@ -461,8 +462,7 @@ class Query */ public function sum($field = '*') { - $result = $this->value('SUM(' . $field . ') AS tp_sum'); - return is_null($result) ? 0 : $result; + return $this->value('SUM(' . $field . ') AS tp_sum', 0); } /** @@ -473,8 +473,7 @@ class Query */ public function min($field = '*') { - $result = $this->value('MIN(' . $field . ') AS tp_min'); - return is_null($result) ? 0 : $result; + return $this->value('MIN(' . $field . ') AS tp_min', 0); } /** @@ -485,8 +484,7 @@ class Query */ public function max($field = '*') { - $result = $this->value('MAX(' . $field . ') AS tp_max'); - return is_null($result) ? 0 : $result; + return $this->value('MAX(' . $field . ') AS tp_max', 0); } /** @@ -497,8 +495,7 @@ class Query */ public function avg($field = '*') { - $result = $this->value('AVG(' . $field . ') AS tp_avg'); - return is_null($result) ? 0 : $result; + return $this->value('AVG(' . $field . ') AS tp_avg', 0); } /** From 326ef84f3b0013206ea3a14709da9a4ebabb86ad Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 17:33:33 +0800 Subject: [PATCH 281/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BInput=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Input.php | 2 +- library/think/db/Query.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Input.php b/library/think/Input.php index 834bd5f0..96b7e90e 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -410,7 +410,7 @@ class Input } else { if (is_array($filter)) { $result = $filter; - } elseif (is_string($filter) && strpos($filter, ',')) { + } elseif (is_string($filter) && false === strpos($filter, '/') && strpos($filter, ',')) { $result = explode(',', $filter); } else { $result = [$filter]; diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 3d757d99..ce5267f5 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -503,7 +503,7 @@ class Query * 支持使用数据库字段和方法 * @access public * @param string|array $field 字段名 - * @param string $value 字段值 + * @param mixed $value 字段值 * @return integer */ public function setField($field, $value = '') From d041ee665cb101b19eb3a89ccf941a56a1642c98 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 17:52:47 +0800 Subject: [PATCH 282/670] =?UTF-8?q?Controller=E5=92=8CModel=E7=B1=BB?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0failException=E6=96=B9=E6=B3=95=20=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E8=AE=BE=E7=BD=AE=E9=AA=8C=E8=AF=81=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E5=90=8E=E6=98=AF=E5=90=A6=E6=8A=9B=E5=87=BA=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 21 ++++++++++++++++++++- library/think/Model.php | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/library/think/Controller.php b/library/think/Controller.php index 5920d7c0..0fc04c49 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -13,6 +13,7 @@ namespace think; \think\Loader::import('controller/Jump', TRAIT_PATH, EXT); +use think\Exception; use think\Request; use think\View; @@ -24,6 +25,8 @@ class Controller protected $view = null; // Request实例 protected $request; + // 验证失败是否抛出异常 + protected $failException = false; /** * 前置操作方法列表 @@ -136,6 +139,18 @@ class Controller $this->view->engine($engine); } + /** + * 设置验证失败后是否抛出异常 + * @access public + * @param bool $fail 是否抛出异常 + * @return $this + */ + public function failException($fail = true) + { + $this->failException = $fail; + return $this; + } + /** * 验证数据 * @access public @@ -170,7 +185,11 @@ class Controller } if (!$v->check($data)) { - return $v->getError(); + if ($this->failException) { + throw new Exception($v->getError()); + } else { + return $v->getError(); + } } else { return true; } diff --git a/library/think/Model.php b/library/think/Model.php index 86c33325..3bd42ca1 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -14,6 +14,7 @@ namespace think; use think\Cache; use think\Db; use think\db\Query; +use think\Exception; use think\Loader; use think\model\Relation; use think\paginator\Collection as PaginatorCollection; @@ -85,6 +86,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $relation; // 属性类型 protected $fieldType = []; + // 验证失败是否抛出异常 + protected $failException = false; /** * 初始化过的模型. @@ -703,6 +706,18 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $this; } + /** + * 设置验证失败后是否抛出异常 + * @access public + * @param bool $fail 是否抛出异常 + * @return $this + */ + public function failException($fail = true) + { + $this->failException = $fail; + return $this; + } + /** * 自动验证数据 * @access protected @@ -729,7 +744,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } if (!$validate->check($data)) { $this->error = $validate->getError(); - return false; + if ($this->failException) { + throw new Exception($this->error); + } else { + return false; + } } $this->validate = null; } From 72c5781259463d7e332e1a8b88b531b283b030bc Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 19:52:17 +0800 Subject: [PATCH 283/670] =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E5=AE=9A=E4=B9=89?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mode/common.php | 57 ++++++++++++++++++++++++++++++++++++++++++------- mode/sae.php | 10 +++++++++ 2 files changed, 59 insertions(+), 8 deletions(-) diff --git a/mode/common.php b/mode/common.php index b56e1f06..f544c82e 100644 --- a/mode/common.php +++ b/mode/common.php @@ -29,11 +29,43 @@ return [ 'think\App' => CORE_PATH . 'App' . EXT, 'think\Build' => CORE_PATH . 'Build' . EXT, 'think\Cache' => CORE_PATH . 'Cache' . EXT, + 'think\cache\driver\Apc' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Apc' . EXT, + 'think\cache\driver\File' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'File' . EXT, + 'think\cache\driver\Lite' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Lite' . EXT, + 'think\cache\driver\Memcache' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Memcache' . EXT, + 'think\cache\driver\Memcached' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Memcached' . EXT, + 'think\cache\driver\Redis' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Redis' . EXT, + 'think\cache\driver\Secache' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Secache' . EXT, + 'think\cache\driver\Sqlite' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Sqlite' . EXT, + 'think\cache\driver\Wincache' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Wincache' . EXT, + 'think\cache\driver\Xcache' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'Xcache' . EXT, 'think\Config' => CORE_PATH . 'Config' . EXT, + 'think\config\Ini' => CORE_PATH . 'config' . DS . 'driver' . DS . 'Ini' . EXT, + 'think\config\Json' => CORE_PATH . 'config' . DS . 'driver' . DS . 'Json' . EXT, + 'think\config\Xml' => CORE_PATH . 'config' . DS . 'driver' . DS . 'Xml' . EXT, 'think\Console' => CORE_PATH . 'Console' . EXT, + 'think\Collection' => CORE_PATH . 'Collection' . EXT, 'think\Controller' => CORE_PATH . 'Controller' . EXT, + 'think\controller\Hprose' => CORE_PATH . 'controller' . DS . 'Hprose' . EXT, + 'think\controller\Jsonrpc' => CORE_PATH . 'controller' . DS . 'Jsonrpc' . EXT, + 'think\controller\Rest' => CORE_PATH . 'controller' . DS . 'Rest' . EXT, + 'think\controller\Rpc' => CORE_PATH . 'controller' . DS . 'Rpc' . EXT, + 'think\controller\Yar' => CORE_PATH . 'controller' . DS . 'Yar' . EXT, 'think\Cookie' => CORE_PATH . 'Cookie' . EXT, 'think\Db' => CORE_PATH . 'Db' . EXT, + 'think\db\Connection' => CORE_PATH . 'db' . DS . 'Connection' . EXT, + 'think\db\connector\Mysql' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Mysql' . EXT, + 'think\db\connector\Oracle' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Oracle' . EXT, + 'think\db\connector\Pgsql' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Pgsql' . EXT, + 'think\db\connector\Sqlite' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Sqlite' . EXT, + 'think\db\connector\Sqlsrv' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Sqlsrv' . EXT, + 'think\db\Builder' => CORE_PATH . 'db' . DS . 'Builder' . EXT, + 'think\db\Builder\Mysql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Mysql' . EXT, + 'think\db\Builder\Oracle' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Oracle' . EXT, + 'think\db\Builder\Pgsql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Pgsql' . EXT, + 'think\db\Builder\Sqlite' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Sqlite' . EXT, + 'think\db\Builder\Sqlsrv' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Sqlsrv' . EXT, + 'think\db\Query' => CORE_PATH . 'db' . DS . 'Query' . EXT, 'think\Debug' => CORE_PATH . 'Debug' . EXT, 'think\Error' => CORE_PATH . 'Error' . EXT, 'think\Exception' => CORE_PATH . 'Exception' . EXT, @@ -50,27 +82,36 @@ return [ 'think\Input' => CORE_PATH . 'Input' . EXT, 'think\Lang' => CORE_PATH . 'Lang' . EXT, 'think\Log' => CORE_PATH . 'Log' . EXT, + 'think\log\driver\File' => CORE_PATH . 'log' . DS . 'driver' . DS . 'File' . EXT, + 'think\log\driver\Socket' => CORE_PATH . 'log' . DS . 'driver' . DS . 'Socket' . EXT, + 'think\log\driver\Trace' => CORE_PATH . 'log' . DS . 'driver' . DS . 'Trace' . EXT, 'think\Model' => CORE_PATH . 'Model' . EXT, 'think\model\Relation' => CORE_PATH . 'model' . DS . 'Relation' . EXT, 'think\model\Merge' => CORE_PATH . 'model' . DS . 'Merge' . EXT, 'think\model\Pivot' => CORE_PATH . 'model' . DS . 'Pivot' . EXT, + 'think\Request' => CORE_PATH . 'Request' . EXT, 'think\Response' => CORE_PATH . 'Response' . EXT, + 'think\response\Json' => CORE_PATH . 'response' . DS . 'Json' . EXT, + 'think\response\Jsonp' => CORE_PATH . 'response' . DS . 'Jsonp' . EXT, + 'think\response\Redirect' => CORE_PATH . 'response' . DS . 'Redirect' . EXT, + 'think\response\View' => CORE_PATH . 'response' . DS . 'View' . EXT, + 'think\response\Xml' => CORE_PATH . 'response' . DS . 'Xml' . EXT, 'think\Process' => CORE_PATH . 'Process' . EXT, + 'think\paginator\Collection' => CORE_PATH . 'paginator' . DS . 'Collection' . EXT, + 'think\paginator\driver\Bootstrap' => CORE_PATH . 'paginator' . DS . 'driver' . DS . 'Bootstrap' . EXT, 'think\Route' => CORE_PATH . 'Route' . EXT, 'think\Session' => CORE_PATH . 'Session' . EXT, + 'think\session\driver\Memcache' => CORE_PATH . 'session' . DS . 'driver' . DS . 'Memcache' . EXT, + 'think\session\driver\Memcached' => CORE_PATH . 'session' . DS . 'driver' . DS . 'Memcached' . EXT, + 'think\session\driver\Redis' => CORE_PATH . 'session' . DS . 'driver' . DS . 'Redis' . EXT, 'think\Template' => CORE_PATH . 'Template' . EXT, + 'think\template\Taglib' => CORE_PATH . 'template' . DS . 'Taglib' . EXT, + 'think\template\taglib\Cx' => CORE_PATH . 'template' . DS . 'taglib' . DS . 'Cx' . EXT, + 'think\template\driver\File' => CORE_PATH . 'template' . DS . 'driver' . DS . 'File' . EXT, 'think\Url' => CORE_PATH . 'Url' . EXT, 'think\Validate' => CORE_PATH . 'Validate' . EXT, 'think\View' => CORE_PATH . 'View' . EXT, - 'think\db\Connection' => CORE_PATH . 'db' . DS . 'Connection' . EXT, - 'think\db\connector\Mysql' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Mysql' . EXT, - 'think\db\Builder' => CORE_PATH . 'db' . DS . 'Builder' . EXT, - 'think\db\Builder\Mysql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Mysql' . EXT, - 'think\db\Query' => CORE_PATH . 'db' . DS . 'Query' . EXT, 'think\view\driver\Think' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Think' . EXT, 'think\view\driver\Php' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Php' . EXT, - 'think\template\driver\File' => CORE_PATH . 'template' . DS . 'driver' . DS . 'File' . EXT, - 'think\log\driver\File' => CORE_PATH . 'log' . DS . 'driver' . DS . 'File' . EXT, - 'think\cache\driver\File' => CORE_PATH . 'cache' . DS . 'driver' . DS . 'File' . EXT, ], ]; diff --git a/mode/sae.php b/mode/sae.php index 4a944a6a..7344a844 100644 --- a/mode/sae.php +++ b/mode/sae.php @@ -75,6 +75,7 @@ return [ 'think\Cache' => CORE_PATH . 'Cache' . EXT, 'think\Config' => CORE_PATH . 'Config' . EXT, 'think\Console' => CORE_PATH . 'Console' . EXT, + 'think\Collection' => CORE_PATH . 'Collection' . EXT, 'think\Controller' => CORE_PATH . 'Controller' . EXT, 'think\Cookie' => CORE_PATH . 'Cookie' . EXT, 'think\Db' => CORE_PATH . 'Db' . EXT, @@ -95,11 +96,20 @@ return [ 'think\Lang' => CORE_PATH . 'Lang' . EXT, 'think\Log' => CORE_PATH . 'Log' . EXT, 'think\Model' => CORE_PATH . 'Model' . EXT, + 'think\Paginator' => CORE_PATH . 'Paginator' . EXT, 'think\model\Relation' => CORE_PATH . 'model' . DS . 'Relation' . EXT, 'think\model\Merge' => CORE_PATH . 'model' . DS . 'Merge' . EXT, 'think\model\Pivot' => CORE_PATH . 'model' . DS . 'Pivot' . EXT, 'think\Process' => CORE_PATH . 'Process' . EXT, + 'think\paginator\Collection' => CORE_PATH . 'paginator' . DS . 'Collection' . EXT, + 'think\paginator\driver\Bootstrap' => CORE_PATH . 'paginator' . DS . 'driver' . DS . 'Bootstrap' . EXT, + 'think\Request' => CORE_PATH . 'Request' . EXT, 'think\Response' => CORE_PATH . 'Response' . EXT, + 'think\response\Json' => CORE_PATH . 'response' . DS . 'Json' . EXT, + 'think\response\Jsonp' => CORE_PATH . 'response' . DS . 'Jsonp' . EXT, + 'think\response\Redirect' => CORE_PATH . 'response' . DS . 'Redirect' . EXT, + 'think\response\View' => CORE_PATH . 'response' . DS . 'View' . EXT, + 'think\response\Xml' => CORE_PATH . 'response' . DS . 'Xml' . EXT, 'think\Route' => CORE_PATH . 'Route' . EXT, 'think\Session' => CORE_PATH . 'Session' . EXT, 'think\Template' => CORE_PATH . 'Template' . EXT, From 33e045c1e5445f211c5b6f74e2e56682f4bc0851 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 23:08:38 +0800 Subject: [PATCH 284/670] =?UTF-8?q?=E8=B0=83=E6=95=B4=E6=A8=A1=E5=BC=8F?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=E4=B8=AD=E7=9A=84=E5=88=AB=E5=90=8D=E5=AE=9A?= =?UTF-8?q?=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mode/common.php | 11 ++++++----- mode/console.php | 4 ++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/mode/common.php b/mode/common.php index f544c82e..1fa74a31 100644 --- a/mode/common.php +++ b/mode/common.php @@ -60,11 +60,11 @@ return [ 'think\db\connector\Sqlite' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Sqlite' . EXT, 'think\db\connector\Sqlsrv' => CORE_PATH . 'db' . DS . 'connector' . DS . 'Sqlsrv' . EXT, 'think\db\Builder' => CORE_PATH . 'db' . DS . 'Builder' . EXT, - 'think\db\Builder\Mysql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Mysql' . EXT, - 'think\db\Builder\Oracle' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Oracle' . EXT, - 'think\db\Builder\Pgsql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Pgsql' . EXT, - 'think\db\Builder\Sqlite' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Sqlite' . EXT, - 'think\db\Builder\Sqlsrv' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Sqlsrv' . EXT, + 'think\db\builder\Mysql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Mysql' . EXT, + 'think\db\builder\Oracle' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Oracle' . EXT, + 'think\db\builder\Pgsql' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Pgsql' . EXT, + 'think\db\builder\Sqlite' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Sqlite' . EXT, + 'think\db\builder\Sqlsrv' => CORE_PATH . 'db' . DS . 'builder' . DS . 'Sqlsrv' . EXT, 'think\db\Query' => CORE_PATH . 'db' . DS . 'Query' . EXT, 'think\Debug' => CORE_PATH . 'Debug' . EXT, 'think\Error' => CORE_PATH . 'Error' . EXT, @@ -113,5 +113,6 @@ return [ 'think\View' => CORE_PATH . 'View' . EXT, 'think\view\driver\Think' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Think' . EXT, 'think\view\driver\Php' => CORE_PATH . 'view' . DS . 'driver' . DS . 'Php' . EXT, + 'traits\controller\Jump' => TRAIT_PATH . 'controller' . DS . 'Jump' . EXT, ], ]; diff --git a/mode/console.php b/mode/console.php index 1da52480..4b1be21b 100644 --- a/mode/console.php +++ b/mode/console.php @@ -23,9 +23,9 @@ return [ ], // 别名定义 'alias' => [ - 'think\App' => MODE_PATH . 'console/App' . EXT + 'think\App' => MODE_PATH . 'console' . DS . 'App' . EXT, ], // 配置文件 - 'config' => THINK_PATH . 'convention' . EXT + 'config' => THINK_PATH . 'convention' . EXT, ]; From 850aa53374afa1f3e1476a7978d125d45a47c4b7 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 23:11:42 +0800 Subject: [PATCH 285/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84save=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index 3bd42ca1..a19cecdf 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -497,7 +497,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } // 数据对象赋值 foreach ($data as $key => $value) { - $this->setAttr($key, $value); + $this->setAttr($key, $value, $data); } if (!empty($where)) { $this->isUpdate = true; From 690ae910ef2db154fb07cfeb13cac18cc291aeeb Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 5 Jun 2016 09:42:27 +0800 Subject: [PATCH 286/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BLoader=E7=B1=BB=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0Composer=E8=87=AA=E5=8A=A8=E5=8A=A0=E8=BD=BD?= =?UTF-8?q?=E5=BC=80=E5=85=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 33 +++++++++++---------- tests/thinkphp/library/think/loaderTest.php | 3 +- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/library/think/Loader.php b/library/think/Loader.php index e54b7ed3..451fb3c4 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -29,6 +29,14 @@ class Loader private static $prefixDirsPsr4 = []; // PSR-0 private static $prefixesPsr0 = []; + // Composer自动加载 + private static $composerLoader = true; + + // 自动加载Composer + public static function composerAutoLoader($auto) + { + self::$composerLoader = $auto; + } // 自动加载 public static function autoload($class) @@ -43,19 +51,12 @@ class Loader } } } - // 检查是否定义类库映射 - if (isset(self::$map[$class])) { - if (is_file(self::$map[$class])) { - // 记录加载信息 - APP_DEBUG && self::$load[] = self::$map[$class]; - include self::$map[$class]; - } else { - return false; - } - } elseif ($file = self::findFileInComposer($class)) { + + if (!empty(self::$map[$class])) { + // 类库映射 + include self::$map[$class]; + } elseif (self::$composerLoader && $file = self::findFileInComposer($class)) { // Composer自动加载 - // 记录加载信息 - APP_DEBUG && self::$load[] = $file; include $file; } else { // 命名空间自动加载 @@ -79,8 +80,6 @@ class Loader if (APP_DEBUG && IS_WIN && false === strpos(realpath($filename), $class . EXT)) { return false; } - // 记录加载信息 - APP_DEBUG && self::$load[] = $filename; include $filename; } else { return false; @@ -123,9 +122,11 @@ class Loader public static function register($autoload = '') { // 注册系统自动加载 - spl_autoload_register($autoload ? $autoload : 'think\\Loader::autoload'); + spl_autoload_register($autoload ?: 'think\\Loader::autoload'); // 注册composer自动加载 - self::registerComposerLoader(); + if (self::$composerLoader) { + self::registerComposerLoader(); + } } // 注册composer自动加载 diff --git a/tests/thinkphp/library/think/loaderTest.php b/tests/thinkphp/library/think/loaderTest.php index 373a320b..0f1a1a2c 100644 --- a/tests/thinkphp/library/think/loaderTest.php +++ b/tests/thinkphp/library/think/loaderTest.php @@ -32,8 +32,7 @@ class loaderTest extends \PHPUnit_Framework_TestCase public function testAddMap() { - Loader::addMap('my\hello\Test', 'Test.php'); - $this->assertEquals(false, Loader::autoload('my\hello\Test')); + Loader::addMap('my\hello\Test', __DIR__ . DS . 'loader' . DS . 'Test.php'); } public function testAddNamespace() From 86475343726d2f17df66603df5ef26d984b5777a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 5 Jun 2016 13:29:09 +0800 Subject: [PATCH 287/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BBevent?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index a19cecdf..904956ed 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -38,7 +38,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 当前类名称 protected $class; // 回调事件 - protected static $event = []; + private static $event = []; // 数据表主键 复合主键使用数组定义 protected $pk; @@ -775,10 +775,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public static function event($event, $callback, $override = false) { + $class = get_called_class(); if ($override) { - static::$event[$event] = []; + self::$event[$class][$event] = []; } - static::$event[$event][] = $callback; + self::$event[$class][$event][] = $callback; } /** @@ -790,8 +791,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ protected function trigger($event, &$params) { - if (isset(static::$event[$event])) { - foreach (static::$event[$event] as $callback) { + 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) { From bf72c1d408f4569d86938b48bb4b11387126ed1d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 08:08:25 +0800 Subject: [PATCH 288/670] =?UTF-8?q?Model=E7=B1=BBsave=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E6=94=B9=E8=BF=9B=20=E6=94=AF=E6=8C=81replace=20=E5=86=99?= =?UTF-8?q?=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 904956ed..93c7f933 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -486,9 +486,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param array $data 数据 * @param array $where 更新条件 * @param bool $getId 新增的时候是否获取id + * @param bool $replace 是否replace * @return integer */ - public function save($data = [], $where = [], $getId = true) + public function save($data = [], $where = [], $getId = true, $replace = false) { if (!empty($data)) { // 数据自动验证 @@ -571,7 +572,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return false; } - $result = $this->db()->insert($this->data); + $result = $this->db()->insert($this->data, $replace); // 获取自动增长主键 if ($result && $getId) { @@ -808,12 +809,13 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * 写入数据 * @access public * @param array $data 数据数组 + * @param bool $replace 是否replace * @return $this */ - public static function create($data = []) + public static function create($data = [], $replace = false) { $model = new static(); - $model->isUpdate(false)->save($data); + $model->isUpdate(false)->save($data, [], true, $replace); return $model; } From 486e58975ba2c1e5f0aeb9dfeefb6653b4bd9400 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 10:19:52 +0800 Subject: [PATCH 289/670] =?UTF-8?q?Model=E7=B1=BB=E6=B3=A8=E9=87=8A?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 76 ++++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 93c7f933..38a4935c 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -131,6 +131,34 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->initialize(); } + /** + * 获取当前模型的数据库查询对象 + * @access public + * @return Query + */ + public function db() + { + $model = $this->class; + if (!isset(self::$links[$model])) { + // 设置当前模型 确保查询返回模型对象 + $query = Db::connect($this->connection)->model($model); + + // 设置当前数据表和模型名 + if (!empty($this->table)) { + $query->setTable($this->table); + } else { + $query->name($this->name); + } + // 全局作用域 + if (method_exists($this, 'base')) { + call_user_func_array([$this, 'base'], [ & $query]); + } + self::$links[$model] = $query; + } + // 返回当前模型的数据库查询对象 + return self::$links[$model]; + } + /** * 获取关联模型实例 * @access protected @@ -869,7 +897,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param mixed $data 主键列表或者查询条件(闭包) * @param string $with 关联预查询 * @param bool $cache 是否缓存 - * @return \think\db\Query + * @return Query */ protected static function parseQuery(&$data, $with, $cache) { @@ -920,7 +948,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @access public * @param string|array|Closure $name 命名范围名称 逗号分隔 * @param mixed $params 参数调用 - * @return \think\Model + * @return Model */ public static function scope($name, $params = []) { @@ -951,7 +979,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $operator 比较操作符 * @param integer $count 个数 * @param string $id 关联表的统计字段 - * @return \think\Model + * @return Model */ public static function has($relation, $operator = '>=', $count = 1, $id = '*') { @@ -974,7 +1002,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @access public * @param string $relation 关联方法名 * @param mixed $where 查询条件(数组或者闭包) - * @return \think\Model + * @return Model */ public static function hasWhere($relation, $where = []) { @@ -1052,7 +1080,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @access public * @param Model $result 数据对象 * @param string $relation 关联名 - * @return \think\Model + * @return Model */ public function eagerlyResult($result, $relation) { @@ -1066,7 +1094,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $foreignKey 关联外键 * @param string $localKey 关联主键 * @param array $alias 别名定义 - * @return \think\db\Query|string + * @return Relation */ public function hasOne($model, $foreignKey = '', $localKey = '', $alias = []) { @@ -1084,7 +1112,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $foreignKey 关联外键 * @param string $otherKey 关联主键 * @param array $alias 别名定义 - * @return \think\db\Query|string + * @return Relation */ public function belongsTo($model, $foreignKey = '', $otherKey = '', $alias = []) { @@ -1102,7 +1130,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $foreignKey 关联外键 * @param string $localKey 关联主键 * @param array $alias 别名定义 - * @return \think\db\Query|string + * @return Relation */ public function hasMany($model, $foreignKey = '', $localKey = '', $alias = []) { @@ -1122,7 +1150,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $throughKey 关联外键 * @param string $localKey 关联主键 * @param array $alias 别名定义 - * @return \think\db\Query|string + * @return Relation */ public function hasManyThrough($model, $through, $foreignKey = '', $throughKey = '', $localKey = '', $alias = []) { @@ -1144,7 +1172,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $foreignKey 关联外键 * @param string $localKey 当前模型关联键 * @param array $alias 别名定义 - * @return \think\db\Query|string + * @return Relation */ public function belongsToMany($model, $table = '', $foreignKey = '', $localKey = '', $alias = []) { @@ -1157,34 +1185,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $this->relation()->belongsToMany($model, $table, $foreignKey, $localKey, $alias); } - /** - * 获取当前模型的数据库查询对象 - * @access public - * @return \think\db\Query - */ - public function db() - { - $model = $this->class; - if (!isset(self::$links[$model])) { - // 设置当前模型 确保查询返回模型对象 - $query = Db::connect($this->connection)->model($model); - - // 设置当前数据表和模型名 - if (!empty($this->table)) { - $query->setTable($this->table); - } else { - $query->name($this->name); - } - // 全局作用域 - if (method_exists($this, 'base')) { - call_user_func_array([$this, 'base'], [ & $query]); - } - self::$links[$model] = $query; - } - // 返回当前模型的数据库查询对象 - return self::$links[$model]; - } - public function __call($method, $args) { if (method_exists($this, 'scope' . $method)) { From 0efb5d02fd841684c5b00e19ee9846362bc64b56 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 14:22:37 +0800 Subject: [PATCH 290/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E5=AD=98=E5=82=A8=E7=BB=93=E6=9E=84=E5=92=8C=E8=BE=93=E5=87=BA?= =?UTF-8?q?=E9=A9=B1=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Log.php | 4 +- library/think/log/driver/File.php | 13 ++--- library/think/log/driver/Sae.php | 13 ++--- library/think/log/driver/Socket.php | 74 ++++++++++++++++++----------- library/think/log/driver/Trace.php | 6 ++- 5 files changed, 62 insertions(+), 48 deletions(-) diff --git a/library/think/Log.php b/library/think/Log.php index ffa03fd4..d3eda965 100644 --- a/library/think/Log.php +++ b/library/think/Log.php @@ -77,7 +77,7 @@ class Log if (!is_string($msg)) { $msg = var_export($msg, true); } - self::$log[] = ['type' => $type, 'msg' => $msg]; + self::$log[$type][] = $msg; } /** @@ -123,7 +123,7 @@ class Log $msg = var_export($msg, true); } // 封装日志信息 - $log[] = ['type' => $type, 'msg' => $msg]; + $log[$type][] = $msg; // 监听log_write Hook::listen('log_write', $log); diff --git a/library/think/log/driver/File.php b/library/think/log/driver/File.php index d525e4ca..62cb9827 100644 --- a/library/think/log/driver/File.php +++ b/library/think/log/driver/File.php @@ -62,14 +62,11 @@ class File $memory_str = " [内存消耗:{$memory_use}kb]"; $file_load = " [文件加载:" . count(get_included_files()) . "]"; - array_unshift($log, [ - 'type' => 'log', - 'msg' => $current_uri . $time_str . $memory_str . $file_load, - ]); - - $info = ''; - foreach ($log as $line) { - $info .= '[' . $line['type'] . '] ' . $line['msg'] . "\r\n"; + $info = '[ log ] ' . $current_uri . $time_str . $memory_str . $file_load . "\r\n"; + foreach ($log as $type => $val) { + foreach ($val as $msg) { + $info .= '[ ' . $type . ' ] ' . $msg . "\r\n"; + } } $server = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '0.0.0.0'; diff --git a/library/think/log/driver/Sae.php b/library/think/log/driver/Sae.php index d01bdabc..036245dd 100644 --- a/library/think/log/driver/Sae.php +++ b/library/think/log/driver/Sae.php @@ -41,14 +41,11 @@ class Sae $memory_str = " [内存消耗:{$memory_use}kb]"; $file_load = " [文件加载:" . count(get_included_files()) . "]"; - array_unshift($log, [ - 'type' => 'log', - 'msg' => $current_uri . $time_str . $memory_str . $file_load, - ]); - - $info = ''; - foreach ($log as $line) { - $info .= '[' . $line['type'] . '] ' . $line['msg'] . "\r\n"; + $info = '[ log ] ' . $current_uri . $time_str . $memory_str . $file_load . "\r\n"; + foreach ($log as $type => $val) { + foreach ($val as $msg) { + $info .= '[ ' . $type . ' ] ' . $msg . "\r\n"; + } } $logstr = "[{$now}] {$_SERVER['SERVER_ADDR']} {$_SERVER['REMOTE_ADDR']} {$_SERVER['REQUEST_URI']}\r\n{$info}\r\n"; diff --git a/library/think/log/driver/Socket.php b/library/think/log/driver/Socket.php index cd27086c..a4942a9c 100644 --- a/library/think/log/driver/Socket.php +++ b/library/think/log/driver/Socket.php @@ -78,39 +78,57 @@ class Socket } else { $current_uri = "cmd:" . implode(' ', $_SERVER['argv']); } - array_unshift($logs, [ + // 基本信息 + $trace[] = [ 'type' => 'group', 'msg' => $current_uri . $time_str . $memory_str . $file_load, 'css' => $this->css['page'], - ]); - - $logs[] = [ - 'type' => 'groupCollapsed', - 'msg' => 'included_files', - 'css' => '', - ]; - $logs[] = [ - 'type' => 'log', - 'msg' => implode("\n", get_included_files()), - 'css' => '', - ]; - $logs[] = [ - 'type' => 'groupEnd', - 'msg' => '', - 'css' => '', ]; - $logs[] = [ - 'type' => 'groupEnd', - 'msg' => '', - 'css' => '', - ]; - - foreach ($logs as &$log) { - if (in_array($log['type'], ['sql', 'notice', 'debug', 'info'])) { - $log['type'] = 'log'; + foreach ($logs as $type => $val) { + $trace[] = [ + 'type' => 'groupCollapsed', + 'msg' => '[ ' . $type . ' ]', + 'css' => isset($this->css[$type]) ? $this->css[$type] : '', + ]; + foreach ($val as $msg) { + $trace[] = [ + 'type' => 'log', + 'msg' => $msg, + 'css' => '', + ]; } + $trace[] = [ + 'type' => 'groupEnd', + 'msg' => '', + 'css' => '', + ]; } + + if ($this->config['show_included_files']) { + $trace[] = [ + 'type' => 'groupCollapsed', + 'msg' => 'included_files', + 'css' => '', + ]; + $trace[] = [ + 'type' => 'log', + 'msg' => implode("\n", get_included_files()), + 'css' => '', + ]; + $trace[] = [ + 'type' => 'groupEnd', + 'msg' => '', + 'css' => '', + ]; + } + + $trace[] = [ + 'type' => 'groupEnd', + 'msg' => '', + 'css' => '', + ]; + $tabid = $this->getClientArg('tabid'); if (!$client_id = $this->getClientArg('client_id')) { $client_id = ''; @@ -120,10 +138,10 @@ class Socket //强制推送到多个client_id foreach ($this->allowForceClientIds as $force_client_id) { $client_id = $force_client_id; - $this->sendToClient($tabid, $client_id, $logs, $force_client_id); + $this->sendToClient($tabid, $client_id, $trace, $force_client_id); } } else { - $this->sendToClient($tabid, $client_id, $logs, ''); + $this->sendToClient($tabid, $client_id, $trace, ''); } return true; } diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index dd640e6a..3471f92b 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -70,8 +70,10 @@ class Trace // 获取调试日志 $debug = []; - foreach ($log as $line) { - $debug[$line['type']][] = $line['msg']; + foreach ($log as $type => $val) { + foreach ($val as $msg) { + $debug[$type][] = $msg; + } } // 页面Trace信息 From 936b1e20e951e4d11efbe1f5fa9d0c0bb4addcaf Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 14:29:11 +0800 Subject: [PATCH 291/670] =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/thinkphp/library/think/log/driver/fileTest.php | 2 +- tests/thinkphp/library/think/logTest.php | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/thinkphp/library/think/log/driver/fileTest.php b/tests/thinkphp/library/think/log/driver/fileTest.php index 168ef81a..3453c09b 100644 --- a/tests/thinkphp/library/think/log/driver/fileTest.php +++ b/tests/thinkphp/library/think/log/driver/fileTest.php @@ -29,6 +29,6 @@ class fileTest extends \PHPUnit_Framework_TestCase Log::record($record_msg, 'notice'); $logs = Log::getLog(); - $this->assertNotFalse(array_search(['type' => 'notice', 'msg' => $record_msg], $logs)); + $this->assertNotFalse(array_search($record_msg, $logs['notice'])); } } diff --git a/tests/thinkphp/library/think/logTest.php b/tests/thinkphp/library/think/logTest.php index 3448b49e..6161f7d5 100644 --- a/tests/thinkphp/library/think/logTest.php +++ b/tests/thinkphp/library/think/logTest.php @@ -23,12 +23,12 @@ class logTest extends \PHPUnit_Framework_TestCase public function testRecord(){ Log::clear(); Log::record('test'); - $this->assertEquals([['type'=>'log','msg'=>'test']], Log::getLog()); + $this->assertEquals(['log'=>['test'], Log::getLog()); Log::record('hello','info'); - $this->assertEquals([['type'=>'log','msg'=>'test'],['type'=>'info','msg'=>'hello']], Log::getLog()); + $this->assertEquals(['log'=>['test'],'info'=>['hello']], Log::getLog()); Log::clear(); Log::info('test'); - $this->assertEquals([['type'=>'info','msg'=>'test']], Log::getLog()); + $this->assertEquals(['info'=>['test']], Log::getLog()); } public function testSave(){ From dc2fa954291f8c782ea48ed73ddef8d84c46a17d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 14:33:08 +0800 Subject: [PATCH 292/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/thinkphp/library/think/logTest.php | 27 +++++++++++++----------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/tests/thinkphp/library/think/logTest.php b/tests/thinkphp/library/think/logTest.php index 6161f7d5..554cf60d 100644 --- a/tests/thinkphp/library/think/logTest.php +++ b/tests/thinkphp/library/think/logTest.php @@ -20,29 +20,32 @@ use think\Log; class logTest extends \PHPUnit_Framework_TestCase { - public function testRecord(){ + 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()); + $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()); + $this->assertEquals(['info' => ['test']], Log::getLog()); } - public function testSave(){ - Log::init(['type'=>'test']); + public function testSave() + { + Log::init(['type' => 'test']); Log::clear(); Log::record('test'); - Log::record([1,2,3]); + Log::record([1, 2, 3]); $this->assertTrue(Log::save()); } - public function testWrite(){ - Log::init(['type'=>'test']); + public function testWrite() + { + Log::init(['type' => 'test']); Log::clear(); - $this->assertTrue(Log::write('hello','info')); - $this->assertTrue(Log::write([1,2,3],'log')); + $this->assertTrue(Log::write('hello', 'info')); + $this->assertTrue(Log::write([1, 2, 3], 'log')); } } From d3540cff5b7ff3c780f210d2746f9455d00f3a9e Mon Sep 17 00:00:00 2001 From: fangrenfu Date: Mon, 6 Jun 2016 15:21:08 +0800 Subject: [PATCH 293/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3mssql=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E5=92=8C=E6=9B=B4=E6=96=B0=E6=97=B6=E7=94=9F=E6=88=90?= =?UTF-8?q?=E8=AF=AD=E5=8F=A5=E7=9A=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 带order参数查询时,取值错误,取的$order[0]内容是第一个字母r。 生成update语句时,ORDER应该替换成空(MSSQL的update语句中不支持order) --- library/think/db/builder/Sqlsrv.php | 34 ++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/library/think/db/builder/Sqlsrv.php b/library/think/db/builder/Sqlsrv.php index ef4a2e85..40c6ef3e 100644 --- a/library/think/db/builder/Sqlsrv.php +++ b/library/think/db/builder/Sqlsrv.php @@ -28,7 +28,7 @@ class Sqlsrv extends Builder */ protected function parseOrder($order) { - return !empty($order) ? ' ORDER BY ' . $order[0] : ' ORDER BY rand()'; + return !empty($order) ? ' ORDER BY ' . $order : ' ORDER BY rand()'; } /** @@ -76,5 +76,37 @@ class Sqlsrv extends Builder } return 'WHERE ' . $limitStr; } + /** + * 生成update SQL + * @access public + * @param array $fields 数据 + * @param array $options 表达式 + * @return string + */ + public function update($data, $options) + { + $table = $this->parseTable($options['table']); + $data = $this->parseData($data, $options); + if (empty($data)) { + return ''; + } + foreach ($data as $key => $val) { + $set[] = $key . '=' . $val; + } + $sql = 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['table']), + '', + $this->parseLimit($options['limit']), + $this->parseLimit($options['lock']), + $this->parseComment($options['comment']), + ], $this->updateSql); + + return $sql; + } } From 96999f04ac99d8a3b12024db11f8a7d2f4e00b9b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 15:32:24 +0800 Subject: [PATCH 294/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BSqlsrv=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/builder/Sqlsrv.php | 33 +---------------------------- 1 file changed, 1 insertion(+), 32 deletions(-) diff --git a/library/think/db/builder/Sqlsrv.php b/library/think/db/builder/Sqlsrv.php index 40c6ef3e..0bbb130d 100644 --- a/library/think/db/builder/Sqlsrv.php +++ b/library/think/db/builder/Sqlsrv.php @@ -19,6 +19,7 @@ use think\db\Builder; 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 $updateSql = 'UPDATE %TABLE% SET %SET% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; /** * order分析 @@ -76,37 +77,5 @@ class Sqlsrv extends Builder } return 'WHERE ' . $limitStr; } - /** - * 生成update SQL - * @access public - * @param array $fields 数据 - * @param array $options 表达式 - * @return string - */ - public function update($data, $options) - { - $table = $this->parseTable($options['table']); - $data = $this->parseData($data, $options); - if (empty($data)) { - return ''; - } - foreach ($data as $key => $val) { - $set[] = $key . '=' . $val; - } - $sql = 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['table']), - '', - $this->parseLimit($options['limit']), - $this->parseLimit($options['lock']), - $this->parseComment($options['comment']), - ], $this->updateSql); - - return $sql; - } } From 37caffb6bc73a2b5865c829ced38a2e11cac1508 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 16:57:18 +0800 Subject: [PATCH 295/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0HTTP=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E7=9A=84=E9=87=8D=E5=AE=9A=E5=90=91=E9=A1=B5=E9=9D=A2?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=20=E5=A2=9E=E5=8A=A0=20http=5Fexception=5Fur?= =?UTF-8?q?l=20=E9=85=8D=E7=BD=AE=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/exception/Handle.php | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index 354c6596..a4737fc3 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -42,13 +42,13 @@ class Handle 'message' => $exception->getMessage(), 'code' => $this->getCode($exception), ]; - $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; + $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; } else { $data = [ 'code' => $exception->getCode(), 'message' => $exception->getMessage(), ]; - $log = "[{$data['code']}]{$data['message']}"; + $log = "[{$data['code']}]{$data['message']}"; } Log::record($log, 'error'); @@ -62,7 +62,6 @@ class Handle return true; } } - return false; } @@ -82,7 +81,7 @@ class Handle } /** - * @param $output + * @param Output $output * @param Exception $e */ public function renderForConsole(Output $output, Exception $e) @@ -92,15 +91,17 @@ class Handle /** * @param HttpException $e - * @return \think\Response + * @return Response */ protected function renderHttpException(HttpException $e) { $status = $e->getStatusCode(); - - //TODO 根据状态码自动输出错误页面 - - return $this->convertExceptionToResponse($e); + $error = Config::get('http_exception_url'); + if (!APP_DEBUG && !empty($error[$status])) { + return Response::create($error[$status], 'redirect')->send(); + } else { + return $this->convertExceptionToResponse($e); + } } /** From 29c8faf11881bb770db94be0f71bed4f98d848d9 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 17:32:18 +0800 Subject: [PATCH 296/670] =?UTF-8?q?=E6=97=A5=E5=BF=97Log=E7=B1=BB=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E6=97=A5=E5=BF=97=E5=86=99=E5=85=A5=E6=8E=88=E6=9D=83?= =?UTF-8?q?Key=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Log.php | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/library/think/Log.php b/library/think/Log.php index d3eda965..c20911e3 100644 --- a/library/think/Log.php +++ b/library/think/Log.php @@ -22,12 +22,16 @@ class Log // 日志信息 protected static $log = []; + // 配置参数 + protected static $config = []; // 日志类型 protected static $type = ['log', 'error', 'info', 'sql', 'notice', 'alert']; // 日志写入驱动 - protected static $driver = null; + protected static $driver; // 通知发送驱动 - protected static $alarm = null; + protected static $alarm; + // 当前日志授权key + protected static $key; /** * 日志初始化 @@ -35,8 +39,9 @@ class Log */ public static function init($config = []) { - $type = isset($config['type']) ? $config['type'] : 'File'; - $class = (!empty($config['namespace']) ? $config['namespace'] : '\\think\\log\\driver\\') . ucwords($type); + $type = isset($config['type']) ? $config['type'] : 'File'; + $class = (!empty($config['namespace']) ? $config['namespace'] : '\\think\\log\\driver\\') . ucwords($type); + self::$config = $config; unset($config['type']); self::$driver = new $class($config); // 记录初始化信息 @@ -89,6 +94,30 @@ class Log self::$log = []; } + /** + * 当前日志记录的授权key + * @param string $key 授权key + * @return void + */ + public static function key($key) + { + self::$key = $key; + } + + /** + * 检查日志写入权限 + * @param array $config 当前日志配置参数 + * @return bool + */ + public static function check($config) + { + + if (self::$key && !empty($config['allow_key']) && !in_array(self::$key, $config['allow_key'])) { + return false; + } + return true; + } + /** * 保存调试信息 * @return bool @@ -100,6 +129,10 @@ class Log self::init(Config::get('log')); } + if (!self::check(self::$config)) { + // 检测日志写入权限 + return false; + } $result = self::$driver->save(self::$log); if ($result) { From 3baf150ce131b538a8f0c70da70d308a51bda709 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 18:01:55 +0800 Subject: [PATCH 297/670] =?UTF-8?q?Query=E7=B1=BB=E5=A2=9E=E5=8A=A0connect?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E7=94=A8=E4=BA=8E=E5=88=87=E6=8D=A2=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index ce5267f5..fcd67bd3 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -95,6 +95,18 @@ class Query return $this->connection; } + /** + * 切换当前的数据库连接 + * @access public + * @param mixed $config + * @return $this + */ + public function connect($config) + { + $this->connection = Db::connect($config); + return $this; + } + /** * 指定默认的数据表名(不含前缀) * @access public From 2cb0f1ed4a32239c40547de2f4faee584b656911 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 18:29:33 +0800 Subject: [PATCH 298/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BLog=E7=B1=BB=E7=9A=84?= =?UTF-8?q?getLog=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E6=9F=90=E4=B8=AA=E7=B1=BB=E5=9E=8B=E7=9A=84=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Log.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/library/think/Log.php b/library/think/Log.php index c20911e3..65c2cd4c 100644 --- a/library/think/Log.php +++ b/library/think/Log.php @@ -63,12 +63,13 @@ class Log } /** - * 获取全部日志信息 + * 获取日志信息 + * @param string $type 信息类型 * @return array */ - public static function getLog() + public static function getLog($type = '') { - return self::$log; + return $type ? self::$log[$type] : self::$log; } /** From aa2e844b73d40d02c0d4800ac58a0646b3918e7a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 18:48:09 +0800 Subject: [PATCH 299/670] =?UTF-8?q?Connection=E7=B1=BB=E7=9A=84=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=BA=93=E8=BF=9E=E6=8E=A5=E5=8F=82=E6=95=B0=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0sql=5Fexplain=E9=85=8D=E7=BD=AE=20=E7=94=A8=E4=BA=8E?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E6=98=AF=E5=90=A6=E9=9C=80=E8=A6=81=E5=88=86?= =?UTF-8?q?=E6=9E=90SQL=E6=80=A7=E8=83=BD=20=E9=BB=98=E8=AE=A4=E5=85=B3?= =?UTF-8?q?=E9=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 31f3e1f0..b913c0df 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -102,6 +102,8 @@ abstract class Connection 'resultset_type' => Db::RESULTSET_ARRAY, // 自动写入时间戳字段 'auto_timestamp' => false, + // 是否需要进行SQL性能分析 + 'sql_explain' => false, ]; // PDO连接参数 @@ -743,7 +745,7 @@ abstract class Connection $log = $this->queryStr . ' [ RunTime:' . $runtime . 's ]'; $result = []; // SQL性能分析 - if (0 === stripos(trim($this->queryStr), 'select')) { + if ($this->config['sql_explain'] && 0 === stripos(trim($this->queryStr), 'select')) { $result = $this->getExplain($this->queryStr); } // SQL监听 From 174102836eca2a9504291793d21254a37733027c Mon Sep 17 00:00:00 2001 From: fangrenfu Date: Mon, 6 Jun 2016 22:40:25 +0800 Subject: [PATCH 300/670] =?UTF-8?q?=E4=BF=AE=E6=94=B9mssql=20=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E6=95=B0=E6=8D=AE=E6=97=B6=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 删除数据时不应该有ORDER,否则在MSSQL中会报错。 定义$deleteSql方式解决。 --- library/think/db/builder/Sqlsrv.php | 1 + 1 file changed, 1 insertion(+) diff --git a/library/think/db/builder/Sqlsrv.php b/library/think/db/builder/Sqlsrv.php index 0bbb130d..2851c473 100644 --- a/library/think/db/builder/Sqlsrv.php +++ b/library/think/db/builder/Sqlsrv.php @@ -20,6 +20,7 @@ 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 $updateSql = 'UPDATE %TABLE% SET %SET% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; + protected $deleteSql = 'DELETE FROM %TABLE% %USING% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; /** * order分析 From b06bee1b0a1e1860cfbcb0d090f211c2e23870b8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 6 Jun 2016 22:52:26 +0800 Subject: [PATCH 301/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E7=9A=84=E6=97=A5=E6=9C=9F=E7=9B=AE=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/File.php b/library/think/File.php index 580cb7dd..fc888b10 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -151,7 +151,7 @@ class File extends SplFileObject $savename = substr($sha1, 0, 2) . DS . substr($sha1, 2); break; case 'date': - $savename = date('Y-m-d') . DS . md5(microtime(true)); + $savename = date('Ymd') . DS . md5(microtime(true)); break; default: $savename = call_user_func($this->rule); From 71bcc1bb7be4c2a354cf84f55dd4e2bba758b547 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 7 Jun 2016 10:46:05 +0800 Subject: [PATCH 302/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Merge=E7=B1=BB=20?= =?UTF-8?q?=E6=94=B9=E8=BF=9BFile=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 1 + library/think/model/Merge.php | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/library/think/File.php b/library/think/File.php index fc888b10..9ce8f36e 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -106,6 +106,7 @@ class File extends SplFileObject return false; } + $path = rtrim($path, DS) . DS; // 文件保存命名规则 $savename = $this->getSaveName($savename); diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index b26c8494..c4903c59 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -145,13 +145,14 @@ class Merge extends Model * @param mixed $data 数据 * @param array $where 更新条件 * @param bool $getId 新增的时候是否获取id + * @param bool $replace 是否replace * @return mixed */ - public function save($data = [], $where = [], $getId = true) + public function save($data = [], $where = [], $getId = true, $replace = false) { if (!empty($data)) { // 数据自动验证 - if (!$this->validateData()) { + if (!$this->validateData($data)) { return false; } // 数据对象赋值 @@ -214,7 +215,7 @@ class Merge extends Model // 处理模型数据 $data = $this->parseData($this->name, $this->data); // 写入主表数据 - $result = $db->name($this->name)->strict(false)->insert($data); + $result = $db->name($this->name)->strict(false)->insert($data, $replace); if ($result) { $insertId = $db->getLastInsID(); // 写入外键数据 From 5988f36102face30f955d616df8b8fb052e814e9 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 7 Jun 2016 11:38:30 +0800 Subject: [PATCH 303/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84JSON=E7=B1=BB=E5=9E=8B=E8=BD=AC=E6=8D=A2=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E9=9D=9E=E6=95=B0=E7=BB=84=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 38a4935c..7f23f479 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -321,11 +321,12 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = json_encode($value, JSON_FORCE_OBJECT); } break; - case 'json': + case 'array': - if (is_array($value)) { - $value = json_encode($value, JSON_UNESCAPED_UNICODE); - } + $value = (array) $value; + case 'json': + $value = json_encode($value, JSON_UNESCAPED_UNICODE); + break; } return $value; From ae2824ced110087d3bf30d81a0adcfd21424d7fb Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 7 Jun 2016 11:52:23 +0800 Subject: [PATCH 304/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Bresponse=E5=8A=A9?= =?UTF-8?q?=E6=89=8B=E5=87=BD=E6=95=B0=20=E6=94=B9=E8=BF=9BResponse?= =?UTF-8?q?=E7=B1=BB=E7=9A=84header=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E6=89=B9=E9=87=8F=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 10 +++++----- library/think/Model.php | 2 -- library/think/Response.php | 10 +++++++--- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/helper.php b/helper.php index 18d8c86e..8e549b02 100644 --- a/helper.php +++ b/helper.php @@ -356,15 +356,15 @@ function request() } /** - * 创建Response对象实例 + * 创建普通 Response 对象实例 * @param mixed $data 输出数据 - * @param string $type 输出类型 - * @param array $options 参数 + * @param string $code 状态码 + * @param array $header 头信息 * @return Response */ -function response($data = [], $type = '', $options = []) +function response($data = [], $code = 200, $header = [], $type = 'html') { - return Response::create($data, $type, $options); + return Response::create($data, $type)->code($code)->header($header); } /** diff --git a/library/think/Model.php b/library/think/Model.php index 7f23f479..664caf3a 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -321,12 +321,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = json_encode($value, JSON_FORCE_OBJECT); } break; - case 'array': $value = (array) $value; case 'json': $value = json_encode($value, JSON_UNESCAPED_UNICODE); - break; } return $value; diff --git a/library/think/Response.php b/library/think/Response.php index d3d6d7eb..1feec722 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -216,13 +216,17 @@ class Response /** * 设置响应头 * @access public - * @param string $name 参数名 + * @param string|array $name 参数名 * @param string $value 参数值 * @return $this */ - public function header($name, $value) + public function header($name, $value = null) { - $this->header[$name] = $value; + if (is_array($name)) { + $this->header = $name; + } else { + $this->header[$name] = $value; + } return $this; } From 7a579ca60e270df7aaf23700f0c10048b84d352e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 7 Jun 2016 12:24:32 +0800 Subject: [PATCH 305/670] =?UTF-8?q?404=E5=BC=82=E5=B8=B8=E8=B7=B3=E8=BD=AC?= =?UTF-8?q?URL=E9=85=8D=E7=BD=AE=E5=8F=82=E6=95=B0=20=E6=94=B9=E4=B8=BA=20?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=E6=A8=A1=E6=9D=BF=E5=9C=B0=E5=9D=80=E5=8F=82?= =?UTF-8?q?=E6=95=B0=20http=5Fexception=5Ftemplate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 2 +- library/think/exception/Handle.php | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/library/think/Response.php b/library/think/Response.php index 1feec722..3a2c9034 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -223,7 +223,7 @@ class Response public function header($name, $value = null) { if (is_array($name)) { - $this->header = $name; + $this->header = array_merge($this->header, $name); } else { $this->header[$name] = $value; } diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index a4737fc3..1a2dbc61 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -95,10 +95,10 @@ class Handle */ protected function renderHttpException(HttpException $e) { - $status = $e->getStatusCode(); - $error = Config::get('http_exception_url'); - if (!APP_DEBUG && !empty($error[$status])) { - return Response::create($error[$status], 'redirect')->send(); + $status = $e->getStatusCode(); + $template = Config::get('http_exception_template'); + if (!APP_DEBUG && !empty($template[$status])) { + return Response::create($template[$status], 'view')->vars(['e' => $e])->send(); } else { return $this->convertExceptionToResponse($e); } From ee7ef63c001820775d4867a96601d85dd1fde217 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 7 Jun 2016 16:09:06 +0800 Subject: [PATCH 306/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= =?UTF-8?q?=E7=9A=84after=5Fbehavior=E5=92=8Cbefore=5Fbehavior=E8=A1=8C?= =?UTF-8?q?=E4=B8=BA=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 4 ++-- library/think/Session.php | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 19467985..c7ef23ff 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -757,7 +757,7 @@ class Route || (isset($option['ext']) && false === stripos($option['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['before_behavior']) && false === Hook::exec($option['before_behavior'], '', $url)) // 行为检测 || (!empty($option['callback']) && is_callable($option['callback']) && false === call_user_func($option['callback'])) // 自定义检测 ) { return false; @@ -810,7 +810,7 @@ class Route if ($option['after_behavior'] instanceof \Closure) { $result = call_user_func_array($option['after_behavior'], [$route]); } else { - $result = Hook::exec($option['after_behavior'], $route); + $result = Hook::exec($option['after_behavior'], '', $route); } // 路由规则重定向 if ($result instanceof Response) { diff --git a/library/think/Session.php b/library/think/Session.php index 49ecb024..17212b89 100644 --- a/library/think/Session.php +++ b/library/think/Session.php @@ -245,11 +245,12 @@ class Session /** * 重新生成session_id + * @param bool $delete 是否删除关联会话文件 * @return void */ - private static function regenerate() + private static function regenerate($delete = false) { - session_regenerate_id(); + session_regenerate_id($delete); } /** From 29bf26fd116efef65e259c6c3a344e645ec9105c Mon Sep 17 00:00:00 2001 From: ZoaChou Date: Tue, 7 Jun 2016 16:47:05 +0800 Subject: [PATCH 307/670] Fix #113 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 判断操作是否合法前先定义$instance --- library/think/App.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/App.php b/library/think/App.php index 9c417d6b..32dcb426 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -272,13 +272,14 @@ class App Hook::listen('module_init', $request); try { + $instance = Loader::controller($controller, $config['url_controller_layer'], $config['use_controller_suffix'], $config['empty_controller']); + // 获取当前操作名 $action = $actionName . $config['action_suffix']; if (!preg_match('/^[A-Za-z](\w)*$/', $action)) { // 非法操作 throw new \ReflectionException('illegal action name :' . $actionName); } - $instance = Loader::controller($controller, $config['url_controller_layer'], $config['use_controller_suffix'], $config['empty_controller']); // 执行操作方法 $call = [$instance, $action]; From 451e7f0dda257c924e6fad6585655927c838aabf Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 7 Jun 2016 17:05:01 +0800 Subject: [PATCH 308/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BInput=E7=B1=BB?= =?UTF-8?q?=E5=92=8CRequest=E7=B1=BB=E7=9A=84session=E8=8E=B7=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Input.php | 6 ++---- library/think/Request.php | 6 ++---- tests/thinkphp/library/think/loaderTest.php | 2 -- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/library/think/Input.php b/library/think/Input.php index 96b7e90e..15e8f880 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -13,6 +13,7 @@ namespace think; use think\Config; use think\File; +use think\Session; class Input { @@ -129,10 +130,7 @@ class Input */ public static function session($name = '', $default = null, $filter = null, $merge = false) { - if (PHP_SESSION_DISABLED == session_status()) { - session_start(); - } - return self::data($_SESSION, $name, $default, $filter, $merge); + return self::data(Session::get(), $name, $default, $filter, $merge); } /** diff --git a/library/think/Request.php b/library/think/Request.php index a87e7848..f079fcbd 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -13,6 +13,7 @@ namespace think; use think\Config; use think\Input; +use think\Session; class Request { @@ -632,10 +633,7 @@ class Request */ public function session($name = '') { - if (PHP_SESSION_DISABLED == session_status()) { - session_start(); - } - return Input::data($this->session ?: $_SESSION, $name); + return Input::data($this->session ?: Session::get(), $name); } /** diff --git a/tests/thinkphp/library/think/loaderTest.php b/tests/thinkphp/library/think/loaderTest.php index 0f1a1a2c..60d1b441 100644 --- a/tests/thinkphp/library/think/loaderTest.php +++ b/tests/thinkphp/library/think/loaderTest.php @@ -23,8 +23,6 @@ class loaderTest extends \PHPUnit_Framework_TestCase public function testAutoload() { - $this->assertEquals(true, Loader::autoload('think\Session')); - //$this->assertEquals(false, Loader::autoload('think\COOKIE')); $this->assertEquals(false, Loader::autoload('\think\Url')); $this->assertEquals(false, Loader::autoload('think\Test')); $this->assertEquals(false, Loader::autoload('my\HelloTest')); From 0b2359e856f1d4c902a0b1e70fd906be8a584f87 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 7 Jun 2016 18:46:07 +0800 Subject: [PATCH 309/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E5=88=B0=E7=B1=BB=E7=9A=84=E6=96=B9=E6=B3=95=E7=9A=84=E5=9C=B0?= =?UTF-8?q?=E5=9D=80=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 3 ++- library/think/exception/Handle.php | 5 ++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index c7ef23ff..bd36215b 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -1041,7 +1041,8 @@ class Route $result = ['type' => 'redirect', 'url' => $url, 'status' => (is_array($route) && isset($route[1])) ? $route[1] : 301]; } elseif (0 === strpos($url, '\\')) { // 路由到方法 - $result = ['type' => 'method', 'method' => is_array($route) ? [$url, $route[1]] : $url, 'params' => $matches]; + $method = strpos($url, '@') ? explode('@', $url) : $url; + $result = ['type' => 'method', 'method' => $method, 'params' => $matches]; } elseif (0 === strpos($url, '@')) { // 路由到控制器 $result = ['type' => 'controller', 'controller' => substr($url, 1), 'params' => $matches]; diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index 1a2dbc61..0946b941 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -145,6 +145,7 @@ class Handle // 不显示详细错误信息 $data['message'] = Config::get('error_message'); } + //保留一层 while (ob_get_level() > 1) { ob_end_clean(); @@ -154,8 +155,7 @@ class Handle extract($data); include Config::get('exception_tmpl'); // 获取并清空缓存 - $content = ob_get_clean(); - + $content = ob_get_clean(); $response = new Response($content, 'html'); if ($exception instanceof HttpException) { @@ -167,7 +167,6 @@ class Handle $statusCode = 500; } $response->code($statusCode); - return $response; } From 36a0f4456d9f1fd1fbc4c0d8fb1672743c4ca646 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 7 Jun 2016 21:16:12 +0800 Subject: [PATCH 310/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Merge=E7=B1=BB?= =?UTF-8?q?=E7=9A=84delete=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Merge.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index c4903c59..5672ebc0 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -254,7 +254,7 @@ class Merge extends Model return false; } - $db = $this->query; + $db = $this->db(); $db->startTrans('merge_delete_' . $this->name); try { $result = $db->delete($this->data); From a7f9fa3603bb6a3b65be1f2ab186f89d39d23524 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 7 Jun 2016 22:26:03 +0800 Subject: [PATCH 311/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Cache.php | 2 +- library/think/Controller.php | 2 +- library/think/Template.php | 2 +- library/think/Validate.php | 2 +- library/think/view/driver/Think.php | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/library/think/Cache.php b/library/think/Cache.php index e541dbe3..3dccefb0 100644 --- a/library/think/Cache.php +++ b/library/think/Cache.php @@ -22,7 +22,7 @@ class Cache * @var object * @access protected */ - protected static $handler = null; + protected static $handler; /** * 连接缓存 diff --git a/library/think/Controller.php b/library/think/Controller.php index 0fc04c49..234989e5 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -22,7 +22,7 @@ class Controller use \traits\controller\Jump; // 视图类实例 - protected $view = null; + protected $view; // Request实例 protected $request; // 验证失败是否抛出异常 diff --git a/library/think/Template.php b/library/think/Template.php index e5430707..f13b5f96 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -52,7 +52,7 @@ class Template private $literal = []; private $includeFile = []; // 记录所有模板包含的文件路径及更新时间 - protected $storage = null; + protected $storage; /** * 架构函数 diff --git a/library/think/Validate.php b/library/think/Validate.php index 69081dab..6b52c6c4 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -18,7 +18,7 @@ use think\Request; class Validate { // 实例 - protected static $instance = null; + protected static $instance; // 自定义的验证类型 protected static $type = []; diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 10ef587d..00bfbccc 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -19,7 +19,7 @@ use think\Template; class Think { // 模板引擎实例 - private $template = null; + private $template; // 模板引擎参数 protected $config = [ // 模板起始路径 From 27bd97691645a57ed0131dffd6c93d3d38afb721 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 8 Jun 2016 13:53:49 +0800 Subject: [PATCH 312/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= =?UTF-8?q?=E7=9A=84parseUrlParams=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 2 +- library/think/Route.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 32dcb426..e7deb066 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -273,7 +273,7 @@ class App try { $instance = Loader::controller($controller, $config['url_controller_layer'], $config['use_controller_suffix'], $config['empty_controller']); - + // 获取当前操作名 $action = $actionName . $config['action_suffix']; if (!preg_match('/^[A-Za-z](\w)*$/', $action)) { diff --git a/library/think/Route.php b/library/think/Route.php index bd36215b..53cefe43 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -1068,7 +1068,7 @@ class Route * @param array $var 变量 * @return void */ - private static function parseUrlParams($url, $var) + private static function parseUrlParams($url, $var = []) { if ($url) { if (Config::get('url_param_type')) { From 0b16a5c5a387fda701c8cda1bcc2f526e7ccbf8a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 8 Jun 2016 17:50:54 +0800 Subject: [PATCH 313/670] =?UTF-8?q?Route=E7=B1=BB=E5=8E=9F=E6=9D=A5?= =?UTF-8?q?=E7=9A=84alias=E6=96=B9=E6=B3=95=E6=9B=B4=E5=90=8D=E4=B8=BAcont?= =?UTF-8?q?roller=EF=BC=8C=E8=B7=AF=E7=94=B1=E5=A2=9E=E5=8A=A0=E5=88=AB?= =?UTF-8?q?=E5=90=8D=E6=96=B9=E6=B3=95=20alias=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=88=AB=E5=90=8D=E7=AE=80=E5=8C=96=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E5=AE=9A=E4=B9=89=EF=BC=8C=E4=BE=8B=E5=A6=82=EF=BC=9A?= =?UTF-8?q?=20//=20=E4=BD=BF=E7=94=A8=20user=20=E8=B7=AF=E7=94=B1=E5=88=AB?= =?UTF-8?q?=E5=90=8D=E6=8C=87=E5=90=91=20index=E6=A8=A1=E5=9D=97=E7=9A=84u?= =?UTF-8?q?ser=E6=8E=A7=E5=88=B6=E5=99=A8=20Route::alias('user','index/use?= =?UTF-8?q?r');?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 142 ++++++++++++++++++--- tests/thinkphp/library/think/routeTest.php | 2 +- 2 files changed, 123 insertions(+), 21 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 53cefe43..d2a708ec 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -61,7 +61,10 @@ class Route private static $bind = []; // 当前分组 private static $group; + // 当前参数 private static $option = []; + // 路由别名 + private static $alias = []; /** * 注册或者获取URL映射规则 @@ -148,21 +151,31 @@ class Route self::domain($rule['__domain__']); unset($rule['__domain__']); } + // 检查变量规则 if (isset($rule['__pattern__'])) { self::pattern($rule['__pattern__']); unset($rule['__pattern__']); } + // 检查路由映射 if (isset($rule['__map__'])) { self::map($rule['__map__']); unset($rule['__map__']); } + + // 检查路由别名 + if (isset($rule['__alias__'])) { + self::alias($rule['__alias__']); + unset($rule['__alias__']); + } + // 检查资源路由 if (isset($rule['__rest__'])) { self::resource($rule['__rest__']); unset($rule['__rest__']); } + $type = strtoupper($type); foreach ($rule as $key => $val) { if (is_numeric($key)) { @@ -413,7 +426,7 @@ class Route } /** - * 注册别名路由 + * 注册控制器路由 操作方法对应不同的请求后缀 * @access public * @param string $rule 路由规则 * @param string $route 路由地址 @@ -421,13 +434,29 @@ class Route * @param array $pattern 变量规则 * @return void */ - public static function alias($rule, $route = '', $option = [], $pattern = []) + public static function controller($rule, $route = '', $option = [], $pattern = []) { foreach (self::$methodPrefix as $type => $val) { self::$type($rule . '/:action', $route . '/' . $val . ':action', $option, $pattern); } } + /** + * 注册别名路由 + * @access public + * @param string|array $rule 路由别名 + * @param string $route 别名对应的路由地址 + * @return void + */ + public static function alias($rule, $route = '') + { + if (is_array($rule)) { + self::$alias[$rule] = array_merge(self::$alias, $alias); + } else { + self::$alias[$rule] = $route; + } + } + /** * 设置不同请求类型下面的方法前缀 * @access public @@ -590,21 +619,32 @@ class Route */ public static function check($request, $url, $depr = '/', $checkDomain = false) { - // 检测域名部署 - if ($checkDomain) { - self::checkDomain($request); - } - // 分隔符替换 确保路由定义使用统一的分隔符 if ('/' != $depr) { $url = str_replace($depr, '/', $url); } if (isset(self::$map[$url])) { - // URL映射 + // URL映射(完整静态URL匹配) return self::parseUrl(self::$map[$url], $depr); } + if (strpos($url, '/') && isset(self::$alias[strstr($url, '/', true)])) { + // 路由别名 + $array = explode('/', $url, 2); + $rule = self::$alias[$array[0]]; + if (0 === strpos($rule, '\\')) { + // 路由到类 + return self::bindToClass($array[1], substr($rule, 1)); + } elseif (0 === strpos($url, '@')) { + // 路由到控制器类 + return self::bindToController($array[1], substr($rule, 1)); + } else { + // 路由到模块/控制器 + return self::bindToModule($array[1], $rule); + } + } + // 获取当前请求类型的路由规则 $rules = self::$rules[$request->method()]; @@ -613,6 +653,10 @@ class Route $rules = array_merge(self::$rules['*'], $rules); } + // 检测域名部署 + if ($checkDomain) { + self::checkDomain($request); + } // 检测URL绑定 $return = self::checkUrlBind($url, $rules); if ($return) { @@ -713,20 +757,10 @@ class Route switch (self::$bind['type']) { case 'class': // 绑定到类 - $array = explode('/', $url, 2); - if (!empty($array[1])) { - self::parseUrlParams($array[1]); - } - return ['type' => 'method', 'method' => [self::$bind['class'], $array[0] ?: Config::get('default_action')], 'params' => []]; + return self::bindToClass($url, self::$bind['class']); case 'namespace': // 绑定到命名空间 - $array = explode('/', $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' => [self::$bind['namespace'] . '\\' . $class, $method], 'params' => []]; + return self::bindToNamespace($url, self::$bind['namespace']); case 'module': // 如果有模块/控制器绑定 针对路由到 模块/控制器 有效 $url = self::$bind['module'] . '/' . $url; @@ -742,6 +776,74 @@ class Route return false; } + /** + * 绑定到类 + * @access public + * @param string $url URL地址 + * @param string $class 类名(带命名空间) + * @return array + */ + public static function bindToClass($url, $class) + { + $array = explode('/', $url, 2); + if (!empty($array[1])) { + self::parseUrlParams($array[1]); + } + return ['type' => 'method', 'method' => [$class, $array[0] ?: Config::get('default_action')], 'params' => []]; + } + + /** + * 绑定到命名空间 + * @access public + * @param string $url URL地址 + * @param string $namespace 命名空间 + * @return array + */ + public static function bindToNamespace($url, $namespace) + { + $array = explode('/', $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], 'params' => []]; + } + + /** + * 绑定到控制器类 + * @access public + * @param string $url URL地址 + * @param string $module 模块名 + * @return array + */ + public static function bindToController($url, $controller) + { + $array = explode('/', $url, 2); + $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); + if (!empty($array[1])) { + self::parseUrlParams($array[1]); + } + return ['type' => 'method', 'method' => [$controller, $action], 'params' => []]; + } + + /** + * 绑定到模块/控制器 + * @access public + * @param string $url URL地址 + * @param string $class 控制器类名(带命名空间) + * @return array + */ + public static function bindToModule($url, $controller) + { + $array = explode('/', $url, 2); + $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); + if (!empty($array[1])) { + self::parseUrlParams($array[1]); + } + return ['type' => 'module', 'module' => $controller . '/' . $action, 'params' => []]; + } + /** * 路由参数有效性检查 * @access private diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index 242b4a4a..5c9e5dd4 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -138,7 +138,7 @@ class routeTest extends \PHPUnit_Framework_TestCase { $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+']); + Route::get('info/:name', '\app\index\model\Info@getInfo', [], ['name' => '\w+']); $this->assertEquals(['type' => 'method', 'method' => '\app\index\service\User::get', 'params' => ['name' => 'thinkphp']], Route::check($request, 'user/thinkphp')); $this->assertEquals(['type' => 'method', 'method' => ['\app\index\model\Info', 'getInfo'], 'params' => ['name' => 'thinkphp']], Route::check($request, 'info/thinkphp')); } From 6de814bd5471fcc23fe2997a93b85f2b458b0f4e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 8 Jun 2016 18:30:03 +0800 Subject: [PATCH 314/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BController=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/library/think/Controller.php b/library/think/Controller.php index 234989e5..a79a2335 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -42,6 +42,9 @@ class Controller */ public function __construct(Request $request = null) { + if (is_null($request)) { + $request = Request::instance(); + } $this->view = View::instance(Config::get('template'), Config::get('view_replace_str')); $this->request = $request; From c4edb2e426619e6609a674380db0adf75c44a5b3 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 9 Jun 2016 08:50:56 +0800 Subject: [PATCH 315/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB=20?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E5=88=AB=E5=90=8D=E6=94=AF=E6=8C=81=E6=9D=A1?= =?UTF-8?q?=E4=BB=B6=E6=A3=80=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index d2a708ec..a4e98504 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -445,15 +445,16 @@ class Route * 注册别名路由 * @access public * @param string|array $rule 路由别名 - * @param string $route 别名对应的路由地址 + * @param string $route 路由地址 + * @param array $option 路由参数 * @return void */ - public static function alias($rule, $route = '') + public static function alias($rule, $route = '', $option = []) { if (is_array($rule)) { - self::$alias[$rule] = array_merge(self::$alias, $alias); + self::$alias = array_merge(self::$alias, $rule); } else { - self::$alias[$rule] = $route; + self::$alias[$rule] = $option ? [$route, $option] : $route; } } @@ -632,8 +633,17 @@ class Route if (strpos($url, '/') && isset(self::$alias[strstr($url, '/', true)])) { // 路由别名 $array = explode('/', $url, 2); - $rule = self::$alias[$array[0]]; - if (0 === strpos($rule, '\\')) { + $item = self::$alias[$array[0]]; + + if (is_array($item)) { + list($rule, $option) = $item; + } else { + $rule = $item; + } + // 参数有效性检查 + if (isset($option) && !self::checkOption($option, $url, $request)) { + // 路由不匹配 + } elseif (0 === strpos($rule, '\\')) { // 路由到类 return self::bindToClass($array[1], substr($rule, 1)); } elseif (0 === strpos($url, '@')) { From b50bcd52988353afaba5c3cb5b37184206c0d82b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 9 Jun 2016 09:00:42 +0800 Subject: [PATCH 316/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB?= =?UTF-8?q?=E7=9A=84alias=E6=96=B9=E6=B3=95=20=E6=94=B9=E8=BF=9BUrl?= =?UTF-8?q?=E7=B1=BB=E7=94=9F=E6=88=90=E6=94=AF=E6=8C=81=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E5=88=AB=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 6 ++++-- library/think/Url.php | 29 ++++++++++++++++++----------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index a4e98504..135d5319 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -449,9 +449,11 @@ class Route * @param array $option 路由参数 * @return void */ - public static function alias($rule, $route = '', $option = []) + public static function alias($rule = null, $route = '', $option = []) { - if (is_array($rule)) { + if (is_null($rule)) { + return self::$alias; + } elseif (is_array($rule)) { self::$alias = array_merge(self::$alias, $rule); } else { self::$alias[$rule] = $option ? [$route, $option] : $route; diff --git a/library/think/Url.php b/library/think/Url.php index 998a1f64..0df14419 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -264,11 +264,11 @@ class Url return false; } - // 生成路由别名并缓存 + // 生成路由映射并缓存 private static function getRouteAlias() { - if ($alias = Cache::get('think_route_alias')) { - return $alias; + if ($item = Cache::get('think_route_map')) { + return $item; } // 获取路由定义 $rules = Route::getRules(); @@ -290,8 +290,8 @@ class Url list($route, $str) = explode('?', $route, 2); parse_str($str, $param); } - $var = self::parseVar($rule . '/' . $key); - $alias[$route][] = [$rule . '/' . $key, $var, $param]; + $var = self::parseVar($rule . '/' . $key); + $item[$route][] = [$rule . '/' . $key, $var, $param]; } } else { $route = $val['route']; @@ -304,8 +304,8 @@ class Url list($route, $str) = explode('?', $route, 2); parse_str($str, $param); } - $var = self::parseVar($rule); - $alias[$route][] = [$rule, $var, $param]; + $var = self::parseVar($rule); + $item[$route][] = [$rule, $var, $param]; } } @@ -317,10 +317,17 @@ class Url list($route, $str) = explode('?', $route, 2); parse_str($str, $param); } - $alias[$route][] = [$rule, [], $param]; + $item[$route][] = [$rule, [], $param]; } - !APP_DEBUG && Cache::set('think_route_alias', $alias); - return $alias; + + // 检测路由别名 + $alias = Route::alias(); + foreach ($alias as $rule => $route) { + $route = is_array($route) ? $route[0] : $route; + $item[$route][] = [$rule, [], []]; + } + !APP_DEBUG && Cache::set('think_route_map', $item); + return $item; } // 分析路由规则中的变量 @@ -363,6 +370,6 @@ class Url // 清空路由别名缓存 public static function clearAliasCache() { - Cache::rm('think_route_alias'); + Cache::rm('think_route_map'); } } From 541b765eb4322d347b695f96c307b97ac8d11937 Mon Sep 17 00:00:00 2001 From: fangrenfu Date: Thu, 9 Jun 2016 09:32:40 +0800 Subject: [PATCH 317/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3selectInsert=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E5=AD=97=E6=AE=B5=E6=95=B0=E4=B8=8D=E4=B8=80=E8=87=B4?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mssql中为实现排序增加了row_number列,导致在selectInsert方法中字段数不一致。 修正方法:定义selectInsertSql属性,重写selectInsert方法。 --- library/think/db/builder/Sqlsrv.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/library/think/db/builder/Sqlsrv.php b/library/think/db/builder/Sqlsrv.php index 2851c473..4010fe3c 100644 --- a/library/think/db/builder/Sqlsrv.php +++ b/library/think/db/builder/Sqlsrv.php @@ -19,6 +19,7 @@ use think\db\Builder; 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% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; protected $deleteSql = 'DELETE FROM %TABLE% %USING% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; @@ -78,5 +79,10 @@ class Sqlsrv extends Builder } return 'WHERE ' . $limitStr; } + public function selectInsert($fields, $table, $options) + { + $this->selectSql=$this->selectInsertSql; + return parent::selectInsert($fields, $table, $options); + } } From 3c57c610dc7387f929c5ca7b85fd54b4c8f08b9e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 9 Jun 2016 10:30:04 +0800 Subject: [PATCH 318/670] =?UTF-8?q?=E9=A2=84=E8=BD=BD=E5=85=A5=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E6=94=AF=E6=8C=81=E6=8C=87=E5=AE=9A=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index fcd67bd3..b1c50e13 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1377,17 +1377,33 @@ class Query $name = Loader::parseName(basename(str_replace('\\', '/', $currentModel))); $table = $this->getTable(); $alias = isset($info['alias'][$name]) ? $info['alias'][$name] : $name; - $this->table($table)->alias($alias)->field(true, false, $table, $alias); + $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); - $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['localKey'] . '=' . $joinAlias . '.' . $info['foreignKey'])->field(true, false, $joinTable, $joinAlias, $joinName . '__'); + $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['localKey'] . '=' . $joinAlias . '.' . $info['foreignKey']); 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, $joinName . '__'); } $i++; } elseif ($closure) { @@ -1399,6 +1415,22 @@ class Query return $this; } + /** + * 关联预加载中 获取关联指定字段值 + * example: + * Model::with(['relation' => function($query){ + * $query->withField("id,name"); + * }]) + * + * @param string | array $field 指定获取的字段 + * @return $this + */ + public function withField($field) + { + $this->options['with_field'] = $field; + return $this; + } + /** * 设置当前字段添加的表别名 * @access public From 399e7b45739a5e6a2de399f6eecf26406cf64363 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 9 Jun 2016 10:45:19 +0800 Subject: [PATCH 319/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Console?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/console/helper/Helper.php | 2 +- library/think/console/helper/Process.php | 4 ++-- library/think/console/helper/Question.php | 18 +++++++++--------- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/library/think/console/helper/Helper.php b/library/think/console/helper/Helper.php index 66be1891..7b327bdd 100644 --- a/library/think/console/helper/Helper.php +++ b/library/think/console/helper/Helper.php @@ -118,4 +118,4 @@ abstract class Helper return self::strlen($string); } -} \ No newline at end of file +} diff --git a/library/think/console/helper/Process.php b/library/think/console/helper/Process.php index 5aaeeff4..4252bfe3 100644 --- a/library/think/console/helper/Process.php +++ b/library/think/console/helper/Process.php @@ -12,8 +12,8 @@ namespace think\console\helper; use think\console\Output; +use think\Process as ThinkProcess; use think\process\Builder as ProcessBuilder; -use think\process as ThinkProcess; use think\process\exception\Failed as ProcessFailedException; class Process extends Helper @@ -115,4 +115,4 @@ class Process extends Helper { return 'process'; } -} \ No newline at end of file +} diff --git a/library/think/console/helper/Question.php b/library/think/console/helper/Question.php index 78416fbd..e1820834 100644 --- a/library/think/console/helper/Question.php +++ b/library/think/console/helper/Question.php @@ -11,16 +11,16 @@ namespace think\console\helper; +use think\console\helper\question\Choice as ChoiceQuestion; +use think\console\helper\question\Question as OutputQuestion; use think\console\Input; use think\console\Output; -use think\console\helper\question\Question as OutputQuestion; -use think\console\helper\question\Choice as ChoiceQuestion; use think\console\output\formatter\Style as OutputFormatterStyle; class Question extends Helper { - private $inputStream; + private $inputStream; private static $shell; private static $stty; @@ -138,7 +138,7 @@ class Question extends Helper if ($question instanceof ChoiceQuestion) { $width = max(array_map('strlen', array_keys($question->getChoices()))); - $messages = (array)$question->getQuestion(); + $messages = (array) $question->getQuestion(); foreach ($question->getChoices() as $key => $value) { $messages[] = sprintf(" [%-${width}s] %s", $key, $value); } @@ -199,7 +199,7 @@ class Question extends Helper $output->write("\033[1D"); } - if ($i === 0) { + if (0 === $i) { $ofs = -1; $matches = $autocomplete; $numMatches = count($matches); @@ -249,7 +249,7 @@ class Question extends Helper $ofs = 0; foreach ($autocomplete as $value) { - if (0 === strpos($value, $ret) && $i !== strlen($value)) { + if (0 === strpos($value, $ret) && strlen($value) !== $i) { $matches[$numMatches++] = $value; } } @@ -314,7 +314,7 @@ class Question extends Helper } if (false !== $shell = $this->getShell()) { - $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword'; + $readCmd = 'csh' === $shell ? 'set mypassword = $<' : 'read -r mypassword'; $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd); $value = rtrim(shell_exec($command)); $output->writeln(''); @@ -389,6 +389,6 @@ class Question extends Helper exec('stty 2>&1', $output, $exitcode); - return self::$stty = $exitcode === 0; + return self::$stty = 0 === $exitcode; } -} \ No newline at end of file +} From 34a08232aa1a69e214e639614979462c1e154abd Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 9 Jun 2016 17:19:13 +0800 Subject: [PATCH 320/670] =?UTF-8?q?=E4=B8=80=E5=AF=B9=E4=B8=80=E5=85=B3?= =?UTF-8?q?=E8=81=94=E5=AE=9A=E4=B9=89=E6=94=AF=E6=8C=81=E6=8C=87=E5=AE=9A?= =?UTF-8?q?=20join=E7=B1=BB=E5=9E=8B=20=E7=94=A8=E4=BA=8E=E9=A2=84?= =?UTF-8?q?=E8=BD=BD=E5=85=A5=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 10 ++++++---- library/think/db/Query.php | 2 +- library/think/model/Relation.php | 10 ++++++++-- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 664caf3a..d7f5644e 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -1093,15 +1093,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $foreignKey 关联外键 * @param string $localKey 关联主键 * @param array $alias 别名定义 + * @param string $joinType JOIN类型 * @return Relation */ - public function hasOne($model, $foreignKey = '', $localKey = '', $alias = []) + 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); + return $this->relation()->hasOne($model, $foreignKey, $localKey, $alias, $joinType); } /** @@ -1111,15 +1112,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param string $foreignKey 关联外键 * @param string $otherKey 关联主键 * @param array $alias 别名定义 + * @param string $joinType JOIN类型 * @return Relation */ - public function belongsTo($model, $foreignKey = '', $otherKey = '', $alias = []) + 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); + return $this->relation()->belongsTo($model, $foreignKey, $otherKey, $alias, $joinType); } /** diff --git a/library/think/db/Query.php b/library/think/db/Query.php index b1c50e13..141cd37f 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1391,7 +1391,7 @@ class Query $joinName = Loader::parseName(basename(str_replace('\\', '/', $info['model']))); $joinAlias = isset($info['alias'][$joinName]) ? $info['alias'][$joinName] : $joinName; $this->via($joinAlias); - $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['localKey'] . '=' . $joinAlias . '.' . $info['foreignKey']); + $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['localKey'] . '=' . $joinAlias . '.' . $info['foreignKey'], $info['joinType']); if ($closure) { // 执行闭包查询 call_user_func_array($closure, [ & $this]); diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index c32fe733..0d3f5aaf 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -41,6 +41,8 @@ class Relation protected $localKey; // 数据表别名 protected $alias; + // 当前关联的JOIN类型 + protected $joinType; /** * 架构函数 @@ -396,15 +398,17 @@ class Relation * @param string $foreignKey 关联外键 * @param string $localKey 关联主键 * @param array $alias 别名定义 + * @param string $joinType JOIN类型 * @return $this */ - public function hasOne($model, $foreignKey, $localKey, $alias) + public function hasOne($model, $foreignKey, $localKey, $alias = [], $joinType = 'INNER') { $this->type = self::HAS_ONE; $this->model = $model; $this->foreignKey = $foreignKey; $this->localKey = $localKey; $this->alias = $alias; + $this->joinType = $joinType; // 返回关联的模型对象 return $this; @@ -417,9 +421,10 @@ class Relation * @param string $foreignKey 关联外键 * @param string $otherKey 关联主键 * @param array $alias 别名定义 + * @param string $joinType JOIN类型 * @return $this */ - public function belongsTo($model, $foreignKey, $otherKey, $alias) + public function belongsTo($model, $foreignKey, $otherKey, $alias = [], $joinType = 'INNER') { // 记录当前关联信息 $this->type = self::BELONGS_TO; @@ -427,6 +432,7 @@ class Relation $this->foreignKey = $foreignKey; $this->localKey = $otherKey; $this->alias = $alias; + $this->joinType = $joinType; // 返回关联的模型对象 return $this; From 069673ea3f53103c11e57205d8f4ee55c390bd93 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 11 Jun 2016 09:50:55 +0800 Subject: [PATCH 321/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Relation=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getRelationInfo=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Relation.php | 1 + 1 file changed, 1 insertion(+) diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index 0d3f5aaf..f6cbecca 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -69,6 +69,7 @@ class Relation 'foreignKey' => $this->foreignKey, 'localKey' => $this->localKey, 'alias' => $this->alias, + 'joinType' => $this->joinType, ]; return $name ? $info[$name] : $info; } From 67a6f398c6b1210ce7111c2881f97c36864c3a1b Mon Sep 17 00:00:00 2001 From: jay <917647288@qq.com> Date: Sun, 12 Jun 2016 08:53:21 +0800 Subject: [PATCH 322/670] add Browser console log support --- library/think/log/driver/Browser.php | 78 ++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 library/think/log/driver/Browser.php diff --git a/library/think/log/driver/Browser.php b/library/think/log/driver/Browser.php new file mode 100644 index 00000000..1f8597de --- /dev/null +++ b/library/think/log/driver/Browser.php @@ -0,0 +1,78 @@ + 'File', + ]; + + // 实例化并传入参数 + public function __construct($config = []) + { + if (is_array($config)) { + $this->config = array_merge($this->config, $config); + } + } + + /** + * 日志写入接口 + * @access public + * @param array $log 日志信息 + * @return bool + */ + public function save(array $log = []) + { + $request = Request::instance(); + $type = $request->type(); + $type = config('default_return_type'); + //输出到控制台 + if(in_array($type, ['html', 'txt'])){ + $lines = []; + foreach ($log as $key => $l) { + $lines[] = $this->output($l['type'], $l['msg']); + } + $lines = implode(PHP_EOL, $lines); + $js = << +{$lines} + +JS; + echo $js; + }else{ + $other_save = $this->config['notview_save']; + // $other_save = "\think\log\driver\"".$other_save; + $other_save = 'think\log\driver\\'.$other_save; + $other_save_class = new $other_save(); + $other_save_class->save($log); + } + return true; + } + + public function output($type, $msg){ + // dump($type); + // dump($msg); + $msg = str_replace(PHP_EOL, '\n', $msg); + if(in_array($type, ['info', 'log', 'error', 'warn', 'debug'])){ + $style = ''; + if('error' == $type){ + $style = 'color:#F4006B;font-size:14px;'; + } + $line = "console.{$type}(\"%c{$msg}\", \"{$style}\");"; + }else{ + if('sql' == $type){ + $style = "color:#009bb4;"; + $line = "console.log(\"%c{$msg}\", \"{$style}\");"; + }else{ + $line = "alert(\"{$msg}\");"; + } + } + return $line; + } + +} From b5fa195ad6221f919482c6384e6969f6d8745263 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 11:21:38 +0800 Subject: [PATCH 323/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Controller=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 24 ++++++++++++------------ library/traits/controller/Jump.php | 18 +++++++++--------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/library/think/Controller.php b/library/think/Controller.php index a79a2335..a9dcd6cb 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -94,61 +94,61 @@ class Controller /** * 加载模板输出 - * @access public + * @access protected * @param string $template 模板文件名 * @param array $vars 模板输出变量 * @param array $replace 模板替换 * @param array $config 模板参数 * @return mixed */ - public function fetch($template = '', $vars = [], $replace = [], $config = []) + protected function fetch($template = '', $vars = [], $replace = [], $config = []) { return $this->view->fetch($template, $vars, $replace, $config); } /** * 渲染内容输出 - * @access public + * @access protected * @param string $content 模板内容 * @param array $vars 模板输出变量 * @param array $config 模板参数 * @return mixed */ - public function display($content = '', $vars = [], $config = []) + protected function display($content = '', $vars = [], $config = []) { return $this->view->display($content, $vars, $config); } /** * 模板变量赋值 - * @access public + * @access protected * @param mixed $name 要显示的模板变量 * @param mixed $value 变量的值 * @return void */ - public function assign($name, $value = '') + protected function assign($name, $value = '') { $this->view->assign($name, $value); } /** * 初始化模板引擎 - * @access public + * @access protected * @param array|string $engine 引擎参数 * @return void */ - public function engine($engine) + protected function engine($engine) { $this->view->engine($engine); } /** * 设置验证失败后是否抛出异常 - * @access public + * @access protected * @param bool $fail 是否抛出异常 * @return $this */ - public function failException($fail = true) + protected function failException($fail = true) { $this->failException = $fail; return $this; @@ -156,14 +156,14 @@ class Controller /** * 验证数据 - * @access public + * @access protected * @param array $data 数据 * @param string|array $validate 验证器名或者验证规则数组 * @param array $message 提示信息 * @param mixed $callback 回调方法(闭包) * @return true|string|array */ - public function validate($data, $validate, $message = [], $callback = null) + protected function validate($data, $validate, $message = [], $callback = null) { if (is_array($validate)) { $v = Loader::validate(); diff --git a/library/traits/controller/Jump.php b/library/traits/controller/Jump.php index 45e2e2dd..27b55c5d 100644 --- a/library/traits/controller/Jump.php +++ b/library/traits/controller/Jump.php @@ -25,14 +25,14 @@ trait Jump { /** * 操作成功跳转的快捷方法 - * @access public + * @access protected * @param mixed $msg 提示信息 * @param string $url 跳转的URL地址 * @param mixed $data 返回的数据 * @param integer $wait 跳转等待时间 * @return array */ - public function success($msg = '', $url = null, $data = '', $wait = 3) + protected function success($msg = '', $url = null, $data = '', $wait = 3) { $code = 1; if (is_numeric($msg)) { @@ -57,14 +57,14 @@ trait Jump /** * 操作错误跳转的快捷方法 - * @access public + * @access protected * @param mixed $msg 提示信息 * @param string $url 跳转的URL地址 * @param mixed $data 返回的数据 * @param integer $wait 跳转等待时间 * @return void */ - public function error($msg = '', $url = null, $data = '', $wait = 3) + protected function error($msg = '', $url = null, $data = '', $wait = 3) { $code = 0; if (is_numeric($msg)) { @@ -90,14 +90,14 @@ trait Jump /** * 返回封装后的API数据到客户端 - * @access public + * @access protected * @param mixed $data 要返回的数据 * @param integer $code 返回的code * @param mixed $msg 提示信息 * @param string $type 返回数据格式 * @return mixed */ - public function result($data, $code = 0, $msg = '', $type = '') + protected function result($data, $code = 0, $msg = '', $type = '') { return Response::create([], $type)->result($data, $code, $msg); } @@ -110,7 +110,7 @@ trait Jump * @param integer $code http code * @return void */ - public function redirect($url, $params = [], $code = 302) + protected function redirect($url, $params = [], $code = 302) { $response = new Redirect($url); if (is_integer($params)) { @@ -123,10 +123,10 @@ trait Jump /** * 获取当前的response 输出类型 - * @access public + * @access protected * @return string */ - public function getResponseType() + protected function getResponseType() { $isAjax = Request::instance()->isAjax(); return $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type'); From 75cfc95b38df4af413526fd2f7bf7ea59ae3fa19 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 11:36:14 +0800 Subject: [PATCH 324/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Controller=E7=B1=BB?= =?UTF-8?q?=E7=9A=84display=E6=96=B9=E6=B3=95=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/library/think/Controller.php b/library/think/Controller.php index a9dcd6cb..503f1884 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -111,12 +111,13 @@ class Controller * @access protected * @param string $content 模板内容 * @param array $vars 模板输出变量 + * @param array $replace 替换内容 * @param array $config 模板参数 * @return mixed */ - protected function display($content = '', $vars = [], $config = []) + protected function display($content = '', $vars = [], $replace = [], $config = []) { - return $this->view->display($content, $vars, $config); + return $this->view->display($content, $vars, $replace, $config); } /** From ccd1e2c2e7efe99e531dd26a55ec02ce3135ae1d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 12:08:47 +0800 Subject: [PATCH 325/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Query=E7=B1=BB?= =?UTF-8?q?=E7=9A=84with=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 141cd37f..eaa90e5d 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1391,11 +1391,16 @@ class Query $joinName = Loader::parseName(basename(str_replace('\\', '/', $info['model']))); $joinAlias = isset($info['alias'][$joinName]) ? $info['alias'][$joinName] : $joinName; $this->via($joinAlias); - $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['localKey'] . '=' . $joinAlias . '.' . $info['foreignKey'], $info['joinType']); + + 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']); + } + if ($closure) { // 执行闭包查询 call_user_func_array($closure, [ & $this]); - //指定获取关联的字段 //需要在 回调中 调方法 withField 方法,如 // $query->where(['id'=>1])->withField('id,name'); From 9023041e6b299db71f662b58c45e10d7885f68a5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 12:53:06 +0800 Subject: [PATCH 326/670] =?UTF-8?q?Query=E7=B1=BB=E5=A2=9E=E5=8A=A0findOrF?= =?UTF-8?q?ail=20selectOrFail=E5=BF=AB=E6=8D=B7=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index eaa90e5d..43cfd300 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1782,6 +1782,34 @@ class Query return $data; } + /** + * 查找多条记录 如果不存在则抛出异常 + * @access public + * @param array|string|Query|\Closure $data + * @return array|\PDOStatement|string|Model + * @throws DbException + * @throws Exception + * @throws PDOException + */ + public function selectOrFail($data=[]) + { + return $this->failException(true)->select($data); + } + + /** + * 查找单条记录 如果不存在则抛出异常 + * @access public + * @param array|string|Query|\Closure $data + * @return array|\PDOStatement|string|Model + * @throws DbException + * @throws Exception + * @throws PDOException + */ + public function findOrFail($data=[]) + { + return $this->failException(true)->find($data); + } + /** * 分批数据返回处理 * @access public From 659900ab914061c1616558ba43db47aa0472b057 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 14:06:36 +0800 Subject: [PATCH 327/670] =?UTF-8?q?Model=E7=B1=BB=E5=92=8CController?= =?UTF-8?q?=E7=B1=BB=E7=9A=84failException=E6=9B=B4=E6=94=B9=E4=B8=BA=20va?= =?UTF-8?q?lidateFailException=20=E9=81=BF=E5=85=8D=E5=92=8CQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84failException=E6=96=B9=E6=B3=95=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 2 +- library/think/Model.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Controller.php b/library/think/Controller.php index 503f1884..03af3da6 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -149,7 +149,7 @@ class Controller * @param bool $fail 是否抛出异常 * @return $this */ - protected function failException($fail = true) + protected function validateFailException($fail = true) { $this->failException = $fail; return $this; diff --git a/library/think/Model.php b/library/think/Model.php index d7f5644e..4815540d 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -740,7 +740,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param bool $fail 是否抛出异常 * @return $this */ - public function failException($fail = true) + public function validateFailException($fail = true) { $this->failException = $fail; return $this; From b10635e22e2381717086e7a56ba7954fe35326e9 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 16:35:42 +0800 Subject: [PATCH 328/670] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E7=B1=BB=E8=A7=84?= =?UTF-8?q?=E8=8C=83=20=E5=A2=9E=E5=8A=A0=E5=BC=82=E5=B8=B8=E7=B1=BB=20?= =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB=E7=9A=84value=E5=92=8Ccolumn?= =?UTF-8?q?=E7=9A=84=E7=BC=93=E5=AD=98=E5=86=B2=E7=AA=81=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 10 +-- library/think/Controller.php | 3 +- library/think/Exception.php | 4 - library/think/Input.php | 2 +- library/think/Loader.php | 14 ++-- library/think/Model.php | 3 +- library/think/Paginator.php | 4 +- library/think/Response.php | 4 +- library/think/Session.php | 4 +- library/think/Template.php | 4 +- library/think/Validate.php | 2 +- library/think/cache/driver/Apc.php | 2 +- library/think/cache/driver/Memcache.php | 4 +- library/think/cache/driver/Memcached.php | 2 +- library/think/cache/driver/Redis.php | 2 +- library/think/cache/driver/Redisd.php | 2 +- library/think/cache/driver/Sae.php | 2 +- library/think/cache/driver/Sqlite.php | 4 +- library/think/cache/driver/Wincache.php | 2 +- library/think/cache/driver/Xcache.php | 4 +- library/think/db/Connection.php | 8 +- .../think/{exception => db}/DbException.php | 2 +- library/think/db/Query.php | 14 +++- .../exception/BindParamException.php} | 6 +- .../db/exception/DataNotFoundException.php | 35 +++++++++ .../db/exception/ModelNotFoundException.php | 38 ++++++++++ .../exception/ClassNotFoundException.php | 16 ++++ .../exception/TemplateNotFoundException.php | 16 ++++ library/think/exception/ValidateException.php | 16 ++++ library/think/view/driver/Php.php | 4 +- library/think/view/driver/Think.php | 4 +- .../thinkphp/library/think/controllerTest.php | 76 ++++++++++++------- tests/thinkphp/library/think/sessionTest.php | 2 +- 33 files changed, 236 insertions(+), 79 deletions(-) rename library/think/{exception => db}/DbException.php (97%) rename library/think/{exception/DbBindParamException.php => db/exception/BindParamException.php} (90%) create mode 100644 library/think/db/exception/DataNotFoundException.php create mode 100644 library/think/db/exception/ModelNotFoundException.php create mode 100644 library/think/exception/ClassNotFoundException.php create mode 100644 library/think/exception/TemplateNotFoundException.php create mode 100644 library/think/exception/ValidateException.php diff --git a/library/think/App.php b/library/think/App.php index e7deb066..bb4dfae1 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -112,7 +112,7 @@ class App $data = $dispatch['response']; break; default: - throw new Exception('dispatch type not support', 10008); + throw new \InvalidArgumentException('dispatch type not support'); } } catch (HttpResponseException $exception) { $data = $exception->getResponse(); @@ -200,7 +200,7 @@ class App } elseif ($param->isDefaultValueAvailable()) { $args[] = $param->getDefaultValue(); } else { - throw new Exception('method param miss:' . $name, 10004); + throw new \InvalidArgumentException('method param miss:' . $name); } } // 全局过滤 @@ -261,7 +261,7 @@ class App // 执行操作 if (!preg_match('/^[A-Za-z](\/|\.|\w)*$/', $controller)) { // 安全检测 - throw new Exception('illegal controller name:' . $controller, 10000); + throw new \InvalidArgumentException('illegal controller name:' . $controller); } // 设置当前请求的模块、控制器、操作 @@ -361,7 +361,7 @@ class App * @param \think\Request $request * @param array $config * @return array - * @throws Exception + * @throws HttpException */ public static function route($request, array $config) { @@ -384,7 +384,7 @@ class App $result = Route::check($request, $path, $depr, !IS_CLI ? $config['url_domain_deploy'] : false); if (APP_ROUTE_MUST && false === $result && $config['url_route_must']) { // 路由无效 - throw new HttpException(404, 'Not Found'); + throw new HttpException(404, 'Route Not Found'); } } if (false === $result) { diff --git a/library/think/Controller.php b/library/think/Controller.php index 03af3da6..dbb4aeae 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -14,6 +14,7 @@ namespace think; \think\Loader::import('controller/Jump', TRAIT_PATH, EXT); use think\Exception; +use think\Exception\ValidateException; use think\Request; use think\View; @@ -190,7 +191,7 @@ class Controller if (!$v->check($data)) { if ($this->failException) { - throw new Exception($v->getError()); + throw new ValidateException($v->getError()); } else { return $v->getError(); } diff --git a/library/think/Exception.php b/library/think/Exception.php index bc4cbdb2..ac648764 100644 --- a/library/think/Exception.php +++ b/library/think/Exception.php @@ -11,10 +11,6 @@ namespace think; -/** - * ThinkPHP核心异常类 - * 所有系统异常必须继承该类 - */ class Exception extends \Exception { diff --git a/library/think/Input.php b/library/think/Input.php index 15e8f880..8bb5334d 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -466,7 +466,7 @@ class Input if (is_scalar($data)) { $data = (string) $data; } else { - throw new Exception('变量类型不允许:' . gettype($data)); + throw new \InvalidArgumentException('变量类型不允许:' . gettype($data)); } } } diff --git a/library/think/Loader.php b/library/think/Loader.php index 451fb3c4..7972ade4 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -12,6 +12,7 @@ namespace think; use think\exception\HttpException; +use think\exception\ClassNotFoundException; use think\Request; class Loader @@ -269,6 +270,7 @@ class Loader * @param bool $appendSuffix 是否添加类名后缀 * @param string $common 公共模块名 * @return Object + * @throws ClassNotFoundException */ public static function model($name = '', $layer = 'model', $appendSuffix = false, $common = 'common') { @@ -289,7 +291,7 @@ class Loader if (class_exists($class)) { $model = new $class(); } else { - throw new Exception('class [ ' . $class . ' ] not exists', 10001); + throw new ClassNotFoundException('class [ ' . $class . ' ] not exists'); } } $_model[$name . $layer] = $model; @@ -303,6 +305,7 @@ class Loader * @param bool $appendSuffix 是否添加类名后缀 * @param string $empty 空控制器名称 * @return Object|false + * @throws ClassNotFoundException */ public static function controller($name, $layer = 'controller', $appendSuffix = false, $empty = '') { @@ -324,7 +327,7 @@ class Loader } elseif ($empty && class_exists($emptyClass = self::parseClass($module, $layer, $empty, $appendSuffix))) { return new $emptyClass(Request::instance()); } else { - throw new HttpException(404, 'class [ ' . $class . ' ] not exists'); + throw new ClassNotFoundException('class [ ' . $class . ' ] not exists'); } } @@ -335,6 +338,7 @@ class Loader * @param bool $appendSuffix 是否添加类名后缀 * @param string $common 公共模块名 * @return Object|false + * @throws ClassNotFoundException */ public static function validate($name = '', $layer = 'validate', $appendSuffix = false, $common = 'common') { @@ -360,7 +364,7 @@ class Loader if (class_exists($class)) { $validate = new $class; } else { - throw new Exception('class [ ' . $class . ' ] not exists', 10001); + throw new ClassNotFoundException('class [ ' . $class . ' ] not exists'); } } $_instance[$name . $layer] = $validate; @@ -409,7 +413,7 @@ class Loader * @param string $method 类的静态方法名 * * @return mixed - * @throws Exception + * @throws ClassNotFoundException */ public static function instance($class, $method = '') { @@ -424,7 +428,7 @@ class Loader $_instance[$identify] = $o; } } else { - throw new Exception('class not exist :' . $class, 10007); + throw new ClassNotFoundException('class not exist :' . $class); } } return $_instance[$identify]; diff --git a/library/think/Model.php b/library/think/Model.php index 4815540d..0b86724f 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -15,6 +15,7 @@ use think\Cache; 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; @@ -773,7 +774,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess if (!$validate->check($data)) { $this->error = $validate->getError(); if ($this->failException) { - throw new Exception($this->error); + throw new ValidateException($this->error); } else { return false; } diff --git a/library/think/Paginator.php b/library/think/Paginator.php index 37433d35..ff243509 100644 --- a/library/think/Paginator.php +++ b/library/think/Paginator.php @@ -143,7 +143,7 @@ abstract class Paginator public function total() { if ($this->simple) { - throw new \Exception('简洁模式下不能获取数据总数'); + throw new \DomainException('简洁模式下不能获取数据总数'); } return $this->total; } @@ -161,7 +161,7 @@ abstract class Paginator public function lastPage() { if ($this->simple) { - throw new \Exception('简洁模式下不能获取最后一页'); + throw new \DomainException('简洁模式下不能获取最后一页'); } return $this->lastPage; } diff --git a/library/think/Response.php b/library/think/Response.php index 3a2c9034..c9c479b3 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -100,7 +100,7 @@ class Response * @access public * @param mixed $data 数据 * @return mixed - * @throws Exception + * @throws \InvalidArgumentException */ public function send($data = null) { @@ -137,7 +137,7 @@ class Response if (is_scalar($data)) { echo $data; } elseif (!is_null($data)) { - throw new Exception('不支持的数据类型输出:' . gettype($data)); + throw new \InvalidArgumentException('不支持的数据类型输出:' . gettype($data)); } if (function_exists('fastcgi_finish_request')) { diff --git a/library/think/Session.php b/library/think/Session.php index 17212b89..193165c9 100644 --- a/library/think/Session.php +++ b/library/think/Session.php @@ -11,6 +11,8 @@ namespace think; +use think\exception\ClassNotFoundException; + class Session { @@ -92,7 +94,7 @@ class Session // 检查驱动类 if (!class_exists($class) || !session_set_save_handler(new $class($config))) { - throw new \think\Exception('error session handler', 11700); + throw new ClassNotFoundException('error session handler'); } } if ($isDoStart) { diff --git a/library/think/Template.php b/library/think/Template.php index f13b5f96..ab14b12c 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -11,6 +11,8 @@ namespace think; +use think\exception\TemplateNotFoundException; + /** * ThinkPHP分离出来的模板引擎 * 支持XML标签和普通标签的模板解析 @@ -1066,7 +1068,7 @@ class Template $this->includeFile[$template] = filemtime($template); return $template; } else { - throw new Exception('template not exist:' . $template, 10700); + throw new TemplateNotFoundException('template not exist:' . $template); } } diff --git a/library/think/Validate.php b/library/think/Validate.php index 6b52c6c4..0eb1c8f7 100644 --- a/library/think/Validate.php +++ b/library/think/Validate.php @@ -1115,7 +1115,7 @@ class Validate if (method_exists($class, $method)) { return call_user_func_array([$class, $method], $params); } else { - throw new Exception(__CLASS__ . ':' . $method . ' method not exist'); + throw new \BadMethodCallException(__CLASS__ . ':' . $method . ' method not exist'); } } } diff --git a/library/think/cache/driver/Apc.php b/library/think/cache/driver/Apc.php index b622762a..95b27d14 100644 --- a/library/think/cache/driver/Apc.php +++ b/library/think/cache/driver/Apc.php @@ -36,7 +36,7 @@ class Apc public function __construct($options = []) { if (!function_exists('apc_cache_info')) { - throw new Exception('_NOT_SUPPERT_:Apc'); + throw new \BadFunctionCallException('not support Apc'); } if (!empty($options)) { $this->options = array_merge($this->options, $options); diff --git a/library/think/cache/driver/Memcache.php b/library/think/cache/driver/Memcache.php index 370c6415..981436fd 100644 --- a/library/think/cache/driver/Memcache.php +++ b/library/think/cache/driver/Memcache.php @@ -30,12 +30,12 @@ class Memcache * 架构函数 * @param array $options 缓存参数 * @access public - * @throws Exception + * @throws \BadFunctionCallException */ public function __construct($options = []) { if (!extension_loaded('memcache')) { - throw new Exception('_NOT_SUPPERT_:memcache'); + throw new \BadFunctionCallException('not support memcache'); } if (!empty($options)) { $this->options = array_merge($this->options, $options); diff --git a/library/think/cache/driver/Memcached.php b/library/think/cache/driver/Memcached.php index e413b06f..b19b0c0c 100644 --- a/library/think/cache/driver/Memcached.php +++ b/library/think/cache/driver/Memcached.php @@ -33,7 +33,7 @@ class Memcached public function __construct($options = []) { if (!extension_loaded('memcached')) { - throw new Exception('_NOT_SUPPERT_:memcached'); + throw new \BadFunctionCallException('not support memcached'); } if (!empty($options)) { $this->options = array_merge($this->options, $options); diff --git a/library/think/cache/driver/Redis.php b/library/think/cache/driver/Redis.php index 403229ff..d872f5a7 100644 --- a/library/think/cache/driver/Redis.php +++ b/library/think/cache/driver/Redis.php @@ -42,7 +42,7 @@ class Redis public function __construct($options = []) { if (!extension_loaded('redis')) { - throw new Exception('_NOT_SUPPERT_:redis'); + throw new \BadFunctionCallException('not support redis'); } if (!empty($options)) { $this->options = array_merge($this->options, $options); diff --git a/library/think/cache/driver/Redisd.php b/library/think/cache/driver/Redisd.php index d32dbaca..ad59cf90 100644 --- a/library/think/cache/driver/Redisd.php +++ b/library/think/cache/driver/Redisd.php @@ -83,7 +83,7 @@ class Redisd public function __construct($options = []) { if (!extension_loaded('redis')) { - throw new Exception('_NOT_SUPPERT_:redis'); + throw new \BadFunctionCallException('not support redis'); } $this->options = $options = array_merge($this->options, $options); diff --git a/library/think/cache/driver/Sae.php b/library/think/cache/driver/Sae.php index 03b70735..c1cdda77 100644 --- a/library/think/cache/driver/Sae.php +++ b/library/think/cache/driver/Sae.php @@ -38,7 +38,7 @@ class Sae public function __construct($options = []) { if (!function_exists('memcache_init')) { - throw new Exception('请在SAE平台上运行代码。'); + throw new \BadFunctionCallException('请在SAE平台上运行代码。'); } $this->handler = memcache_init(); if (!$this->handler) { diff --git a/library/think/cache/driver/Sqlite.php b/library/think/cache/driver/Sqlite.php index 6144a366..ac903fdc 100644 --- a/library/think/cache/driver/Sqlite.php +++ b/library/think/cache/driver/Sqlite.php @@ -32,13 +32,13 @@ class Sqlite implements CacheInterface /** * 架构函数 * @param array $options 缓存参数 - * @throws Exception + * @throws \BadFunctionCallException * @access public */ public function __construct($options = []) { if (!extension_loaded('sqlite')) { - throw new Exception('_NOT_SUPPERT_:sqlite'); + throw new \BadFunctionCallException('not support sqlite'); } if (!empty($options)) { $this->options = array_merge($this->options, $options); diff --git a/library/think/cache/driver/Wincache.php b/library/think/cache/driver/Wincache.php index 66972a48..0717ef05 100644 --- a/library/think/cache/driver/Wincache.php +++ b/library/think/cache/driver/Wincache.php @@ -34,7 +34,7 @@ class Wincache public function __construct($options = []) { if (!function_exists('wincache_ucache_info')) { - throw new Exception('_NOT_SUPPERT_:WinCache'); + throw new \BadFunctionCallException('not support WinCache'); } if (!empty($options)) { $this->options = array_merge($this->options, $options); diff --git a/library/think/cache/driver/Xcache.php b/library/think/cache/driver/Xcache.php index 3fea3296..891e6212 100644 --- a/library/think/cache/driver/Xcache.php +++ b/library/think/cache/driver/Xcache.php @@ -29,12 +29,12 @@ class Xcache * 架构函数 * @param array $options 缓存参数 * @access public - * @throws Exception + * @throws \BadFunctionCallException */ public function __construct($options = []) { if (!function_exists('xcache_info')) { - throw new Exception('_NOT_SUPPERT_:Xcache'); + throw new \BadFunctionCallException('not support Xcache'); } if (!empty($options)) { $this->options = array_merge($this->options, $options); diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index b913c0df..f77df8b7 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -18,8 +18,8 @@ use think\Db; use think\db\Query; use think\Debug; use think\Exception; -use think\exception\DbBindParamException; use think\exception\PDOException; +use think\db\exception\BindParamException; use think\Log; abstract class Connection @@ -326,7 +326,7 @@ abstract class Connection * @param boolean $master 是否在主服务器读操作 * @param bool|string $class 指定返回的数据集对象 * @return mixed - * @throws DbBindParamException + * @throws BindParamException * @throws PDOException */ public function query($sql, $bind = [], $fetch = false, $master = false, $class = false) @@ -375,7 +375,7 @@ abstract class Connection * @param boolean $getLastInsID 是否获取自增ID * @param string $sequence 自增序列名 * @return int - * @throws DbBindParamException + * @throws BindParamException * @throws PDOException */ public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) @@ -465,7 +465,7 @@ abstract class Connection $result = $this->PDOStatement->bindValue($param, $val); } if (!$result) { - throw new DbBindParamException( + throw new BindParamException( "Error occurred when binding parameters '{$param}'", $this->config, $this->queryStr, diff --git a/library/think/exception/DbException.php b/library/think/db/DbException.php similarity index 97% rename from library/think/exception/DbException.php rename to library/think/db/DbException.php index 11c1c932..08c2a398 100644 --- a/library/think/exception/DbException.php +++ b/library/think/db/DbException.php @@ -9,7 +9,7 @@ // | Author: 麦当苗儿 // +---------------------------------------------------------------------- -namespace think\exception; +namespace think\db; use think\Exception; diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 43cfd300..2bad6e8e 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -21,6 +21,8 @@ use think\db\Connection; use think\Exception; use think\exception\DbException; use think\exception\PDOException; +use think\db\exception\ModelNotFoundException; +use think\db\exception\DataNotFoundException; use think\Loader; use think\Model; use think\model\Relation; @@ -379,6 +381,9 @@ class Query 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); } @@ -412,6 +417,9 @@ class Query 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); } @@ -1775,7 +1783,11 @@ class Query } } } elseif (!empty($options['fail'])) { - throw new DbException('Data not Found', $options, $sql); + if(!empty($this->model)){ + throw new ModelNotFoundException('Data not Found', $this->model, $options); + }else{ + throw new DataNotFoundException('Data not Found', $options['table'], $options); + } } else { $data = false; } diff --git a/library/think/exception/DbBindParamException.php b/library/think/db/exception/BindParamException.php similarity index 90% rename from library/think/exception/DbBindParamException.php rename to library/think/db/exception/BindParamException.php index f39c39ac..2e998875 100644 --- a/library/think/exception/DbBindParamException.php +++ b/library/think/db/exception/BindParamException.php @@ -9,14 +9,14 @@ // | Author: 麦当苗儿 // +---------------------------------------------------------------------- -namespace think\exception; +namespace think\db\exception; -use think\exception\DbException; +use think\db\Exception; /** * PDO参数绑定异常 */ -class DbBindParamException extends DbException +class BindParamException extends Exception { /** diff --git a/library/think/db/exception/DataNotFoundException.php b/library/think/db/exception/DataNotFoundException.php new file mode 100644 index 00000000..27569e90 --- /dev/null +++ b/library/think/db/exception/DataNotFoundException.php @@ -0,0 +1,35 @@ + +// +---------------------------------------------------------------------- + +namespace think\db\exception; + +use think\db\DbException; + +class DataNotFoundException extends DbException +{ + protected $table; + + /** + * DbException constructor. + * @param string $message + * @param string $table + * @param array $config + */ + public function __construct($message, $table = '', Array $config = []) + { + $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 new file mode 100644 index 00000000..b12db4df --- /dev/null +++ b/library/think/db/exception/ModelNotFoundException.php @@ -0,0 +1,38 @@ + +// +---------------------------------------------------------------------- + +namespace think\db\exception; + +use think\db\DbException; + +class ModelNotFoundException extends DbException +{ + protected $model; + + /** + * 构造方法 + * @param string $message + * @param string $model + */ + public function __construct($message, $model = '', Array $config = []) + { + $this->message = $message; + $this->model = $model; + + $this->setData('Database Config', $config); + } + + public function getModel() + { + return $this->model; + } + +} diff --git a/library/think/exception/ClassNotFoundException.php b/library/think/exception/ClassNotFoundException.php new file mode 100644 index 00000000..a02d1cb1 --- /dev/null +++ b/library/think/exception/ClassNotFoundException.php @@ -0,0 +1,16 @@ + +// +---------------------------------------------------------------------- + +namespace think\exception; + +class ClassNotFoundException extends \RuntimeException +{ +} \ No newline at end of file diff --git a/library/think/exception/TemplateNotFoundException.php b/library/think/exception/TemplateNotFoundException.php new file mode 100644 index 00000000..5632a747 --- /dev/null +++ b/library/think/exception/TemplateNotFoundException.php @@ -0,0 +1,16 @@ + +// +---------------------------------------------------------------------- + +namespace think\exception; + +class TemplateNotFoundException extends \RuntimeException +{ +} \ No newline at end of file diff --git a/library/think/exception/ValidateException.php b/library/think/exception/ValidateException.php new file mode 100644 index 00000000..34cdae83 --- /dev/null +++ b/library/think/exception/ValidateException.php @@ -0,0 +1,16 @@ + +// +---------------------------------------------------------------------- + +namespace think\exception; + +class ValidateException extends \RuntimeException +{ +} \ No newline at end of file diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index 5eda4faf..de841824 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -11,7 +11,7 @@ namespace think\view\driver; -use think\Exception; +use think\exception\TemplateNotFoundException; use think\Log; use think\Request; @@ -62,7 +62,7 @@ class Php } // 模板不存在 抛出异常 if (!is_file($template)) { - throw new Exception('template file not exists:' . $template, 10700); + throw new TemplateNotFoundException('template file not exists:' . $template); } // 记录视图信息 APP_DEBUG && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 00bfbccc..4a14fc8f 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -11,7 +11,7 @@ namespace think\view\driver; -use think\Exception; +use think\exception\TemplateNotFoundException; use think\Log; use think\Request; use think\Template; @@ -72,7 +72,7 @@ class Think } // 模板不存在 抛出异常 if (!is_file($template)) { - throw new Exception('template file not exists:' . $template, 10700); + throw new TemplateNotFoundException('template file not exists:' . $template); } // 记录视图信息 APP_DEBUG && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); diff --git a/tests/thinkphp/library/think/controllerTest.php b/tests/thinkphp/library/think/controllerTest.php index dbf60d8e..ce5f49a0 100644 --- a/tests/thinkphp/library/think/controllerTest.php +++ b/tests/thinkphp/library/think/controllerTest.php @@ -31,6 +31,48 @@ class Foo extends Controller { $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 @@ -88,8 +130,6 @@ class Baz extends Controller } } -define('ACTION_NAME', 'index'); - class controllerTest extends \PHPUnit_Framework_TestCase { public function testInitialize() @@ -123,8 +163,7 @@ class controllerTest extends \PHPUnit_Framework_TestCase $view = $this->getView($controller); $template = dirname(__FILE__) . '/display.html'; $viewFetch = $view->fetch($template, ['name' => 'ThinkPHP']); - $controllerFetch = $controller->fetch($template, ['name' => 'ThinkPHP']); - $this->assertEquals($controllerFetch, $viewFetch); + $this->assertEquals($controller->fetchTest(), $viewFetch); } public function testDisplay() @@ -133,16 +172,15 @@ class controllerTest extends \PHPUnit_Framework_TestCase $view = $this->getView($controller); $template = dirname(__FILE__) . '/display.html'; $viewFetch = $view->display($template, ['name' => 'ThinkPHP']); - $controllerFetch = $controller->display($template, ['name' => 'ThinkPHP']); - $this->assertEquals($controllerFetch, $viewFetch); + + $this->assertEquals($controller->displayTest(), $viewFetch); } public function testAssign() { $controller = new Foo(Request::instance()); $view = $this->getView($controller); - $controller->assign('abcd', 'dcba'); - $controller->assign(['key1' => 'value1', 'key2' => 'value2']); + $controller->assignTest(); $expect = ['abcd' => 'dcba', 'key1' => 'value1', 'key2' => 'value2']; $this->assertAttributeEquals($expect, 'data', $view); } @@ -150,27 +188,7 @@ class controllerTest extends \PHPUnit_Framework_TestCase public function testValidate() { $controller = new Foo(Request::instance()); - $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之间'], - ]; - $result = $controller->validate($data, $validate); + $result = $controller->test(); $this->assertTrue($result); } } diff --git a/tests/thinkphp/library/think/sessionTest.php b/tests/thinkphp/library/think/sessionTest.php index 50ae99b6..8c3c2d53 100644 --- a/tests/thinkphp/library/think/sessionTest.php +++ b/tests/thinkphp/library/think/sessionTest.php @@ -163,7 +163,7 @@ class sessionTest extends \PHPUnit_Framework_TestCase // 测试session驱动是否存在 // @expectedException 异常类名 - $this->setExpectedException('\think\Exception', 'error session handler', 11700); + $this->setExpectedException('\think\exception\ClassNotFoundException', 'error session handler'); Session::init($config); } From af1bc0429d8fba67890f158e3ad7accd3aa2d8d7 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 16:51:49 +0800 Subject: [PATCH 329/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Query=E7=B1=BB?= =?UTF-8?q?=E7=9A=84with=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 2bad6e8e..e8cf69b5 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1416,8 +1416,8 @@ class Query $field = $this->options['with_field']; unset($this->options['with_field']); } - $this->field($field, false, $joinTable, $joinAlias, $joinName . '__'); } + $this->field($field, false, $joinTable, $joinAlias, $joinName . '__'); $i++; } elseif ($closure) { $with[$key] = $closure; From b1c8665b99fd0d5a3cad612b154ce6e9cbf82d29 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 17:08:48 +0800 Subject: [PATCH 330/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 7 ++++--- library/think/db/exception/BindParamException.php | 6 +++--- library/think/db/exception/DataNotFoundException.php | 2 +- library/think/db/exception/ModelNotFoundException.php | 2 +- library/think/{db => exception}/DbException.php | 2 +- 5 files changed, 10 insertions(+), 9 deletions(-) rename library/think/{db => exception}/DbException.php (97%) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index e8cf69b5..1ecc72d1 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -18,9 +18,10 @@ use think\Config; use think\Db; use think\db\Builder; use think\db\Connection; +use think\db\DbException; use think\Exception; -use think\exception\DbException; use think\exception\PDOException; +use think\db\exception\BindParamException; use think\db\exception\ModelNotFoundException; use think\db\exception\DataNotFoundException; use think\Loader; @@ -179,7 +180,7 @@ class Query * @param boolean $master 是否在主服务器读操作 * @param bool|string $class 指定返回的数据集对象 * @return mixed - * @throws DbBindParamException + * @throws BindParamException * @throws PDOException */ public function query($sql, $bind = [], $fetch = false, $master = false, $class = false) @@ -196,7 +197,7 @@ class Query * @param boolean $getLastInsID 是否获取自增ID * @param boolean $sequence 自增序列名 * @return int - * @throws DbBindParamException + * @throws BindParamException * @throws PDOException */ public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) diff --git a/library/think/db/exception/BindParamException.php b/library/think/db/exception/BindParamException.php index 2e998875..585a0d73 100644 --- a/library/think/db/exception/BindParamException.php +++ b/library/think/db/exception/BindParamException.php @@ -11,16 +11,16 @@ namespace think\db\exception; -use think\db\Exception; +use think\exception\DbException; /** * PDO参数绑定异常 */ -class BindParamException extends Exception +class BindParamException extends DbException { /** - * DbBindParamException constructor. + * BindParamException constructor. * @param string $message * @param array $config * @param string $sql diff --git a/library/think/db/exception/DataNotFoundException.php b/library/think/db/exception/DataNotFoundException.php index 27569e90..ac0f416d 100644 --- a/library/think/db/exception/DataNotFoundException.php +++ b/library/think/db/exception/DataNotFoundException.php @@ -11,7 +11,7 @@ namespace think\db\exception; -use think\db\DbException; +use think\exception\DbException; class DataNotFoundException extends DbException { diff --git a/library/think/db/exception/ModelNotFoundException.php b/library/think/db/exception/ModelNotFoundException.php index b12db4df..aba7187b 100644 --- a/library/think/db/exception/ModelNotFoundException.php +++ b/library/think/db/exception/ModelNotFoundException.php @@ -11,7 +11,7 @@ namespace think\db\exception; -use think\db\DbException; +use think\exception\DbException; class ModelNotFoundException extends DbException { diff --git a/library/think/db/DbException.php b/library/think/exception/DbException.php similarity index 97% rename from library/think/db/DbException.php rename to library/think/exception/DbException.php index 08c2a398..11c1c932 100644 --- a/library/think/db/DbException.php +++ b/library/think/exception/DbException.php @@ -9,7 +9,7 @@ // | Author: 麦当苗儿 // +---------------------------------------------------------------------- -namespace think\db; +namespace think\exception; use think\Exception; From a09cf8d3a1ed76c8d5db882e462292f9d321a75a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 17:17:21 +0800 Subject: [PATCH 331/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Oracle=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Db.php | 2 +- library/think/db/connector/Oracle.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/Db.php b/library/think/Db.php index 4331be12..a75764b7 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -70,7 +70,7 @@ class Db // 解析连接参数 支持数组和字符串 $options = self::parseConfig($config); if (empty($options['type'])) { - throw new Exception('db type error'); + throw new \InvalidArgumentException('db type error'); } $class = (!empty($options['namespace']) ? $options['namespace'] : '\\think\\db\\connector\\') . ucwords($options['type']); // 记录初始化信息 diff --git a/library/think/db/connector/Oracle.php b/library/think/db/connector/Oracle.php index 19954ecc..7e067aea 100644 --- a/library/think/db/connector/Oracle.php +++ b/library/think/db/connector/Oracle.php @@ -125,10 +125,10 @@ class Oracle extends Connection /** * 取得数据库的表信息(暂时实现取得用户表信息) * @access public + * @param string $dbName * @return array - * @internal param string $dbName */ - public function getTables() + public function getTables($dbName = '') { $pdo = $this->linkID->query("select table_name from all_tables"); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); From 4d9a4bcaae8447d83cae81f5dc1f74a67c39c21e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 17:26:36 +0800 Subject: [PATCH 332/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Oracle=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/connector/Oracle.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/db/connector/Oracle.php b/library/think/db/connector/Oracle.php index 7e067aea..7364c506 100644 --- a/library/think/db/connector/Oracle.php +++ b/library/think/db/connector/Oracle.php @@ -51,7 +51,7 @@ class Oracle extends Connection * @throws \Exception * @throws \think\Exception */ - public function execute($sql, $bind = [], $fetch = false) + public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) { $this->initConnect(true); if (!$this->linkID) { @@ -85,6 +85,9 @@ class Oracle extends Connection $this->numRows = $this->PDOStatement->rowCount(); if ($flag || preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $sql)) { $this->lastInsID = $this->linkID->lastInsertId(); + if ($getLastInsID) { + return $this->lastInsID; + } } return $this->numRows; } catch (\PDOException $e) { From cc191effcc610a1ff82505d2d7a0eed92af31753 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 17:34:54 +0800 Subject: [PATCH 333/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BOracle=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8=E7=9A=84execute=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/connector/Oracle.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/library/think/db/connector/Oracle.php b/library/think/db/connector/Oracle.php index 7364c506..a9b7e102 100644 --- a/library/think/db/connector/Oracle.php +++ b/library/think/db/connector/Oracle.php @@ -47,6 +47,8 @@ class Oracle extends Connection * @param string $sql sql指令 * @param array $bind 参数绑定 * @param boolean $fetch 不执行只是获取SQL + * @param boolean $getLastInsID 是否获取自增ID + * @param string $sequence 序列名 * @return integer * @throws \Exception * @throws \think\Exception @@ -65,8 +67,10 @@ class Oracle extends Connection } $flag = false; if (preg_match("/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i", $sql, $match)) { - $table = Config::get("db_sequence_prefix") . str_ireplace(Config::get("database.prefix"), "", $match[2]); - $flag = (boolean) $this->query("SELECT * FROM all_sequences WHERE sequence_name='" . strtoupper($table) . "'"); + if(is_null($sequence)){ + $sequence = Config::get("db_sequence_prefix") . str_ireplace(Config::get("database.prefix"), "", $match[2]); + } + $flag = (boolean) $this->query("SELECT * FROM all_sequences WHERE sequence_name='" . strtoupper($sequence) . "'"); } //释放前次的查询结果 if (!empty($this->PDOStatement)) { From 8c08015a6af88317cac7db0c049dc21c546e685d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 18:14:35 +0800 Subject: [PATCH 334/670] =?UTF-8?q?Model=E7=9A=84=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E5=A2=9E=E5=8A=A0serialize=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/library/think/Model.php b/library/think/Model.php index 0b86724f..0996872f 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -327,6 +327,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess case 'json': $value = json_encode($value, JSON_UNESCAPED_UNICODE); break; + case 'serialize': + $value = serialize($value); + break; } return $value; } @@ -398,6 +401,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess case 'object': $value = json_decode($value); break; + case 'serialize': + $value = unserialize($value); + break; } return $value; } From 420fdd9eafb0e30f005bf3f185d573a2ee4a8e38 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 18:22:48 +0800 Subject: [PATCH 335/670] =?UTF-8?q?Model=E7=B1=BB=E7=9A=84json=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E8=BD=AC=E6=8D=A2=E6=94=AF=E6=8C=81=E4=BC=A0=E5=85=A5?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index 0996872f..1b7b251f 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -325,7 +325,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess case 'array': $value = (array) $value; case 'json': - $value = json_encode($value, JSON_UNESCAPED_UNICODE); + $option = !empty($param) ? (intval)$param : JSON_UNESCAPED_UNICODE; + $value = json_encode($value, $option); break; case 'serialize': $value = serialize($value); From 6d0c3a633e4918d106ca4981130611786ecceddf Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 18:26:40 +0800 Subject: [PATCH 336/670] =?UTF-8?q?Model=E7=B1=BB=E7=9A=84=E5=BC=BA?= =?UTF-8?q?=E5=88=B6=E7=B1=BB=E5=9E=8B=E8=BD=AC=E6=8D=A2=E5=AE=9A=E4=B9=89?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=95=B0=E7=BB=84=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 1b7b251f..c1ab43c8 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -286,12 +286,15 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * 数据写入 类型转换 * @access public * @param mixed $value 值 - * @param string $type 要转换的类型 + * @param string|array $type 要转换的类型 * @return mixed */ protected function writeTransform($value, $type) { - if (strpos($type, ':')) { + if(is_array($type)){ + $param = $type[1]; + $type = $type[0]; + }elseif (strpos($type, ':')) { list($type, $param) = explode(':', $type, 2); } switch ($type) { @@ -365,12 +368,15 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * 数据读取 类型转换 * @access public * @param mixed $value 值 - * @param string $type 要转换的类型 + * @param string|array $type 要转换的类型 * @return mixed */ protected function readTransform($value, $type) { - if (strpos($type, ':')) { + if(is_array($type)){ + $param = $type[1]; + $type = $type[0]; + }elseif (strpos($type, ':')) { list($type, $param) = explode(':', $type, 2); } switch ($type) { From 00b0c0f229edd1bfd19dab4aaf15d028e0b93183 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 12 Jun 2016 22:47:08 +0800 Subject: [PATCH 337/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB=20?= =?UTF-8?q?=E6=94=B9=E8=BF=9B=E6=9F=A5=E8=AF=A2=E6=96=B9=E6=B3=95=E7=9A=84?= =?UTF-8?q?SQL=E8=BF=94=E5=9B=9E=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 8 ++- library/think/db/Connection.php | 26 +++------- library/think/db/Query.php | 71 +++++++++++++++++---------- library/think/db/connector/Oracle.php | 8 ++- 4 files changed, 57 insertions(+), 56 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index c1ab43c8..b6be17b2 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -292,8 +292,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected function writeTransform($value, $type) { if(is_array($type)){ - $param = $type[1]; - $type = $type[0]; + list($type,$param) = $type; }elseif (strpos($type, ':')) { list($type, $param) = explode(':', $type, 2); } @@ -328,7 +327,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess case 'array': $value = (array) $value; case 'json': - $option = !empty($param) ? (intval)$param : JSON_UNESCAPED_UNICODE; + $option = !empty($param) ? (int)$param : JSON_UNESCAPED_UNICODE; $value = json_encode($value, $option); break; case 'serialize': @@ -374,8 +373,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected function readTransform($value, $type) { if(is_array($type)){ - $param = $type[1]; - $type = $type[0]; + list($type,$param) = $type; }elseif (strpos($type, ':')) { list($type, $param) = explode(':', $type, 2); } diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index f77df8b7..ab18a719 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -28,11 +28,6 @@ abstract class Connection /** @var PDOStatement PDO操作实例 */ protected $PDOStatement; - // 当前操作的数据表名 - protected $table = ''; - // 当前操作的数据对象名 - protected $name = ''; - /** @var string 当前SQL指令 */ protected $queryStr = ''; // 最后插入ID @@ -322,26 +317,21 @@ abstract class Connection * @access public * @param string $sql sql指令 * @param array $bind 参数绑定 - * @param boolean $fetch 不执行只是获取SQL * @param boolean $master 是否在主服务器读操作 * @param bool|string $class 指定返回的数据集对象 * @return mixed * @throws BindParamException * @throws PDOException */ - public function query($sql, $bind = [], $fetch = false, $master = false, $class = false) + public function query($sql, $bind = [], $master = false, $class = false) { $this->initConnect($master); if (!$this->linkID) { return false; } - // 根据参数绑定组装最终的SQL语句 - $this->queryStr = $this->getBindSql($sql, $bind); - - if ($fetch) { - return $this->queryStr; - } + $this->queryStr = $this->getRealSql($sql, $bind); + //释放前次的查询结果 if (!empty($this->PDOStatement)) { $this->free(); @@ -371,25 +361,21 @@ abstract class Connection * @access public * @param string $sql sql指令 * @param array $bind 参数绑定 - * @param boolean $fetch 不执行只是获取SQL * @param boolean $getLastInsID 是否获取自增ID * @param string $sequence 自增序列名 * @return int * @throws BindParamException * @throws PDOException */ - public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) + public function execute($sql, $bind = [], $getLastInsID = false, $sequence = null) { $this->initConnect(true); if (!$this->linkID) { return false; } // 根据参数绑定组装最终的SQL语句 - $this->queryStr = $this->getBindSql($sql, $bind); + $this->queryStr = $this->getRealSql($sql, $bind); - if ($fetch) { - return $this->queryStr; - } //释放前次的查询结果 if (!empty($this->PDOStatement)) { $this->free(); @@ -428,7 +414,7 @@ abstract class Connection * @param array $bind 参数绑定列表 * @return string */ - protected function getBindSql($sql, array $bind = []) + public function getRealSql($sql, array $bind = []) { if ($bind) { foreach ($bind as $key => $val) { diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 1ecc72d1..4eee12ca 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1521,7 +1521,7 @@ class Query * @param boolean $replace 是否replace * @param boolean $getLastInsID 是否获取自增ID * @param string $sequence 自增序列名 - * @return integer + * @return integer|string */ public function insert(array $data, $replace = false, $getLastInsID = false, $sequence = null) { @@ -1529,9 +1529,13 @@ class Query $options = $this->parseExpress(); // 生成SQL语句 $sql = $this->builder()->insert($data, $options, $replace); + if($options['fetch_sql']){ + // 获取实际执行的SQL语句 + return $this->connection->getRealSql($sql,$this->bind); + } $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null); // 执行操作 - return $this->execute($sql, $this->getBind(), $options['fetch_sql'], $getLastInsID, $sequence); + return $this->execute($sql, $this->getBind(), $getLastInsID, $sequence); } /** @@ -1540,7 +1544,7 @@ class Query * @param mixed $data 数据 * @param boolean $replace 是否replace * @param string $sequence 自增序列名 - * @return integer + * @return integer|string */ public function insertGetId(array $data, $replace = false, $sequence = null) { @@ -1551,7 +1555,7 @@ class Query * 批量插入记录 * @access public * @param mixed $dataSet 数据集 - * @return integer + * @return integer|string */ public function insertAll(array $dataSet) { @@ -1562,8 +1566,13 @@ class Query } // 生成SQL语句 $sql = $this->builder()->insertAll($dataSet, $options); - // 执行操作 - return $this->execute($sql, $this->getBind(), $options['fetch_sql']); + if($options['fetch_sql']){ + // 获取实际执行的SQL语句 + return $this->connection->getRealSql($sql,$this->bind); + }else{ + // 执行操作 + return $this->execute($sql, $this->getBind()); + } } /** @@ -1571,7 +1580,7 @@ class Query * @access public * @param string $fields 要插入的数据表字段名 * @param string $table 要插入的数据表名 - * @return int + * @return integer|string * @throws PDOException */ public function selectInsert($fields, $table) @@ -1580,15 +1589,20 @@ class Query $options = $this->parseExpress(); // 生成SQL语句 $sql = $this->builder()->selectInsert($fields, $table, $options); - // 执行操作 - return $this->execute($sql, $this->getBind(), $options['fetch_sql']); + if($options['fetch_sql']){ + // 获取实际执行的SQL语句 + return $this->connection->getRealSql($sql,$this->bind); + }else{ + // 执行操作 + return $this->execute($sql, $this->getBind()); + } } /** * 更新记录 * @access public * @param mixed $data 数据 - * @return int + * @return integer|string * @throws Exception * @throws PDOException */ @@ -1622,11 +1636,13 @@ class Query } // 生成UPDATE SQL语句 $sql = $this->builder()->update($data, $options); - if ('' == $sql) { - return 0; + if($options['fetch_sql']){ + // 获取实际执行的SQL语句 + return $this->connection->getRealSql($sql,$this->bind); + }else{ + // 执行操作 + return '' == $sql ? 0 : $this->execute($sql, $this->getBind()); } - // 执行操作 - return $this->execute($sql, $this->getBind(), $options['fetch_sql']); } /** @@ -1666,13 +1682,13 @@ class Query if (!$resultSet) { // 生成查询SQL $sql = $this->builder()->select($options); + if($options['fetch_sql']){ + // 获取实际执行的SQL语句 + return $this->connection->getRealSql($sql,$this->bind); + } // 执行查询操作 - $resultSet = $this->query($sql, $this->getBind(), $options['fetch_sql'], $options['master'], $options['fetch_class']); + $resultSet = $this->query($sql, $this->getBind(), $options['master'], $options['fetch_class']); - if (is_string($resultSet)) { - // 返回SQL - return $resultSet; - } if ($resultSet instanceof \PDOStatement) { // 返回PDOStatement对象 return $resultSet; @@ -1747,13 +1763,12 @@ class Query if (!$result) { // 生成查询SQL $sql = $this->builder()->select($options); + if($options['fetch_sql']){ + // 获取实际执行的SQL语句 + return $this->connection->getRealSql($sql,$this->bind); + } // 执行查询 - $result = $this->query($sql, $this->getBind(), $options['fetch_sql'], $options['master'], $options['fetch_class']); - - if (is_string($result)) { - // 返回SQL - return $result; - } + $result = $this->query($sql, $this->getBind(), $options['master'], $options['fetch_class']); if ($result instanceof \PDOStatement) { // 返回PDOStatement对象 @@ -1902,8 +1917,12 @@ class Query } // 生成删除SQL语句 $sql = $this->builder()->delete($options); + if($options['fetch_sql']){ + // 获取实际执行的SQL语句 + return $this->getRealSql($sql,$this->bind); + } // 执行操作 - return $this->execute($sql, $this->getBind(), $options['fetch_sql']); + return $this->execute($sql, $this->getBind()); } /** diff --git a/library/think/db/connector/Oracle.php b/library/think/db/connector/Oracle.php index a9b7e102..1e2a4372 100644 --- a/library/think/db/connector/Oracle.php +++ b/library/think/db/connector/Oracle.php @@ -46,14 +46,13 @@ class Oracle extends Connection * @access public * @param string $sql sql指令 * @param array $bind 参数绑定 - * @param boolean $fetch 不执行只是获取SQL * @param boolean $getLastInsID 是否获取自增ID * @param string $sequence 序列名 * @return integer * @throws \Exception * @throws \think\Exception */ - public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) + public function execute($sql, $bind = [], $getLastInsID = false, $sequence = null) { $this->initConnect(true); if (!$this->linkID) { @@ -62,9 +61,7 @@ class Oracle extends Connection // 根据参数绑定组装最终的SQL语句 $this->queryStr = $this->getBindSql($sql, $bind); - if ($fetch) { - return $this->queryStr; - } + $flag = false; if (preg_match("/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i", $sql, $match)) { if(is_null($sequence)){ @@ -72,6 +69,7 @@ class Oracle extends Connection } $flag = (boolean) $this->query("SELECT * FROM all_sequences WHERE sequence_name='" . strtoupper($sequence) . "'"); } + //释放前次的查询结果 if (!empty($this->PDOStatement)) { $this->free(); From b6b8b6dcb42600391d40658844ce4edf53c54846 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 13 Jun 2016 11:09:42 +0800 Subject: [PATCH 338/670] =?UTF-8?q?Controller=E7=B1=BB=E5=A2=9E=E5=8A=A0ba?= =?UTF-8?q?tchValidate=E5=B1=9E=E6=80=A7=20validate=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0batch=E5=8F=82=E6=95=B0=EF=BC=8C=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E8=AE=BE=E7=BD=AE=E6=98=AF=E5=90=A6=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=20=E5=BC=82=E5=B8=B8=E7=B1=BB=E6=94=B9?= =?UTF-8?q?=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 11 +++++++++-- library/think/Loader.php | 8 ++++---- library/think/Session.php | 2 +- library/think/Template.php | 2 +- library/think/db/Query.php | 6 +++++- .../db/exception/DataNotFoundException.php | 10 +++++++++- .../db/exception/ModelNotFoundException.php | 5 +++++ .../think/exception/ClassNotFoundException.php | 16 ++++++++++++++++ .../exception/TemplateNotFoundException.php | 17 +++++++++++++++++ library/think/exception/ValidateException.php | 16 ++++++++++++++++ library/think/view/driver/Php.php | 2 +- library/think/view/driver/Think.php | 2 +- 12 files changed, 85 insertions(+), 12 deletions(-) diff --git a/library/think/Controller.php b/library/think/Controller.php index dbb4aeae..74e69ef2 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -28,6 +28,8 @@ class Controller protected $request; // 验证失败是否抛出异常 protected $failException = false; + // 是否批量验证 + protected $batchValidate = false; /** * 前置操作方法列表 @@ -162,10 +164,11 @@ class Controller * @param array $data 数据 * @param string|array $validate 验证器名或者验证规则数组 * @param array $message 提示信息 + * @param bool $batch 是否批量验证 * @param mixed $callback 回调方法(闭包) * @return true|string|array */ - protected function validate($data, $validate, $message = [], $callback = null) + protected function validate($data, $validate, $message = [], $batch = false, $callback = null) { if (is_array($validate)) { $v = Loader::validate(); @@ -180,12 +183,16 @@ class Controller $v->scene($scene); } } + // 是否批量验证 + if($batch || $this->batchValidate){ + $v->batch(true); + } if (is_array($message)) { $v->message($message); } - if (is_callable($callback)) { + if ($callback && is_callable($callback)) { call_user_func_array($callback, [$v, &$data]); } diff --git a/library/think/Loader.php b/library/think/Loader.php index 7972ade4..27ad52f2 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -291,7 +291,7 @@ class Loader if (class_exists($class)) { $model = new $class(); } else { - throw new ClassNotFoundException('class [ ' . $class . ' ] not exists'); + throw new ClassNotFoundException('class [ ' . $class . ' ] not exists', $class); } } $_model[$name . $layer] = $model; @@ -327,7 +327,7 @@ class Loader } elseif ($empty && class_exists($emptyClass = self::parseClass($module, $layer, $empty, $appendSuffix))) { return new $emptyClass(Request::instance()); } else { - throw new ClassNotFoundException('class [ ' . $class . ' ] not exists'); + throw new ClassNotFoundException('class [ ' . $class . ' ] not exists', $class); } } @@ -364,7 +364,7 @@ class Loader if (class_exists($class)) { $validate = new $class; } else { - throw new ClassNotFoundException('class [ ' . $class . ' ] not exists'); + throw new ClassNotFoundException('class [ ' . $class . ' ] not exists', $class); } } $_instance[$name . $layer] = $validate; @@ -428,7 +428,7 @@ class Loader $_instance[$identify] = $o; } } else { - throw new ClassNotFoundException('class not exist :' . $class); + throw new ClassNotFoundException('class not exist :' . $class, $class); } } return $_instance[$identify]; diff --git a/library/think/Session.php b/library/think/Session.php index 193165c9..e9855a9e 100644 --- a/library/think/Session.php +++ b/library/think/Session.php @@ -94,7 +94,7 @@ class Session // 检查驱动类 if (!class_exists($class) || !session_set_save_handler(new $class($config))) { - throw new ClassNotFoundException('error session handler'); + throw new ClassNotFoundException('error session handler', $class); } } if ($isDoStart) { diff --git a/library/think/Template.php b/library/think/Template.php index ab14b12c..b1d6943b 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -1068,7 +1068,7 @@ class Template $this->includeFile[$template] = filemtime($template); return $template; } else { - throw new TemplateNotFoundException('template not exist:' . $template); + throw new TemplateNotFoundException('template not exist:' . $template, $template); } } diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 4eee12ca..c82e5db8 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1723,7 +1723,11 @@ class Query } } } elseif (!empty($options['fail'])) { - throw new DbException('Data not Found', $options, $sql); + if(!empty($this->model)){ + throw new ModelNotFoundException('Data not Found', $this->model, $options); + }else{ + throw new DataNotFoundException('Data not Found', $options['table'], $options); + } } return $resultSet; } diff --git a/library/think/db/exception/DataNotFoundException.php b/library/think/db/exception/DataNotFoundException.php index ac0f416d..efd66d3b 100644 --- a/library/think/db/exception/DataNotFoundException.php +++ b/library/think/db/exception/DataNotFoundException.php @@ -31,5 +31,13 @@ class DataNotFoundException extends DbException $this->setData('Database Config', $config); } - + /** + * 获取数据表名 + * @access public + * @return string + */ + public function getTable() + { + return $this->table; + } } diff --git a/library/think/db/exception/ModelNotFoundException.php b/library/think/db/exception/ModelNotFoundException.php index aba7187b..69b70965 100644 --- a/library/think/db/exception/ModelNotFoundException.php +++ b/library/think/db/exception/ModelNotFoundException.php @@ -30,6 +30,11 @@ class ModelNotFoundException extends DbException $this->setData('Database Config', $config); } + /** + * 获取模型类名 + * @access public + * @return string + */ public function getModel() { return $this->model; diff --git a/library/think/exception/ClassNotFoundException.php b/library/think/exception/ClassNotFoundException.php index a02d1cb1..7160f86b 100644 --- a/library/think/exception/ClassNotFoundException.php +++ b/library/think/exception/ClassNotFoundException.php @@ -13,4 +13,20 @@ namespace think\exception; class ClassNotFoundException extends \RuntimeException { + protected $class; + public function __construct($message,$class='') + { + $this->message = $message; + $this->class = $class; + } + + /** + * 获取类名 + * @access public + * @return string + */ + public function getClass() + { + return $this->class; + } } \ No newline at end of file diff --git a/library/think/exception/TemplateNotFoundException.php b/library/think/exception/TemplateNotFoundException.php index 5632a747..b9d5294e 100644 --- a/library/think/exception/TemplateNotFoundException.php +++ b/library/think/exception/TemplateNotFoundException.php @@ -13,4 +13,21 @@ namespace think\exception; class TemplateNotFoundException extends \RuntimeException { + protected $template; + + public function __construct($message,$template='') + { + $this->message = $message; + $this->template = $template; + } + + /** + * 获取模板文件 + * @access public + * @return string + */ + public function getTemplate() + { + return $this->template; + } } \ No newline at end of file diff --git a/library/think/exception/ValidateException.php b/library/think/exception/ValidateException.php index 34cdae83..6f1cd4d1 100644 --- a/library/think/exception/ValidateException.php +++ b/library/think/exception/ValidateException.php @@ -13,4 +13,20 @@ namespace think\exception; class ValidateException extends \RuntimeException { + protected $error; + + public function __construct($error) + { + $this->error = $error; + } + + /** + * 获取验证错误信息 + * @access public + * @return array|string + */ + public function getError() + { + return $this->error; + } } \ No newline at end of file diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index de841824..7db03fdb 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -62,7 +62,7 @@ class Php } // 模板不存在 抛出异常 if (!is_file($template)) { - throw new TemplateNotFoundException('template file not exists:' . $template); + throw new TemplateNotFoundException('template file not exists:' . $template, $template); } // 记录视图信息 APP_DEBUG && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 4a14fc8f..906fcf10 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -72,7 +72,7 @@ class Think } // 模板不存在 抛出异常 if (!is_file($template)) { - throw new TemplateNotFoundException('template file not exists:' . $template); + throw new TemplateNotFoundException('template file not exists:' . $template, $template); } // 记录视图信息 APP_DEBUG && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); From 5171ea302d546d35275a9e5b57a3becd9dae8b0f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 13 Jun 2016 11:37:54 +0800 Subject: [PATCH 339/670] =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=85=B3=E9=97=AD?= =?UTF-8?q?=E4=BC=AA=E9=9D=99=E6=80=81=E8=AE=BF=E9=97=AE=20=E8=AE=BE?= =?UTF-8?q?=E7=BD=AEurl=5Fhtml=5Fsuffix=20=E4=B8=BAfalse?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index f079fcbd..f4c6a84c 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -349,8 +349,18 @@ class Request public function path() { if (is_null($this->path)) { - // 去除正常的URL后缀 - $this->path = preg_replace(Config::get('url_html_suffix') ? '/\.(' . trim(Config::get('url_html_suffix'), '.') . ')$/i' : '/\.' . $this->ext() . '$/i', '', $this->pathinfo()); + $suffix = Config::get('url_html_suffix'); + $pathinfo = $this->pathinfo(); + if(false === $suffix){ + // 禁止伪静态访问 + $this->path = $pathinfo; + }elseif($suffix){ + // 去除正常的URL后缀 + $this->path = preg_replace('/\.(' . ltrim($suffix, '.') . ')$/i' , '', $pathinfo); + }else{ + // 允许任何后缀访问 + $this->path = preg_replace('/\.' . $this->ext() . '$/i', '', $pathinfo); + } } return $this->path; } From 5c084d92d39bb73c2339f3f965a148d76ec4aa52 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 13 Jun 2016 12:37:45 +0800 Subject: [PATCH 340/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=20model=20controller?= =?UTF-8?q?=20validate=20action=20=E5=8A=A9=E6=89=8B=E5=87=BD=E6=95=B0=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20$appendSuffix=20=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/helper.php b/helper.php index 8e549b02..51458c23 100644 --- a/helper.php +++ b/helper.php @@ -144,22 +144,24 @@ function widget($name, $data = []) * 实例化Model * @param string $name Model名称 * @param string $layer 业务层名称 + * @param bool $appendSuffix 是否添加类名后缀 * @return \think\Model */ -function model($name = '', $layer = 'model') +function model($name = '', $layer = 'model', $appendSuffix = false) { - return Loader::model($name, $layer); + return Loader::model($name, $layer, $appendSuffix); } /** * 实例化验证器 * @param string $name 验证器名称 * @param string $layer 业务层名称 + * @param bool $appendSuffix 是否添加类名后缀 * @return \think\Validate */ -function validate($name = '', $layer = 'validate') +function validate($name = '', $layer = 'validate', $appendSuffix = false) { - return Loader::validate($name, $layer); + return Loader::validate($name, $layer, $appendSuffix); } /** @@ -177,11 +179,12 @@ function db($name = '', $config = []) * 实例化控制器 格式:[模块/]控制器 * @param string $name 资源地址 * @param string $layer 控制层名称 + * @param bool $appendSuffix 是否添加类名后缀 * @return \think\Controller */ -function controller($name, $layer = 'controller') +function controller($name, $layer = 'controller', $appendSuffix = false) { - return Loader::controller($name, $layer); + return Loader::controller($name, $layer, $appendSuffix); } /** @@ -189,11 +192,12 @@ function controller($name, $layer = 'controller') * @param string $url 调用地址 * @param string|array $vars 调用参数 支持字符串和数组 * @param string $layer 要调用的控制层名称 + * @param bool $appendSuffix 是否添加类名后缀 * @return mixed */ -function action($url, $vars = [], $layer = 'controller') +function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) { - return Loader::action($url, $vars, $layer); + return Loader::action($url, $vars, $layer, $appendSuffix); } /** From 101bfb3f83092ad2b7ef835b2b354eae8572f68a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 13 Jun 2016 16:11:42 +0800 Subject: [PATCH 341/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E7=9A=84create=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index f4c6a84c..d4deb6f2 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -191,7 +191,8 @@ class Request $options['cookie'] = $cookie; $options['file'] = $files; $options['server'] = $server; - return new self($options); + self::$instance = new self($options); + return self::$instance; } /** From a9cfe2a801d8bb98c116e61fe48054423d8e32ce Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 13 Jun 2016 16:27:59 +0800 Subject: [PATCH 342/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=E5=92=8C=E6=97=B6=E9=97=B4=E6=9F=A5=E8=AF=A2=E6=96=B9=E6=B3=95?= =?UTF-8?q?=20datetime?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Builder.php | 43 +++++++++++++++++++++++++++++++----- library/think/db/Query.php | 14 ++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index 53c23e9b..c3bdf253 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -28,7 +28,7 @@ abstract class Builder protected $options = []; // 数据库表达式 - 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']; + 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', 'between time' => 'BETWEEN TIME', 'not between time' => 'NOT BETWEEN TIME']; // SQL表达式 protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%'; @@ -272,12 +272,10 @@ abstract class Builder } // where子单元分析 - protected function parseWhereItem($key, $val, $rule = '') + protected function parseWhereItem($field, $val, $rule = '') { - if ($key) { - // 字段分析 - $key = $this->parseKey($key); - } + // 字段分析 + $key = $field ? $this->parseKey($field) : ''; // 查询规则和条件 if (!is_array($val)) { @@ -340,6 +338,13 @@ abstract class Builder } else { $whereStr .= $exp . ' (' . $value . ')'; } + } elseif (in_array($exp, ['< TIME', '> TIME'])){ + $whereStr .= $key . ' ' . substr($exp,0,1) . ' ' . $this->parseDateTime($value, $field); + } elseif (in_array($exp, ['BETWEEN TIME', 'NOT BETWEEN TIME'])){ + if(is_string($value)){ + $value = explode(',',$value); + } + $whereStr .= $key . ' ' . substr($exp,0,-4) . $this->parseDateTime($value[0], $field) . ' AND ' . $this->parseDateTime($value[1], $field); } return $whereStr; } @@ -352,6 +357,32 @@ abstract class Builder return $query->buildSql($show); } + /** + * 日期时间条件解析 + * @access protected + * @param string $value + * @param string $key + * @return string + */ + protected function parseDateTime($value, $key) + { + // 获取时间字段类型 + $type = $this->query->getTableInfo('', 'type'); + if(isset($type[$key])){ + if(preg_match('/(datetime|timestamp)/is', $type[$key])){ + // 日期及时间戳类型 + $value = date('Y-m-d H:i:s', strtotime($value)); + }elseif(preg_match('/(date)/is', $type[$key])){ + // 日期及时间戳类型 + $value = date('Y-m-d', strtotime($value)); + }else{ + // 整型 + $value = strtotime($value); + } + } + return is_int($value)? $value : $this->connection->quote($value); + } + /** * limit分析 * @access protected diff --git a/library/think/db/Query.php b/library/think/db/Query.php index c82e5db8..977cdc4c 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1227,6 +1227,20 @@ class Query return $this; } + /** + * 查询日期或者时间 + * @access public + * @param string $field 日期字段名 + * @param string $op 比较运算 > < between not between + * @param string|array $range 比较范围 + * @return $this + */ + public function datetime($field, $op, $range = []) + { + $this->where($field, strtolower($op) . ' time', $range); + return $this; + } + /** * 获取数据表信息 * @access public From 4689c86e0ae4419ecb24d9e07d38bd36cc77f1a5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 13 Jun 2016 16:45:39 +0800 Subject: [PATCH 343/670] =?UTF-8?q?Response=E7=B1=BB=E5=A2=9E=E5=8A=A0getC?= =?UTF-8?q?ode=E6=96=B9=E6=B3=95=E5=92=8CgetContent=E6=96=B9=E6=B3=95=20se?= =?UTF-8?q?nd=E6=96=B9=E6=B3=95data=E5=8F=82=E6=95=B0=E5=8E=BB=E6=8E=89=20?= =?UTF-8?q?App=E7=B1=BB=E7=9A=84run=E6=96=B9=E6=B3=95=E8=BF=94=E5=9B=9Eres?= =?UTF-8?q?ponse=E5=AF=B9=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 4 +- library/think/Response.php | 53 +++++++++++++++++++----- start.php | 5 ++- tests/thinkphp/library/think/appTest.php | 2 +- 4 files changed, 49 insertions(+), 15 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index bb4dfae1..6b911fdb 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -123,12 +123,12 @@ class App // 输出数据到客户端 if ($data instanceof Response) { - return $data->send(); + return $data; } elseif (!is_null($data)) { // 默认自动识别响应输出类型 $isAjax = $request->isAjax(); $type = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type'); - return Response::create($data, $type)->send(); + return Response::create($data, $type); } } diff --git a/library/think/Response.php b/library/think/Response.php index c9c479b3..0024e0af 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -20,8 +20,10 @@ class Response protected static $instance = []; // 输出数据的转换方法 protected $transform; - // 输出数据 + // 原始数据 protected $data; + // 输出数据 + protected $content; // 输出类型 protected $type; // 当前的contentType @@ -98,26 +100,21 @@ class Response /** * 发送数据到客户端 * @access public - * @param mixed $data 数据 * @return mixed * @throws \InvalidArgumentException */ - public function send($data = null) + public function send() { - $data = !is_null($data) ? $data : $this->data; - if (isset($this->contentType)) { $this->contentType($this->contentType); } - if (is_callable($this->transform)) { - $data = call_user_func_array($this->transform, [$data]); - } - defined('RESPONSE_TYPE') or define('RESPONSE_TYPE', $this->type); // 处理输出数据 - $data = $this->output($data); + $data = $this->getTransformData(); + // 输出数据赋值 + $this->content = $data; // 监听response_data Hook::listen('response_data', $data, $this); @@ -147,6 +144,22 @@ class Response return $data; } + /** + * 处理数据 + * @access protected + * @param mixed $data 要处理的数据 + * @return mixed + */ + protected function getTransformData() + { + if (is_callable($this->transform)) { + $data = call_user_func_array($this->transform, [$this->data]); + }else{ + $data = $this->data; + } + return $this->output($data); + } + /** * 处理数据 * @access protected @@ -319,7 +332,7 @@ class Response } /** - * 获取数据 + * 获取原始数据 * @return mixed */ public function getData() @@ -327,6 +340,15 @@ class Response return $this->data; } + /** + * 获取输出数据 + * @return mixed + */ + public function getContent() + { + return $this->content; + } + /** * 获取输出类型 * @return string @@ -335,4 +357,13 @@ class Response { return $this->type; } + + /** + * 获取状态码 + * @return integer + */ + public function getCode() + { + return $this->header['status']; + } } diff --git a/start.php b/start.php index be2b2ba9..036716bc 100644 --- a/start.php +++ b/start.php @@ -64,5 +64,8 @@ if (isset($mode['tags'])) { // 是否自动运行 if (APP_AUTO_RUN) { - App::run(); + $response = App::run(); + if($response instanceof Response){ + $response->send(); + } } diff --git a/tests/thinkphp/library/think/appTest.php b/tests/thinkphp/library/think/appTest.php index d959ff83..0f9173ac 100644 --- a/tests/thinkphp/library/think/appTest.php +++ b/tests/thinkphp/library/think/appTest.php @@ -50,7 +50,7 @@ class appTest extends \PHPUnit_Framework_TestCase { Config::set('root_namespace', ['/path/']); - App::run(Request::instance()); + App::run(Request::instance())->send(); $expectOutputString = '

:)

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

[ V5.0 版本由 七牛云 独家赞助发布 ]
'; $this->expectOutputString($expectOutputString); From 126bb348ca90efc11bb94982721043c6fa400219 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 13 Jun 2016 16:54:07 +0800 Subject: [PATCH 344/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BResponse=E7=B1=BB?= =?UTF-8?q?=E7=9A=84send=E6=96=B9=E6=B3=95=E5=92=8CgetContent=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/library/think/Response.php b/library/think/Response.php index 0024e0af..be92774d 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -22,8 +22,6 @@ class Response protected $transform; // 原始数据 protected $data; - // 输出数据 - protected $content; // 输出类型 protected $type; // 当前的contentType @@ -112,9 +110,7 @@ class Response defined('RESPONSE_TYPE') or define('RESPONSE_TYPE', $this->type); // 处理输出数据 - $data = $this->getTransformData(); - // 输出数据赋值 - $this->content = $data; + $data = $this->getContent(); // 监听response_data Hook::listen('response_data', $data, $this); @@ -144,22 +140,6 @@ class Response return $data; } - /** - * 处理数据 - * @access protected - * @param mixed $data 要处理的数据 - * @return mixed - */ - protected function getTransformData() - { - if (is_callable($this->transform)) { - $data = call_user_func_array($this->transform, [$this->data]); - }else{ - $data = $this->data; - } - return $this->output($data); - } - /** * 处理数据 * @access protected @@ -346,7 +326,12 @@ class Response */ public function getContent() { - return $this->content; + if (is_callable($this->transform)) { + $data = call_user_func_array($this->transform, [$this->data]); + }else{ + $data = $this->data; + } + return $this->output($data); } /** From 19cc11c59e9b4015827b0b8fe9b6cd4872f1d319 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Mon, 13 Jun 2016 17:05:37 +0800 Subject: [PATCH 345/670] =?UTF-8?q?Redirect=E5=A2=9E=E5=8A=A0=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E8=B7=B3=E8=BD=AC=E5=9C=B0=E5=9D=80=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/response/Redirect.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/library/think/response/Redirect.php b/library/think/response/Redirect.php index c60c007f..f6604039 100644 --- a/library/think/response/Redirect.php +++ b/library/think/response/Redirect.php @@ -39,6 +39,16 @@ class Redirect extends Response return; } + /** + * 获取跳转地址 + * @return string + */ + public function getTargetUrl() + { + $this->getContent(); + return $this->header['Location']; + } + public function params($params = []) { $this->params = $params; From 8b0078d9367d1e4845eb09a6e6a59d741585336c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 13 Jun 2016 17:05:50 +0800 Subject: [PATCH 346/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BLang=E7=B1=BB?= =?UTF-8?q?=E7=9A=84detect=E6=96=B9=E6=B3=95=20=E8=BF=94=E5=9B=9E=E5=BD=93?= =?UTF-8?q?=E5=89=8D=E8=AF=AD=E8=A8=80=20=E5=8F=96=E6=B6=88=20LANG=5FSET?= =?UTF-8?q?=20=E5=B8=B8=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 8 ++++---- library/think/Lang.php | 1 + library/think/Request.php | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 6b911fdb..c25cc92b 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -68,11 +68,11 @@ class App // 开启多语言机制 if ($config['lang_switch_on']) { // 获取当前语言 - defined('LANG_SET') or define('LANG_SET', Lang::range()); + $request->langset(Lang::detect()); // 加载系统语言包 - Lang::load(THINK_PATH . 'lang' . DS . LANG_SET . EXT); + Lang::load(THINK_PATH . 'lang' . DS . $request->langset() . EXT); if (!APP_MULTI_MODULE) { - Lang::load(APP_PATH . 'lang' . DS . LANG_SET . EXT); + Lang::load(APP_PATH . 'lang' . DS . $request->langset() . EXT); } } @@ -349,7 +349,7 @@ class App // 加载当前模块语言包 if ($config['lang_switch_on'] && $module) { - Lang::load($path . 'lang' . DS . LANG_SET . EXT); + Lang::load($path . 'lang' . DS . Request::instance()->langset() . EXT); } } return Config::get(); diff --git a/library/think/Lang.php b/library/think/Lang.php index 2a60fcbf..fe94bf7e 100644 --- a/library/think/Lang.php +++ b/library/think/Lang.php @@ -157,6 +157,7 @@ class Lang // 合法的语言 self::$range = $langSet; } + return self::$range; } /** diff --git a/library/think/Request.php b/library/think/Request.php index d4deb6f2..d10f5ddb 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -71,6 +71,7 @@ class Request protected $module; protected $controller; protected $action; + protected $langset; /** * @var array 请求参数 @@ -968,4 +969,20 @@ class Request return $this->action ?: ''; } } + + /** + * 设置或者获取当前的语言 + * @access public + * @param string $lang 语言名 + * @return string + */ + public function langset($lang = null) + { + if (!is_null($lang)) { + $this->langset = $lang; + return $this; + } else { + return $this->langset ?: ''; + } + } } From e14174fd63c6a3950f8db94ece97d35c42be0771 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 13 Jun 2016 17:51:21 +0800 Subject: [PATCH 347/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E5=92=8CRoute=E7=B1=BB=E7=9A=84checkDomain=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 5 +++++ library/think/Route.php | 12 +++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index d10f5ddb..e0648f12 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -192,6 +192,11 @@ class Request $options['cookie'] = $cookie; $options['file'] = $files; $options['server'] = $server; + $options['url'] = $server['REQUEST_URI']; + $options['baseUrl'] = $info['path']; + $options['pathinfo'] = $info['path']; + $options['method'] = $server['REQUEST_METHOD']; + $options['domain'] = $server['HTTP_HOST']; self::$instance = new self($options); return self::$instance; } diff --git a/library/think/Route.php b/library/think/Route.php index 135d5319..3f8cb56a 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -523,24 +523,26 @@ class Route /** * 检测子域名部署 * @access public + * @param \think\Request $request Request请求对象 * @return void */ - public static function checkDomain() + public static function checkDomain($request) { // 域名规则 $rules = self::$domain; // 开启子域名部署 支持二级和三级域名 if (!empty($rules)) { - if (isset($rules[$_SERVER['HTTP_HOST']])) { + $host = $request->host(); + if (isset($rules[$host])) { // 完整域名或者IP配置 - $rule = $rules[$_SERVER['HTTP_HOST']]; + $rule = $rules[$host]; } else { $rootDomain = Config::get('url_domain_root'); if ($rootDomain) { // 配置域名根 例如 thinkphp.cn 163.com.cn 如果是国家级域名 com.cn net.cn 之类的域名需要配置 - $domain = explode('.', rtrim(stristr($_SERVER['HTTP_HOST'], $rootDomain, true), '.')); + $domain = explode('.', rtrim(stristr($host, $rootDomain, true), '.')); } else { - $domain = explode('.', $_SERVER['HTTP_HOST'], -2); + $domain = explode('.', $host, -2); } // 子域名配置 if (!empty($domain)) { From eb026e02a603f40a173f3cfd8e67f30f903f3ae7 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Mon, 13 Jun 2016 18:48:07 +0800 Subject: [PATCH 348/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Bconsole=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 79 +++++++++++++++++----------- library/think/Console.php | 38 ++++++++++---- mode/console.php | 31 ----------- mode/console/App.php | 107 -------------------------------------- 4 files changed, 77 insertions(+), 178 deletions(-) delete mode 100644 mode/console.php delete mode 100644 mode/console/App.php diff --git a/library/think/App.php b/library/think/App.php index c25cc92b..5dc27bf3 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -29,6 +29,11 @@ use think\Route; */ class App { + /** + * @var bool 是否初始化过 + */ + protected static $init = false; + /** * 执行应用程序 * @access public @@ -40,30 +45,9 @@ class App { is_null($request) && $request = Request::instance(); - // 初始化应用 - $config = self::init('', Config::get()); - - // 注册根命名空间 - if (!empty($config['root_namespace'])) { - Loader::addNamespace($config['root_namespace']); - } - - // 加载额外文件 - 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)) { - include_once $file; - } - } - } - - // 设置系统时区 - date_default_timezone_set($config['default_timezone']); + $config = self::initCommon(); try { - // 监听app_init - Hook::listen('app_init'); // 开启多语言机制 if ($config['lang_switch_on']) { @@ -136,7 +120,7 @@ class App * 执行函数或者闭包方法 支持参数调用 * @access public * @param string|array|\Closure $function 函数或者闭包 - * @param array $vars 变量 + * @param array $vars 变量 * @return mixed */ public static function invokeFunction($function, $vars = []) @@ -152,7 +136,7 @@ class App * 调用反射执行类的方法 支持参数绑定 * @access public * @param string|array $method 方法 - * @param array $vars 变量 + * @param array $vars 变量 * @return mixed */ public static function invokeMethod($method, $vars = []) @@ -178,7 +162,7 @@ class App * 绑定参数 * @access public * @param \ReflectionMethod $reflect 反射类 - * @param array $vars 变量 + * @param array $vars 变量 * @return array */ private static function bindParams($reflect, $vars) @@ -239,7 +223,7 @@ class App // 模块初始化 if ($module && $available) { // 初始化模块 - $config = self::init($module, $config); + $config = self::init($module); } else { throw new HttpException(404, 'module [ ' . $module . ' ] not exists '); } @@ -299,14 +283,47 @@ class App return $data; } + /** + * 初始化公共配置 + */ + public static function initCommon() + { + if (empty(self::$init)) { + // 初始化应用 + self::$init = $config = self::init(); + + // 注册根命名空间 + if (!empty($config['root_namespace'])) { + Loader::addNamespace($config['root_namespace']); + } + + // 加载额外文件 + 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)) { + include_once $file; + } + } + } + + // 设置系统时区 + date_default_timezone_set($config['default_timezone']); + + // 监听app_init + Hook::listen('app_init'); + } + return self::$init; + } + + /** * 初始化应用或模块 * @access public * @param string $module 模块名 - * @param array $config 配置参数 - * @return void + * @return array */ - private static function init($module, $config) + private static function init($module = '') { // 定位模块目录 $module = ($module && APP_MULTI_MODULE) ? $module . DS : ''; @@ -359,9 +376,9 @@ class App * URL路由检测(根据PATH_INFO) * @access public * @param \think\Request $request - * @param array $config + * @param array $config * @return array - * @throws HttpException + * @throws \think\Exception */ public static function route($request, array $config) { diff --git a/library/think/Console.php b/library/think/Console.php index c4d96f59..3dc31467 100644 --- a/library/think/Console.php +++ b/library/think/Console.php @@ -66,6 +66,26 @@ class Console } } + public static function init() + { + // 实例化console + $console = new self('Think Console', '0.1'); + // 读取指令集 + if (is_file(CONF_PATH . 'command' . EXT)) { + $commands = include CONF_PATH . 'command' . EXT; + if (is_array($commands)) { + foreach ($commands as $command) { + if (class_exists($command) && is_subclass_of($command, "\\think\\console\\command\\Command")) { + // 注册指令 + $console->add(new $command()); + } + } + } + } + // 运行 + $console->run(); + } + /** * 执行当前的指令 * @return int @@ -90,7 +110,7 @@ class Console $exitCode = $e->getCode(); if (is_numeric($exitCode)) { - $exitCode = (int) $exitCode; + $exitCode = (int)$exitCode; if (0 === $exitCode) { $exitCode = 1; } @@ -201,7 +221,7 @@ class Console */ public function setCatchExceptions($boolean) { - $this->catchExceptions = (bool) $boolean; + $this->catchExceptions = (bool)$boolean; } /** @@ -211,7 +231,7 @@ class Console */ public function setAutoExit($boolean) { - $this->autoExit = (bool) $boolean; + $this->autoExit = (bool)$boolean; } /** @@ -379,7 +399,7 @@ class Console $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]) . '[^:]*'; }, $namespace); - $namespaces = preg_grep('{^' . $expr . '}', $allNamespaces); + $namespaces = preg_grep('{^' . $expr . '}', $allNamespaces); if (empty($namespaces)) { $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace); @@ -417,7 +437,7 @@ class Console $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]) . '[^:]*'; }, $name); - $commands = preg_grep('{^' . $expr . '}', $allCommands); + $commands = preg_grep('{^' . $expr . '}', $allCommands); if (empty($commands) || count(preg_grep('{^' . $expr . '$}', $commands)) < 1) { if (false !== $pos = strrpos($name, ':')) { @@ -606,19 +626,19 @@ class Console if ('\\' === DS) { if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) { - return [(int) $matches[1], (int) $matches[2]]; + return [(int)$matches[1], (int)$matches[2]]; } if (preg_match('/^(\d+)x(\d+)$/', $this->getConsoleMode(), $matches)) { - return [(int) $matches[1], (int) $matches[2]]; + return [(int)$matches[1], (int)$matches[2]]; } } if ($sttyString = $this->getSttyColumns()) { if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) { - return [(int) $matches[2], (int) $matches[1]]; + return [(int)$matches[2], (int)$matches[1]]; } if (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) { - return [(int) $matches[2], (int) $matches[1]]; + return [(int)$matches[2], (int)$matches[1]]; } } diff --git a/mode/console.php b/mode/console.php deleted file mode 100644 index 4b1be21b..00000000 --- a/mode/console.php +++ /dev/null @@ -1,31 +0,0 @@ - -// +---------------------------------------------------------------------- - -/** - * ThinkPHP CLI模式定义 - */ -return [ - - // 命名空间 - 'namespace' => [ - 'think' => LIB_PATH . 'think' . DS, - 'behavior' => LIB_PATH . 'behavior' . DS, - 'traits' => LIB_PATH . 'traits' . DS, - APP_NAMESPACE => APP_PATH, - ], - // 别名定义 - 'alias' => [ - 'think\App' => MODE_PATH . 'console' . DS . 'App' . EXT, - ], - // 配置文件 - 'config' => THINK_PATH . 'convention' . EXT, - -]; diff --git a/mode/console/App.php b/mode/console/App.php deleted file mode 100644 index 7376a84a..00000000 --- a/mode/console/App.php +++ /dev/null @@ -1,107 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace think; - -use think\Console; - -class App -{ - /** - * 执行应用程序 - * @access public - * @return void - */ - public static function run() - { - self::init(); - - // 实例化console - $console = new Console('Think Console', '0.1'); - // 读取指令集 - if (is_file(CONF_PATH . 'command' . EXT)) { - $commands = include CONF_PATH . 'command' . EXT; - if (is_array($commands)) { - foreach ($commands as $command) { - if (class_exists($command) && is_subclass_of($command, "\\think\\console\\command\\Command")) { - // 注册指令 - $console->add(new $command()); - } - } - } - } - // 运行 - $console->run(); - } - - private static function init() - { - // 加载初始化文件 - if (is_file(APP_PATH . 'init' . EXT)) { - include APP_PATH . 'init' . EXT; - - // 加载模块配置 - $config = Config::get(); - } else { - // 加载模块配置 - $config = Config::load(CONF_PATH . 'config' . CONF_EXT); - - // 加载应用状态配置 - if ($config['app_status']) { - $config = Config::load(CONF_PATH . $config['app_status'] . CONF_EXT); - } - - // 读取扩展配置文件 - if ($config['extra_config_list']) { - foreach ($config['extra_config_list'] as $name => $file) { - $filename = CONF_PATH . $file . CONF_EXT; - Config::load($filename, is_string($name) ? $name : pathinfo($filename, PATHINFO_FILENAME)); - } - } - - // 加载别名文件 - if (is_file(CONF_PATH . 'alias' . EXT)) { - Loader::addMap(include CONF_PATH . 'alias' . EXT); - } - - // 加载行为扩展文件 - if (is_file(CONF_PATH . 'tags' . EXT)) { - Hook::import(include CONF_PATH . 'tags' . EXT); - } - - // 加载公共文件 - if (is_file(APP_PATH . 'common' . EXT)) { - include APP_PATH . 'common' . EXT; - } - } - - // 注册根命名空间 - if (!empty($config['root_namespace'])) { - Loader::addNamespace($config['root_namespace']); - } - - // 加载额外文件 - 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)) { - include_once $file; - } - } - } - - // 设置系统时区 - date_default_timezone_set($config['default_timezone']); - - // 监听app_init - Hook::listen('app_init'); - } -} From 1914fcad4daf2ca3c806b02fbb4883b136709901 Mon Sep 17 00:00:00 2001 From: jay <917647288@qq.com> Date: Tue, 14 Jun 2016 00:15:03 +0800 Subject: [PATCH 349/670] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=BA=E9=80=82?= =?UTF-8?q?=E5=90=88=E6=9C=80=E6=96=B0=E7=89=88=E6=9C=AC=E7=9A=84=E6=B5=8F?= =?UTF-8?q?=E8=A7=88=E5=99=A8=E8=BE=93=E5=87=BA=20Browser=20trace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支持数组的前端显示,对象的有问题。采用分组模式 --- library/think/log/driver/Browser.php | 140 ++++++++++++++++++++------- 1 file changed, 104 insertions(+), 36 deletions(-) diff --git a/library/think/log/driver/Browser.php b/library/think/log/driver/Browser.php index 1f8597de..a86fb142 100644 --- a/library/think/log/driver/Browser.php +++ b/library/think/log/driver/Browser.php @@ -1,14 +1,18 @@ 'File', + 'trace_tabs' => ['base' => '基本', 'file' => '文件', 'info' => '流程', 'notice|error' => '错误', 'sql' => 'SQL', 'debug|log' => '调试'], ]; // 实例化并传入参数 @@ -27,52 +31,116 @@ class Browser */ public function save(array $log = []) { - $request = Request::instance(); - $type = $request->type(); - $type = config('default_return_type'); - //输出到控制台 - if(in_array($type, ['html', 'txt'])){ - $lines = []; - foreach ($log as $key => $l) { - $lines[] = $this->output($l['type'], $l['msg']); + if (IS_CLI || IS_API || Request::instance()->isAjax() || (defined('RESPONSE_TYPE') && !in_array(RESPONSE_TYPE, ['html', 'view']))) { + // ajax cli api方式下不输出 + return false; + } + // 获取基本信息 + $runtime = microtime(true) - START_TIME; + $reqs = number_format(1 / number_format($runtime, 8), 2); + $runtime = number_format($runtime, 6); + $mem = number_format((memory_get_usage() - START_MEM) / 1024, 2); + + // 页面Trace信息 + $base = [ + '请求信息' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']) . ' ' . $_SERVER['SERVER_PROTOCOL'] . ' ' . $_SERVER['REQUEST_METHOD'] . ' : ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], + '运行时间' => "{$runtime}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()), + ]; + + if (session_id()) { + $base['会话信息'] = 'SESSION_ID=' . session_id(); + } + + $info = Debug::getFile(true); + + // 获取调试日志 + $debug = []; + foreach ($log as $type => $val) { + foreach ($val as $msg) { + $debug[$type][] = $msg; } - $lines = implode(PHP_EOL, $lines); - $js = <<config['trace_tabs'] as $name => $title) { + $name = strtolower($name); + switch ($name) { + case 'base': // 基本信息 + $trace[$title] = $base; + break; + case 'file': // 文件信息 + $trace[$title] = $info; + break; + default: // 调试信息 + if (strpos($name, '|')) { + // 多组信息 + $names = explode('|', $name); + $result = []; + foreach ($names as $name) { + $result = array_merge($result, isset($debug[$name]) ? $debug[$name] : []); + } + $trace[$title] = $result; + } else { + $trace[$title] = isset($debug[$name]) ? $debug[$name] : ''; + } + } + } + + //输出到控制台 + $lines = ''; + foreach ($trace as $type => $msg) { + $lines .= $this->output($type, $msg); + } + $js = << {$lines} JS; - echo $js; - }else{ - $other_save = $this->config['notview_save']; - // $other_save = "\think\log\driver\"".$other_save; - $other_save = 'think\log\driver\\'.$other_save; - $other_save_class = new $other_save(); - $other_save_class->save($log); - } + echo $js; + return true; } public function output($type, $msg){ - // dump($type); - // dump($msg); - $msg = str_replace(PHP_EOL, '\n', $msg); - if(in_array($type, ['info', 'log', 'error', 'warn', 'debug'])){ - $style = ''; - if('error' == $type){ - $style = 'color:#F4006B;font-size:14px;'; - } - $line = "console.{$type}(\"%c{$msg}\", \"{$style}\");"; - }else{ - if('sql' == $type){ - $style = "color:#009bb4;"; - $line = "console.log(\"%c{$msg}\", \"{$style}\");"; - }else{ - $line = "alert(\"{$msg}\");"; + $type = strtolower($type); + $line[] = "console.group('{$type}');"; + foreach ($msg as $key => $m) { + switch ($type) { + case '调试': + //我多么希望进来的是原数据格式而不是字符串 + if(substr($m, 0, 5) == 'array'){ + eval("\$o = $m;"); + $line[] = "console.log(".json_encode($o).");"; + }else{ + $msg = addslashes($m); + $msg = str_replace(PHP_EOL, '\n', $msg); + $line[] = "console.log('$msg');"; + } + break; + case 'error': + $msg = str_replace(PHP_EOL, '\n', $m); + $style = 'color:#F4006B;font-size:14px;'; + $line[] = "console.log(\"%c{$msg}\", \"{$style}\");"; + break; + case 'sql': + $msg = str_replace(PHP_EOL, '\n', $m); + $style = "color:#009bb4;"; + $line[] = "console.log(\"%c{$msg}\", \"{$style}\");"; + break; + default: + $m = is_string($key)? $key.' '.$m: $key+1 .' '.$m; + $msg = str_replace(PHP_EOL, '\n', $m); + $line[] = "console.log(\"{$msg}\");"; + break; } } - return $line; + $line[]= "console.groupEnd();"; + return implode(PHP_EOL, $line); } } From 87a3c5577cffb82cf3ac5864de41b49e0b26a126 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 08:12:14 +0800 Subject: [PATCH 350/670] =?UTF-8?q?APP=5FMULTI=5FMODULE=E5=B8=B8=E9=87=8F?= =?UTF-8?q?=E6=94=B9=E4=B8=BAapp=5Fmulti=5Fmodule=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 1 - convention.php | 2 ++ library/think/App.php | 6 +++--- library/think/Build.php | 2 +- library/think/Loader.php | 2 +- library/think/Route.php | 4 ++-- tests/thinkphp/library/think/appTest.php | 3 +-- tests/thinkphp/library/think/routeTest.php | 13 ++++++------- tests/thinkphp/library/think/urlTest.php | 2 ++ 9 files changed, 18 insertions(+), 17 deletions(-) diff --git a/base.php b/base.php index 64ed27a3..59b265e3 100644 --- a/base.php +++ b/base.php @@ -30,7 +30,6 @@ defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH . 'temp' . DS); defined('APP_NAMESPACE') or define('APP_NAMESPACE', 'app'); defined('CONF_PATH') or define('CONF_PATH', APP_PATH); // 配置文件目录 defined('CONF_EXT') or define('CONF_EXT', EXT); // 配置文件后缀 -defined('APP_MULTI_MODULE') or define('APP_MULTI_MODULE', true); // 是否多模块 defined('ENV_PREFIX') or define('ENV_PREFIX', 'PHP_'); // 环境变量的配置前缀 defined('IS_API') or define('IS_API', false); // 是否API接口 defined('APP_AUTO_RUN') or define('APP_AUTO_RUN', true); // 是否自动运行 diff --git a/convention.php b/convention.php index cfed3f30..d1e1edd9 100644 --- a/convention.php +++ b/convention.php @@ -7,6 +7,8 @@ return [ // 应用模式状态 'app_status' => '', + // 是否支持多模块 + 'app_multi_module' => true, // 注册的根命名空间 'root_namespace' => [], // 扩展配置文件 diff --git a/library/think/App.php b/library/think/App.php index 5dc27bf3..22aa01dc 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -55,7 +55,7 @@ class App $request->langset(Lang::detect()); // 加载系统语言包 Lang::load(THINK_PATH . 'lang' . DS . $request->langset() . EXT); - if (!APP_MULTI_MODULE) { + if (!$config['app_multi_module']) { Lang::load(APP_PATH . 'lang' . DS . $request->langset() . EXT); } } @@ -205,7 +205,7 @@ class App if (is_string($result)) { $result = explode('/', $result); } - if (APP_MULTI_MODULE) { + if ($config['app_multi_module']) { // 多模块部署 $module = strip_tags(strtolower($result[0] ?: $config['default_module'])); $bind = Route::bind('module'); @@ -326,7 +326,7 @@ class App private static function init($module = '') { // 定位模块目录 - $module = ($module && APP_MULTI_MODULE) ? $module . DS : ''; + $module = ($module) ? $module . DS : ''; // 加载初始化文件 if (is_file(APP_PATH . $module . 'init' . EXT)) { diff --git a/library/think/Build.php b/library/think/Build.php index 0f23a113..ed510e39 100644 --- a/library/think/Build.php +++ b/library/think/Build.php @@ -88,7 +88,7 @@ class Build */ public static function module($module = '', $list = []) { - $module = APP_MULTI_MODULE ? $module : ''; + $module = $module ? $module : ''; if (!is_dir(APP_PATH . $module)) { // 创建模块目录 mkdir(APP_PATH . $module); diff --git a/library/think/Loader.php b/library/think/Loader.php index 27ad52f2..6c5cad6a 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -463,6 +463,6 @@ class Loader $array = explode('\\', $name); $class = self::parseName(array_pop($array), 1) . (CLASS_APPEND_SUFFIX || $appendSuffix ? ucfirst($layer) : ''); $path = $array ? implode('\\', $array) . '\\' : ''; - return APP_NAMESPACE . '\\' . (APP_MULTI_MODULE ? $module . '\\' : '') . $layer . '\\' . $path . $class; + return APP_NAMESPACE . '\\' . ($module ? $module . '\\' : '') . $layer . '\\' . $path . $class; } } diff --git a/library/think/Route.php b/library/think/Route.php index 3f8cb56a..96cb3640 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -1004,7 +1004,7 @@ class Route if (isset($path)) { if ($reverse) { // 解析模块 - $module = APP_MULTI_MODULE ? array_shift($path) : null; + $module = Config::get('app_multi_module') ? array_shift($path) : null; if ($autoSearch) { // 自动搜索控制器 $dir = APP_PATH . ($module ? $module . DS : '') . 'controller'; @@ -1038,7 +1038,7 @@ class Route } else { $action = array_pop($path); $controller = !empty($path) ? array_pop($path) : null; - $module = APP_MULTI_MODULE && !empty($path) ? array_pop($path) : null; + $module = Config::get('app_multi_module') && !empty($path) ? array_pop($path) : null; $method = Request::instance()->method(); // REST 操作方法支持 if ('[rest]' == $action) { diff --git a/tests/thinkphp/library/think/appTest.php b/tests/thinkphp/library/think/appTest.php index 0f9173ac..b29bd459 100644 --- a/tests/thinkphp/library/think/appTest.php +++ b/tests/thinkphp/library/think/appTest.php @@ -49,8 +49,7 @@ class appTest extends \PHPUnit_Framework_TestCase public function testRun() { Config::set('root_namespace', ['/path/']); - - App::run(Request::instance())->send(); + App::run(Request::create("http://www.example.com"))->send(); $expectOutputString = '

:)

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

[ V5.0 版本由 七牛云 独家赞助发布 ]
'; $this->expectOutputString($expectOutputString); diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index 5c9e5dd4..0b0314c2 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -168,29 +168,28 @@ class routeTest extends \PHPUnit_Framework_TestCase public function testDomain() { - $_SERVER['HTTP_HOST'] = 'subdomain.thinkphp.cn'; - $_SERVER['REQUEST_URI'] = ''; + $request = Request::create('http://subdomain.thinkphp.cn'); Route::domain('subdomain.thinkphp.cn', 'sub?abc=test&status=1'); - Route::checkDomain(); + Route::checkDomain($request); $this->assertEquals('sub?abc=test&status=1', Route::domain('subdomain.thinkphp.cn')); $this->assertEquals('sub', Route::bind('module')); $this->assertEquals('test', $_GET['abc']); $this->assertEquals(1, $_GET['status']); Route::domain('subdomain.thinkphp.cn', function () {return ['type' => 'module', 'module' => 'sub2'];}); - Route::checkDomain(); + Route::checkDomain($request); $this->assertEquals('sub2', Route::bind('module')); Route::domain('subdomain.thinkphp.cn', '\app\index\controller'); - Route::checkDomain(); + Route::checkDomain($request); $this->assertEquals('\app\index\controller', Route::bind('namespace')); Route::domain('subdomain.thinkphp.cn', '@\app\index\controller\blog'); - Route::checkDomain(); + Route::checkDomain($request); $this->assertEquals('\app\index\controller\blog', Route::bind('class')); Route::domain('subdomain.thinkphp.cn', '[sub3]'); - Route::checkDomain(); + Route::checkDomain($request); $this->assertEquals('sub3', Route::bind('group')); } } diff --git a/tests/thinkphp/library/think/urlTest.php b/tests/thinkphp/library/think/urlTest.php index a82c0936..96fa0788 100644 --- a/tests/thinkphp/library/think/urlTest.php +++ b/tests/thinkphp/library/think/urlTest.php @@ -29,6 +29,7 @@ class urlTest extends \PHPUnit_Framework_TestCase 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')); @@ -41,6 +42,7 @@ class urlTest extends \PHPUnit_Framework_TestCase 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')); From 9bfeeb8ac695a2f0211b8255bbd4b38c65013794 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 08:37:14 +0800 Subject: [PATCH 351/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84selectInsert=E6=96=B9=E6=B3=95=20=E5=AF=B9=20table?= =?UTF-8?q?=E5=8F=82=E6=95=B0=E7=9A=84=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 1 + 1 file changed, 1 insertion(+) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 977cdc4c..1eb3f722 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1602,6 +1602,7 @@ class Query // 分析查询表达式 $options = $this->parseExpress(); // 生成SQL语句 + $table = $this->parseSqlTable($table); $sql = $this->builder()->selectInsert($fields, $table, $options); if($options['fetch_sql']){ // 获取实际执行的SQL语句 From 4993f4a0cb5984f63d1a8733ee1dca9d8c5e9ceb Mon Sep 17 00:00:00 2001 From: jay <917647288@qq.com> Date: Tue, 14 Jun 2016 08:44:55 +0800 Subject: [PATCH 352/670] =?UTF-8?q?=E5=88=86=E7=BB=84=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E5=B1=95=E5=BC=80=E5=9F=BA=E6=9C=AC=E5=92=8C=E8=B0=83=E8=AF=95?= =?UTF-8?q?=E5=92=8C=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/Browser.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/library/think/log/driver/Browser.php b/library/think/log/driver/Browser.php index a86fb142..66106846 100644 --- a/library/think/log/driver/Browser.php +++ b/library/think/log/driver/Browser.php @@ -108,7 +108,11 @@ JS; public function output($type, $msg){ $type = strtolower($type); - $line[] = "console.group('{$type}');"; + $trace_tabs = array_values($this->config['trace_tabs']); + $line[] = ($type == $trace_tabs[0] || '调试' == $type || '错误'== $type)? + "console.group('{$type}');" + : + "console.groupCollapsed('{$type}');"; foreach ($msg as $key => $m) { switch ($type) { case '调试': @@ -122,10 +126,11 @@ JS; $line[] = "console.log('$msg');"; } break; - case 'error': + case '错误': $msg = str_replace(PHP_EOL, '\n', $m); $style = 'color:#F4006B;font-size:14px;'; - $line[] = "console.log(\"%c{$msg}\", \"{$style}\");"; + $line[] = "console.error(\"%c{$msg}\", \"{$style}\");"; + // $line[] = "console.error(".json_encode(debug_backtrace()).");"; break; case 'sql': $msg = str_replace(PHP_EOL, '\n', $m); From b1f4125678d8ae048b742ea09610ad303a110e84 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 10:14:48 +0800 Subject: [PATCH 353/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/thinkphp/library/think/routeTest.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index 0b0314c2..f3222c8d 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -22,6 +22,11 @@ use think\Route; class routeTest extends \PHPUnit_Framework_TestCase { + protected function setUp() + { + Config::set('app_multi_module',true); + } + public function testRegister() { $request = Request::instance(); From fbb792eb2e8a31aecc95c8b00dd6c721844fcaa2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 10:32:13 +0800 Subject: [PATCH 354/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BBuilder=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E6=97=B6=E9=97=B4=E6=97=A5=E6=9C=9F=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Builder.php | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index c3bdf253..67566972 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -369,15 +369,13 @@ abstract class Builder // 获取时间字段类型 $type = $this->query->getTableInfo('', 'type'); if(isset($type[$key])){ + $value = strtotime($value) ?: $value; if(preg_match('/(datetime|timestamp)/is', $type[$key])){ // 日期及时间戳类型 - $value = date('Y-m-d H:i:s', strtotime($value)); + $value = date('Y-m-d H:i:s', $value); }elseif(preg_match('/(date)/is', $type[$key])){ // 日期及时间戳类型 - $value = date('Y-m-d', strtotime($value)); - }else{ - // 整型 - $value = strtotime($value); + $value = date('Y-m-d', $value); } } return is_int($value)? $value : $this->connection->quote($value); From 2e35cf1cb04e5c0fe1472697beb57485574e6ebe Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 10:52:21 +0800 Subject: [PATCH 355/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BResponse=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getCode=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Response.php b/library/think/Response.php index be92774d..c986e5a8 100644 --- a/library/think/Response.php +++ b/library/think/Response.php @@ -349,6 +349,6 @@ class Response */ public function getCode() { - return $this->header['status']; + return isset($this->header['status']) ? $this->header['status'] : 200; } } From af648cfa8d5ac45587ad6ada306f3547ba7cd19a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 11:49:07 +0800 Subject: [PATCH 356/670] =?UTF-8?q?ViewResponse=E7=B1=BB=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?getVars=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/response/View.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/library/think/response/View.php b/library/think/response/View.php index e92cd052..224e3b60 100644 --- a/library/think/response/View.php +++ b/library/think/response/View.php @@ -38,7 +38,7 @@ class View extends Response /** * 视图变量赋值 - * @access protected + * @access public * @param array $vars 模板变量 * @return $this */ @@ -48,6 +48,21 @@ class View extends Response return $this; } + /** + * 获取视图变量 + * @access public + * @param string $name 模板变量 + * @return mixed + */ + public function getVars($name = null) + { + if(is_null($name)){ + return $this->vars; + }else{ + return isset($this->vars[$name]) ? $this->vars[$name] : null; + } + } + /** * 模板变量赋值 * @access public From 8fa12a4d1602fea79a24f45809c171965fd2383e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 12:23:44 +0800 Subject: [PATCH 357/670] =?UTF-8?q?Query=E7=B1=BB=E7=9A=84datetime?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E6=9B=B4=E6=94=B9=E4=B8=BAwhereTime=E6=96=B9?= =?UTF-8?q?=E6=B3=95=20=E5=B9=B6=E6=94=AF=E6=8C=81=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=E8=A1=A8=E8=BE=BE=E5=BC=8F=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 1eb3f722..48d118b1 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1231,12 +1231,43 @@ class Query * 查询日期或者时间 * @access public * @param string $field 日期字段名 - * @param string $op 比较运算 > < between not between + * @param string $op 比较运算符或者表达式 * @param string|array $range 比较范围 * @return $this */ - public function datetime($field, $op, $range = []) + public function whereTime($field, $op, $range = null) { + if(is_null($range)){ + // 使用日期表达式 + $date = getdate(); + switch(strtolower($op)){ + case 'today': + $range = 'today'; + break; + case 'week': + $range = 'this week 00:00:00'; + break; + case 'month': + $range = mktime(0, 0, 0, $date['mon'], 1, $date['year']); + break; + case 'year': + $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); return $this; } From 5f76cd826a580cdae5836bc2129d95a0036582a8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 12:29:05 +0800 Subject: [PATCH 358/670] =?UTF-8?q?Query=E7=B1=BBwhereTime=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=94=B9=E8=BF=9B=20=E6=94=AF=E6=8C=81=E6=97=A5?= =?UTF-8?q?=E6=9C=9F=E8=A1=A8=E8=BE=BE=E5=BC=8F=E7=9A=84=E7=BC=A9=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 48d118b1..fa771afc 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1242,15 +1242,19 @@ class Query $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': From c5bde960863664f316afe90562d2b82d7799f6b4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 12:34:08 +0800 Subject: [PATCH 359/670] =?UTF-8?q?Cookie=E7=B1=BB=E5=A2=9E=E5=8A=A0has?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Cookie.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/library/think/Cookie.php b/library/think/Cookie.php index d21f3226..30ff81d4 100644 --- a/library/think/Cookie.php +++ b/library/think/Cookie.php @@ -95,6 +95,19 @@ class Cookie $_COOKIE[$name] = $value; } + /** + * 判断Cookie数据 + * @param string $name cookie名称 + * @param string|null $prefix cookie前缀 + * @return bool + */ + public static function has($name, $prefix = null) + { + $prefix = !is_null($prefix) ? $prefix : self::$config['prefix']; + $name = $prefix . $name; + return isset($_COOKIE[$name]) ? $value: null; + } + /** * Cookie获取 * @param string $name cookie名称 From fb188291d5c550c0741f0bbd04c53dabee69efe8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 12:53:45 +0800 Subject: [PATCH 360/670] =?UTF-8?q?File=E7=B1=BB=E6=94=B9=E8=BF=9B?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 14 +++++++++++--- library/think/Input.php | 12 ++++++++++-- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/library/think/File.php b/library/think/File.php index 9ce8f36e..e9111235 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -22,14 +22,17 @@ class File extends SplFileObject private $error = ''; // 文件上传命名规则 protected $rule = 'date'; + // 单元测试 + protected $isTest; // 上传文件信息 protected $info; - public function __construct($filename, $info = []) + public function __construct($filename, $info = [],$isTest=false) { parent::__construct($filename); - $this->info = $info; + $this->info = $info; + $this->isTest = $isTest; } /** @@ -88,6 +91,9 @@ class File extends SplFileObject */ public function isValid() { + if($this->isTest){ + return is_file($this->getRealPath()); + } return is_uploaded_file($this->getRealPath()); } @@ -122,7 +128,9 @@ class File extends SplFileObject } /* 移动文件 */ - if (!move_uploaded_file($this->getRealPath(), $path . $savename)) { + if($this->isTest){ + rename($this->getRealPath(),$path.$savename); + } elseif (!move_uploaded_file($this->getRealPath(), $path . $savename)) { $this->error = '文件上传保存错误!'; return false; } diff --git a/library/think/Input.php b/library/think/Input.php index 8bb5334d..21953722 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -241,11 +241,19 @@ class Input if (empty($val['tmp_name'])) { continue; } - $item[$key] = new File($val['tmp_name'], $val); + if($val instanceof File){ + $item[$key] = $val; + }else{ + $item[$key] = new File($val['tmp_name'], $val); + } } return $item; } elseif (isset($array[$name])) { - return new File($array[$name]['tmp_name'], $array[$name]); + if($array[$name] instanceof File){ + return $array[$name]; + }else{ + return new File($array[$name]['tmp_name'], $array[$name]); + } } } return null; From c9155c016dab28c891ea62f1504e0c7c6c48c13d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 14:06:40 +0800 Subject: [PATCH 361/670] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E7=9A=84=E6=95=B0=E6=8D=AE=E9=9B=86=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E6=94=B9=E4=B8=BA=E5=AD=97=E7=AC=A6=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Db.php | 6 ------ library/think/db/Connection.php | 8 +++----- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/library/think/Db.php b/library/think/Db.php index a75764b7..06ba04c7 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -39,12 +39,6 @@ use think\db\Query; */ class Db { - // 数组数据集 - const RESULTSET_ARRAY = 1; - // 对象数据集 - const RESULTSET_COLLECTION = 2; - // 自定义对象数据集 - const RESULTSET_CLASS = 3; // 数据库连接实例 private static $instance = []; // 查询次数 diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index ab18a719..f927acd0 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -50,7 +50,7 @@ abstract class Connection protected $linkWrite; // 查询结果类型 - protected $resultSetType = Db::RESULTSET_ARRAY; + protected $resultSetType = 'array'; // 查询结果类型 protected $fetchType = PDO::FETCH_ASSOC; // 字段属性大小写 @@ -485,13 +485,11 @@ abstract class Connection return new $class($result); } switch ($this->resultSetType) { - case Db::RESULTSET_COLLECTION: + case 'collection': // 返回数据集Collection对象 $result = new Collection($result); break; - case Db::RESULTSET_CLASS: - break; - case Db::RESULTSET_ARRAY: + case 'array': default: // 返回二维数组 } From 15aeb6d7f47d48242b9042b0357e9519d6cbdc34 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 14:24:25 +0800 Subject: [PATCH 362/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BLog=E7=B1=BB=E7=9A=84?= =?UTF-8?q?record=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Log.php | 6 ------ library/think/log/driver/File.php | 3 +++ library/think/log/driver/Sae.php | 3 +++ library/think/log/driver/Socket.php | 3 +++ library/think/log/driver/Trace.php | 3 +++ 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/library/think/Log.php b/library/think/Log.php index 65c2cd4c..76474c21 100644 --- a/library/think/Log.php +++ b/library/think/Log.php @@ -80,9 +80,6 @@ class Log */ public static function record($msg, $type = 'log') { - if (!is_string($msg)) { - $msg = var_export($msg, true); - } self::$log[$type][] = $msg; } @@ -153,9 +150,6 @@ class Log */ public static function write($msg, $type = 'log') { - if (!is_string($msg)) { - $msg = var_export($msg, true); - } // 封装日志信息 $log[$type][] = $msg; diff --git a/library/think/log/driver/File.php b/library/think/log/driver/File.php index 62cb9827..81053045 100644 --- a/library/think/log/driver/File.php +++ b/library/think/log/driver/File.php @@ -65,6 +65,9 @@ class File $info = '[ log ] ' . $current_uri . $time_str . $memory_str . $file_load . "\r\n"; foreach ($log as $type => $val) { foreach ($val as $msg) { + if (!is_string($msg)) { + $msg = var_export($msg, true); + } $info .= '[ ' . $type . ' ] ' . $msg . "\r\n"; } } diff --git a/library/think/log/driver/Sae.php b/library/think/log/driver/Sae.php index 036245dd..d9ca44fe 100644 --- a/library/think/log/driver/Sae.php +++ b/library/think/log/driver/Sae.php @@ -44,6 +44,9 @@ class Sae $info = '[ log ] ' . $current_uri . $time_str . $memory_str . $file_load . "\r\n"; foreach ($log as $type => $val) { foreach ($val as $msg) { + if (!is_string($msg)) { + $msg = var_export($msg, true); + } $info .= '[ ' . $type . ' ] ' . $msg . "\r\n"; } } diff --git a/library/think/log/driver/Socket.php b/library/think/log/driver/Socket.php index a4942a9c..a6a666f4 100644 --- a/library/think/log/driver/Socket.php +++ b/library/think/log/driver/Socket.php @@ -92,6 +92,9 @@ class Socket 'css' => isset($this->css[$type]) ? $this->css[$type] : '', ]; foreach ($val as $msg) { + if (!is_string($msg)) { + $msg = var_export($msg, true); + } $trace[] = [ 'type' => 'log', 'msg' => $msg, diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index 3471f92b..824b1639 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -72,6 +72,9 @@ class Trace $debug = []; foreach ($log as $type => $val) { foreach ($val as $msg) { + if (!is_string($msg)) { + $msg = var_export($msg, true); + } $debug[$type][] = $msg; } } From b15f411ae3a5fdb781cd55536a03361a0d03526a Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 14:46:43 +0800 Subject: [PATCH 363/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BBuilder=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Builder.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index 67566972..18a4e8bf 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -28,7 +28,7 @@ abstract class Builder protected $options = []; // 数据库表达式 - 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', 'between time' => 'BETWEEN TIME', 'not between time' => 'NOT BETWEEN TIME']; + 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', 'between time' => 'BETWEEN TIME', 'not between time' => 'NOT BETWEEN TIME', 'notbetween time' => 'NOT BETWEEN TIME']; // SQL表达式 protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%'; From 09a7b91fefdeee15010cf4fdbf454d333abf8278 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 14:49:24 +0800 Subject: [PATCH 364/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Connection=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index f927acd0..aa8e221c 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -94,7 +94,7 @@ abstract class Connection // 是否严格检查字段是否存在 'fields_strict' => true, // 数据集返回类型 - 'resultset_type' => Db::RESULTSET_ARRAY, + 'resultset_type' => 'array', // 自动写入时间戳字段 'auto_timestamp' => false, // 是否需要进行SQL性能分析 From 5e7c8e99021af820d3b6e112b8a858c014d88fb4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 14:57:12 +0800 Subject: [PATCH 365/670] =?UTF-8?q?=E5=8F=96=E6=B6=88=20MODULE=5FPATH=20?= =?UTF-8?q?=E5=B8=B8=E9=87=8F=20=E7=94=A8=20App::$modulePath=20=E6=9B=BF?= =?UTF-8?q?=E4=BB=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 7 ++++++- library/think/Loader.php | 2 +- library/think/view/driver/Php.php | 5 +++-- library/think/view/driver/Think.php | 5 +++-- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 22aa01dc..ffc6f16d 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -34,6 +34,11 @@ class App */ protected static $init = false; + /** + * @var string 当前模块路径 + */ + public static $modulePath; + /** * 执行应用程序 * @access public @@ -232,7 +237,7 @@ class App $module = ''; } // 当前模块路径 - define('MODULE_PATH', APP_PATH . ($module ? $module . DS : '')); + App::$modulePath = APP_PATH . ($module ? $module . DS : ''); // 获取控制器名 $controller = strip_tags($result[1] ?: $config['default_controller']); diff --git a/library/think/Loader.php b/library/think/Loader.php index 6c5cad6a..0cef94b7 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -239,7 +239,7 @@ class Loader $baseUrl = self::$namespace[$name]; } elseif ('@' == $name) { //加载当前模块应用类库 - $baseUrl = MODULE_PATH; + $baseUrl = App::$modulePath; } elseif (is_dir(EXTEND_PATH . $name)) { $baseUrl = EXTEND_PATH; } else { diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index 7db03fdb..98660690 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -11,6 +11,7 @@ namespace think\view\driver; +use think\App; use think\exception\TemplateNotFoundException; use think\Log; use think\Request; @@ -91,8 +92,8 @@ class Php */ private function parseTemplate($template) { - if (empty($this->config['view_path']) && defined('MODULE_PATH')) { - $this->config['view_path'] = MODULE_PATH . 'view' . DS; + if (empty($this->config['view_path'])) { + $this->config['view_path'] = App::$modulePath . 'view' . DS; } if (strpos($template, '@')) { diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index 906fcf10..be9a763c 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -11,6 +11,7 @@ namespace think\view\driver; +use think\App; use think\exception\TemplateNotFoundException; use think\Log; use think\Request; @@ -35,8 +36,8 @@ class Think public function __construct($config = []) { $this->config = array_merge($this->config, $config); - if (empty($this->config['view_path']) && defined('MODULE_PATH')) { - $this->config['view_path'] = MODULE_PATH . 'view' . DS; + if (empty($this->config['view_path'])) { + $this->config['view_path'] = App::$modulePath . 'view' . DS; } $this->template = new Template($this->config); } From af4e544937e87fb4f3445be636313a7fba3ca4e8 Mon Sep 17 00:00:00 2001 From: jay <917647288@qq.com> Date: Tue, 14 Jun 2016 15:02:45 +0800 Subject: [PATCH 366/670] =?UTF-8?q?=E8=B0=83=E6=95=B4=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E7=9A=84=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/Browser.php | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/library/think/log/driver/Browser.php b/library/think/log/driver/Browser.php index 66106846..9b068466 100644 --- a/library/think/log/driver/Browser.php +++ b/library/think/log/driver/Browser.php @@ -1,5 +1,13 @@ +// +---------------------------------------------------------------------- namespace think\log\driver; use think\Cache; use think\Config; @@ -116,14 +124,11 @@ JS; foreach ($msg as $key => $m) { switch ($type) { case '调试': - //我多么希望进来的是原数据格式而不是字符串 - if(substr($m, 0, 5) == 'array'){ - eval("\$o = $m;"); - $line[] = "console.log(".json_encode($o).");"; + $var_type = gettype($m); + if(in_array($var_type, ['array', 'string'])){ + $line[] = "console.log(".json_encode($m).");"; }else{ - $msg = addslashes($m); - $msg = str_replace(PHP_EOL, '\n', $msg); - $line[] = "console.log('$msg');"; + $line[] = "console.log(".json_encode(var_export($m, 1)).");"; } break; case '错误': From 00517f912570e1708f5a8e884114c1fbdd3f29ac Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 15:33:49 +0800 Subject: [PATCH 367/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Request=E7=B1=BB?= =?UTF-8?q?=E7=9A=84create=E6=96=B9=E6=B3=95=20=E4=BF=AE=E6=AD=A3Route?= =?UTF-8?q?=E7=B1=BB=E7=9A=84check=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 +- library/think/Route.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index e0648f12..3e1a3940 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -194,7 +194,7 @@ class Request $options['server'] = $server; $options['url'] = $server['REQUEST_URI']; $options['baseUrl'] = $info['path']; - $options['pathinfo'] = $info['path']; + $options['pathinfo'] = ltrim($info['path'],'/'); $options['method'] = $server['REQUEST_METHOD']; $options['domain'] = $server['HTTP_HOST']; self::$instance = new self($options); diff --git a/library/think/Route.php b/library/think/Route.php index 96cb3640..56f5cef4 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -695,7 +695,7 @@ class Route if (!empty($val['routes'])) { // 分组路由 - if ($pos = strpos($rule, ':') || $pos = strpos($rule, '<')) { + if (($pos = strpos($rule, ':')) || ($pos = strpos($rule, '<'))) { $str = substr($rule, 0, $pos); } else { $str = $rule; From 02595c8350070c82208afe0217b965e3725c3a87 Mon Sep 17 00:00:00 2001 From: cbwfree Date: Tue, 14 Jun 2016 16:24:52 +0800 Subject: [PATCH 368/670] =?UTF-8?q?Query=20=E7=9A=84=20delete()=20?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E4=BD=BF=E7=94=A8=20fetchSql()=20=E6=8A=A5?= =?UTF-8?q?=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原代码第 `1976` 行 `$this->getRealSql($sql,$this->bind);` 应该修改为 `$this->connection->getRealSql($sql,$this->bind);` --- library/think/db/Query.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index fa771afc..566d5446 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1973,7 +1973,7 @@ class Query $sql = $this->builder()->delete($options); if($options['fetch_sql']){ // 获取实际执行的SQL语句 - return $this->getRealSql($sql,$this->bind); + return $this->connection->getRealSql($sql,$this->bind); } // 执行操作 return $this->execute($sql, $this->getBind()); From 6fb951a29de6d3ef1758104324937b0fa6b52f0d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 16:55:30 +0800 Subject: [PATCH 369/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BApp=E7=B1=BB=E7=9A=84?= =?UTF-8?q?route=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/App.php b/library/think/App.php index ffc6f16d..7b64581e 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -403,7 +403,7 @@ class App Route::import($config['route']); } // 路由检测(根据路由定义返回不同的URL调度) - $result = Route::check($request, $path, $depr, !IS_CLI ? $config['url_domain_deploy'] : false); + $result = Route::check($request, $path, $depr, $config['url_domain_deploy']); if (APP_ROUTE_MUST && false === $result && $config['url_route_must']) { // 路由无效 throw new HttpException(404, 'Route Not Found'); From 8d08655670c27265d1c7727a5d40f594c2a1e03e Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Tue, 14 Jun 2016 17:26:41 +0800 Subject: [PATCH 370/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E7=9A=84=E4=B8=80=E5=A4=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tpl/think_exception.tpl | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tpl/think_exception.tpl b/tpl/think_exception.tpl index 2262fb91..5d397284 100644 --- a/tpl/think_exception.tpl +++ b/tpl/think_exception.tpl @@ -286,8 +286,10 @@ echo htmlentities(json_encode($val, JSON_PRETTY_PRINT)); } else if(is_bool($val)) { echo $val ? 'true' : 'false'; - } else { + } else if(is_scalar($val)) { echo htmlentities($val); + } else { + echo 'Resource'; } ?> From 3845e5d77f29e2059e43a87f736778a9b4c7f449 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Tue, 14 Jun 2016 17:28:02 +0800 Subject: [PATCH 371/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E7=9A=84=E4=B8=80=E5=A4=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tpl/think_exception.tpl | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tpl/think_exception.tpl b/tpl/think_exception.tpl index 5d397284..4e46f6ee 100644 --- a/tpl/think_exception.tpl +++ b/tpl/think_exception.tpl @@ -253,8 +253,10 @@ echo htmlentities(json_encode($val, JSON_PRETTY_PRINT)); } else if(is_bool($val)) { echo $val ? 'true' : 'false'; - } else { + } else if(is_scalar($val)) { echo htmlentities($val); + } else { + echo 'Resource'; } ?> From ec6617dc154313597432db40c24b3673146a69da Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 18:12:26 +0800 Subject: [PATCH 372/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/thinkphp/library/think/routeTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index f3222c8d..1ca2afdb 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -18,6 +18,7 @@ namespace tests\thinkphp\library\think; use think\Request; use think\Route; +use think\Config; class routeTest extends \PHPUnit_Framework_TestCase { From aa2eedb0fab51c90961c27726eeda1d8102f4969 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 18:28:14 +0800 Subject: [PATCH 373/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BFile=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/File.php | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/library/think/File.php b/library/think/File.php index e9111235..eb0d499a 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -20,6 +20,8 @@ class File extends SplFileObject * @var string */ private $error = ''; + // 当前完整文件名 + protected $filename; // 文件上传命名规则 protected $rule = 'date'; // 单元测试 @@ -28,11 +30,12 @@ class File extends SplFileObject // 上传文件信息 protected $info; - public function __construct($filename, $info = [],$isTest=false) + public function __construct($filename, $info = [], $isTest = false) { parent::__construct($filename); $this->info = $info; $this->isTest = $isTest; + $this->filename = $this->getRealPath(); } /** @@ -71,7 +74,7 @@ class File extends SplFileObject public function getMime() { $finfo = finfo_open(FILEINFO_MIME_TYPE); - return finfo_file($finfo, $this->getRealPath()); + return finfo_file($finfo, $this->filename); } /** @@ -92,9 +95,9 @@ class File extends SplFileObject public function isValid() { if($this->isTest){ - return is_file($this->getRealPath()); + return is_file($this->filename); } - return is_uploaded_file($this->getRealPath()); + return is_uploaded_file($this->filename); } /** @@ -129,8 +132,8 @@ class File extends SplFileObject /* 移动文件 */ if($this->isTest){ - rename($this->getRealPath(),$path.$savename); - } elseif (!move_uploaded_file($this->getRealPath(), $path . $savename)) { + rename($this->filename, $path.$savename); + } elseif (!move_uploaded_file($this->filename, $path . $savename)) { $this->error = '文件上传保存错误!'; return false; } @@ -152,11 +155,11 @@ class File extends SplFileObject } else { switch ($this->rule) { case 'md5': - $md5 = md5_file($this->getRealPath()); + $md5 = md5_file($this->filename); $savename = substr($md5, 0, 2) . DS . substr($md5, 2); break; case 'sha1': - $sha1 = sha1_file($this->getRealPath()); + $sha1 = sha1_file($this->filename); $savename = substr($sha1, 0, 2) . DS . substr($sha1, 2); break; case 'date': From 5ce406abd2d16c0dafeed574c20ba22d83188a4c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 22:30:24 +0800 Subject: [PATCH 374/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=97=B6=E9=97=B4=E6=88=B3=E5=86=99=E5=85=A5?= =?UTF-8?q?=E6=94=AF=E6=8C=81date=E5=AD=97=E6=AE=B5=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index b6be17b2..8cbc745c 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -257,7 +257,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = $_SERVER['REQUEST_TIME']; break; } - } elseif (isset($this->fieldType[$name]) && preg_match('/(datetime|timestamp)/is', $this->fieldType[$name])) { + } elseif (isset($this->fieldType[$name]) && preg_match('/(datetime|date|timestamp)/is', $this->fieldType[$name])) { $value = date($this->dateFormat, $_SERVER['REQUEST_TIME']); } else { $value = $_SERVER['REQUEST_TIME']; From 3d989e6f2c2d6d93bd4903106f9c56b8f3386720 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 22:52:15 +0800 Subject: [PATCH 375/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E9=A9=B1=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/Browser.php | 39 ++++++++++++---------------- library/think/log/driver/Trace.php | 15 ++--------- 2 files changed, 19 insertions(+), 35 deletions(-) diff --git a/library/think/log/driver/Browser.php b/library/think/log/driver/Browser.php index 9b068466..24d91aea 100644 --- a/library/think/log/driver/Browser.php +++ b/library/think/log/driver/Browser.php @@ -8,12 +8,15 @@ // +---------------------------------------------------------------------- // | Author: yangweijie // +---------------------------------------------------------------------- + namespace think\log\driver; + use think\Cache; use think\Config; use think\Db; use think\Debug; use think\Request; + /** * 浏览器调试输出 */ @@ -64,14 +67,6 @@ class Browser $info = Debug::getFile(true); - // 获取调试日志 - $debug = []; - foreach ($log as $type => $val) { - foreach ($val as $msg) { - $debug[$type][] = $msg; - } - } - // 页面Trace信息 $trace = []; foreach ($this->config['trace_tabs'] as $name => $title) { @@ -89,11 +84,11 @@ class Browser $names = explode('|', $name); $result = []; foreach ($names as $name) { - $result = array_merge($result, isset($debug[$name]) ? $debug[$name] : []); + $result = array_merge($result, isset($log[$name]) ? $log[$name] : []); } $trace[$title] = $result; } else { - $trace[$title] = isset($debug[$name]) ? $debug[$name] : ''; + $trace[$title] = isset($log[$name]) ? $log[$name] : ''; } } } @@ -120,8 +115,9 @@ JS; $line[] = ($type == $trace_tabs[0] || '调试' == $type || '错误'== $type)? "console.group('{$type}');" : - "console.groupCollapsed('{$type}');"; - foreach ($msg as $key => $m) { + "console.groupCollapsed('{$type}');";//dump($msg); + + foreach ((array)$msg as $key => $m) { switch ($type) { case '调试': $var_type = gettype($m); @@ -132,20 +128,19 @@ JS; } break; case '错误': - $msg = str_replace(PHP_EOL, '\n', $m); - $style = 'color:#F4006B;font-size:14px;'; - $line[] = "console.error(\"%c{$msg}\", \"{$style}\");"; - // $line[] = "console.error(".json_encode(debug_backtrace()).");"; + $msg = str_replace(PHP_EOL, '\n', $m); + $style = 'color:#F4006B;font-size:14px;'; + $line[] = "console.error(\"%c{$msg}\", \"{$style}\");"; break; case 'sql': - $msg = str_replace(PHP_EOL, '\n', $m); - $style = "color:#009bb4;"; - $line[] = "console.log(\"%c{$msg}\", \"{$style}\");"; + $msg = str_replace(PHP_EOL, '\n', $m); + $style = "color:#009bb4;"; + $line[] = "console.log(\"%c{$msg}\", \"{$style}\");"; break; default: - $m = is_string($key)? $key.' '.$m: $key+1 .' '.$m; - $msg = str_replace(PHP_EOL, '\n', $m); - $line[] = "console.log(\"{$msg}\");"; + $m = is_string($key)? $key.' '.$m: $key+1 .' '.$m; + $msg = str_replace(PHP_EOL, '\n', $m); + $line[] = "console.log(\"{$msg}\");"; break; } } diff --git a/library/think/log/driver/Trace.php b/library/think/log/driver/Trace.php index 824b1639..8b121e76 100644 --- a/library/think/log/driver/Trace.php +++ b/library/think/log/driver/Trace.php @@ -68,17 +68,6 @@ class Trace $info = Debug::getFile(true); - // 获取调试日志 - $debug = []; - foreach ($log as $type => $val) { - foreach ($val as $msg) { - if (!is_string($msg)) { - $msg = var_export($msg, true); - } - $debug[$type][] = $msg; - } - } - // 页面Trace信息 $trace = []; foreach ($this->config['trace_tabs'] as $name => $title) { @@ -96,11 +85,11 @@ class Trace $names = explode('|', $name); $result = []; foreach ($names as $name) { - $result = array_merge($result, isset($debug[$name]) ? $debug[$name] : []); + $result = array_merge($result, isset($log[$name]) ? $log[$name] : []); } $trace[$title] = $result; } else { - $trace[$title] = isset($debug[$name]) ? $debug[$name] : ''; + $trace[$title] = isset($log[$name]) ? $log[$name] : ''; } } } From f4bf3620e953f8121fb20da3e7d6cb45530578bf Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 23:12:05 +0800 Subject: [PATCH 376/670] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/Browser.php | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/library/think/log/driver/Browser.php b/library/think/log/driver/Browser.php index 24d91aea..2a614da4 100644 --- a/library/think/log/driver/Browser.php +++ b/library/think/log/driver/Browser.php @@ -105,17 +105,16 @@ class Browser JS; echo $js; - return true; } - public function output($type, $msg){ - $type = strtolower($type); + public function output($type, $msg) + { + $type = strtolower($type); $trace_tabs = array_values($this->config['trace_tabs']); - $line[] = ($type == $trace_tabs[0] || '调试' == $type || '错误'== $type)? - "console.group('{$type}');" - : - "console.groupCollapsed('{$type}');";//dump($msg); + $line[] = ($type == $trace_tabs[0] || '调试' == $type || '错误'== $type) + ? "console.group('{$type}');" + : "console.groupCollapsed('{$type}');"; foreach ((array)$msg as $key => $m) { switch ($type) { @@ -138,7 +137,7 @@ JS; $line[] = "console.log(\"%c{$msg}\", \"{$style}\");"; break; default: - $m = is_string($key)? $key.' '.$m: $key+1 .' '.$m; + $m = is_string($key)? $key . ' ' . $m : $key+1 . ' ' . $m; $msg = str_replace(PHP_EOL, '\n', $m); $line[] = "console.log(\"{$msg}\");"; break; From ea8bad77598e079eedc0140455581f98c438b078 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 14 Jun 2016 23:58:45 +0800 Subject: [PATCH 377/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Browser=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E9=A9=B1=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/log/driver/Browser.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/log/driver/Browser.php b/library/think/log/driver/Browser.php index 2a614da4..12a428a0 100644 --- a/library/think/log/driver/Browser.php +++ b/library/think/log/driver/Browser.php @@ -138,8 +138,8 @@ JS; break; default: $m = is_string($key)? $key . ' ' . $m : $key+1 . ' ' . $m; - $msg = str_replace(PHP_EOL, '\n', $m); - $line[] = "console.log(\"{$msg}\");"; + $msg = json_encode($m); + $line[] = "console.log({$msg});"; break; } } From d08ae3671a2a38c235aa9d6941be498b5b30f70a Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 15 Jun 2016 11:03:08 +0800 Subject: [PATCH 378/670] =?UTF-8?q?=E5=AE=8C=E5=96=84=E4=BA=8B=E5=8A=A1?= =?UTF-8?q?=E5=B5=8C=E5=A5=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 99 +++++++++++++++++---------- library/think/db/connector/Mysql.php | 4 ++ library/think/db/connector/Oracle.php | 4 ++ library/think/db/connector/Pgsql.php | 4 ++ library/think/db/connector/Sqlite.php | 4 ++ 5 files changed, 80 insertions(+), 35 deletions(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index aa8e221c..f9ea922c 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -36,8 +36,6 @@ abstract class Connection protected $numRows = 0; // 事务指令数 protected $transTimes = 0; - // 事务标识 - protected $transLabel = ''; // 错误信息 protected $error = ''; @@ -520,65 +518,67 @@ abstract class Connection * @access public * @param callable $callback 数据操作方法回调 * @return mixed + * @throws PDOException + * @throws \Exception + * @throws \Throwable */ public function transaction($callback) { - $label = microtime(true); - $this->startTrans($label); + $this->startTrans(); try { $result = null; if (is_callable($callback)) { - $result = call_user_func_array($callback, []); + $result = call_user_func_array($callback, [$this]); } - $this->commit($label); + $this->commit(); return $result; } catch (\Exception $e) { $this->rollback(); throw $e; + } catch (\Throwable $e) { + $this->rollback(); + throw $e; } } /** * 启动事务 * @access public - * @param string $label 事务标识 * @return bool|null */ - public function startTrans($label = '') + public function startTrans() { $this->initConnect(true); if (!$this->linkID) { return false; } - //数据rollback 支持 - if (0 == $this->transTimes) { - $this->transLabel = $label; + ++$this->transTimes; + + if ($this->transTimes == 1) { $this->linkID->beginTransaction(); + } elseif ($this->transTimes > 1 && $this->supportSavepoint()) { + $this->linkID->exec( + $this->parseSavepoint('trans' . $this->transTimes) + ); } - $this->transTimes++; - return; } /** * 用于非自动提交状态下面的查询提交 * @access public - * @param string $label 事务标识 * @return boolean * @throws PDOException */ - public function commit($label = '') + public function commit() { $this->initConnect(true); - if ($this->transTimes > 0 && $label == $this->transLabel) { - try { - $this->linkID->commit(); - $this->transTimes = 0; - } catch (\PDOException $e) { - throw new PDOException($e, $this->config, $this->queryStr); - } + + if ($this->transTimes == 1) { + $this->linkID->commit(); } - return true; + + --$this->transTimes; } /** @@ -590,15 +590,45 @@ abstract class Connection public function rollback() { $this->initConnect(true); - if ($this->transTimes > 0) { - try { - $this->linkID->rollback(); - $this->transTimes = 0; - } catch (\PDOException $e) { - throw new PDOException($e, $this->config, $this->queryStr); - } + + if ($this->transTimes == 1) { + $this->linkID->rollBack(); + } elseif ($this->transTimes > 1 && $this->supportSavepoint()) { + $this->linkID->exec( + $this->parseSavepointRollBack('trans' . $this->transTimes) + ); } - return true; + + $this->transTimes = max(0, $this->transTimes - 1); + } + + /** + * 是否支持事务嵌套 + * @return bool + */ + protected function supportSavepoint() + { + return false; + } + + /** + * 生成定义保存点的SQL + * @param $name + * @return string + */ + protected function parseSavepoint($name) + { + return 'SAVEPOINT ' . $name; + } + + /** + * 生成回滚到保存点的SQL + * @param $name + * @return string + */ + protected function parseSavepointRollBack($name) + { + return 'ROLLBACK TO SAVEPOINT ' . $name; } /** @@ -614,14 +644,13 @@ abstract class Connection return false; } // 自动启动事务支持 - $label = microtime(true); - $this->startTrans($label); + $this->startTrans(); try { foreach ($sqlArray as $sql) { - $result = $this->execute($sql); + $this->execute($sql); } // 提交事务 - $this->commit($label); + $this->commit(); } catch (\PDOException $e) { $this->rollback(); return false; diff --git a/library/think/db/connector/Mysql.php b/library/think/db/connector/Mysql.php index b9d910d3..5f83f496 100644 --- a/library/think/db/connector/Mysql.php +++ b/library/think/db/connector/Mysql.php @@ -110,4 +110,8 @@ class Mysql extends Connection } return $result; } + + protected function supportSavepoint(){ + return true; + } } diff --git a/library/think/db/connector/Oracle.php b/library/think/db/connector/Oracle.php index 1e2a4372..f50ec5f1 100644 --- a/library/think/db/connector/Oracle.php +++ b/library/think/db/connector/Oracle.php @@ -154,4 +154,8 @@ class Oracle extends Connection { return []; } + + protected function supportSavepoint(){ + return true; + } } diff --git a/library/think/db/connector/Pgsql.php b/library/think/db/connector/Pgsql.php index 350803a8..161165ac 100644 --- a/library/think/db/connector/Pgsql.php +++ b/library/think/db/connector/Pgsql.php @@ -93,4 +93,8 @@ class Pgsql extends Connection { return []; } + + protected function supportSavepoint(){ + return true; + } } diff --git a/library/think/db/connector/Sqlite.php b/library/think/db/connector/Sqlite.php index cac8c352..d8f63f81 100644 --- a/library/think/db/connector/Sqlite.php +++ b/library/think/db/connector/Sqlite.php @@ -92,4 +92,8 @@ class Sqlite extends Connection { return []; } + + protected function supportSavepoint(){ + return true; + } } From ea1b1af3a33aaf13ec0adb6fb2447a39c32f1d98 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 15 Jun 2016 11:10:24 +0800 Subject: [PATCH 379/670] =?UTF-8?q?=E5=AE=8C=E5=96=84=E4=BA=8B=E5=8A=A1?= =?UTF-8?q?=E5=B5=8C=E5=A5=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 10 ++++------ library/think/model/Merge.php | 8 ++++---- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 566d5446..7082370a 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -239,24 +239,22 @@ class Query /** * 启动事务 * @access public - * @param string $label 事务标识 * @return bool|null */ - public function startTrans($label = '') + public function startTrans() { - return $this->connection->startTrans($label); + return $this->connection->startTrans(); } /** * 用于非自动提交状态下面的查询提交 * @access public - * @param string $label 事务标识 * @return boolean * @throws PDOException */ - public function commit($label = '') + public function commit() { - return $this->connection->commit($label); + return $this->connection->commit(); } /** diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 5672ebc0..3da4fc07 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -173,7 +173,7 @@ class Merge extends Model } $db = $this->db(); - $db->startTrans('merge_save_' . $this->name); + $db->startTrans(); try { if ($this->isUpdate) { // 自动写入 @@ -235,7 +235,7 @@ class Merge extends Model // 新增回调 $this->trigger('after_insert', $this); } - $db->commit('merge_save_' . $this->name); + $db->commit(); return $result; } catch (\PDOException $e) { $db->rollback(); @@ -255,7 +255,7 @@ class Merge extends Model } $db = $this->db(); - $db->startTrans('merge_delete_' . $this->name); + $db->startTrans(); try { $result = $db->delete($this->data); if ($result) { @@ -270,7 +270,7 @@ class Merge extends Model } } $this->trigger('after_delete', $this); - $db->commit('merge_delete_' . $this->name); + $db->commit(); return $result; } catch (\PDOException $e) { $db->rollback(); From c88bcf45ade68029fe33c3868ff21a2fa5bc6214 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 15 Jun 2016 11:44:21 +0800 Subject: [PATCH 380/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84column=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81=20field?= =?UTF-8?q?=E5=92=8Ckey=E7=9B=B8=E5=90=8C=E7=9A=84=E6=83=85=E5=86=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 2 +- library/think/db/Query.php | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/library/think/App.php b/library/think/App.php index 7b64581e..0c710b51 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -331,7 +331,7 @@ class App private static function init($module = '') { // 定位模块目录 - $module = ($module) ? $module . DS : ''; + $module = $module ? $module . DS : ''; // 加载初始化文件 if (is_file(APP_PATH . $module . 'init' . EXT)) { diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 566d5446..3bd7aeec 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -447,6 +447,8 @@ class Query $result[$val[$key]] = $val; } elseif (2 == $count) { $result[$val[$key]] = $val[$key2]; + } elseif (1 == $count) { + $result[$val[$key]] = $val[$key1]; } } } else { From bc58cd765bc5bb0583620c0a2cab61617404f0bb Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 15 Jun 2016 11:46:33 +0800 Subject: [PATCH 381/670] =?UTF-8?q?=E5=9B=BA=E5=AE=9A=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E4=BE=9D=E8=B5=96=E5=BA=93=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 6a23e52a..0618a62e 100644 --- a/composer.json +++ b/composer.json @@ -22,9 +22,9 @@ "require-dev": { "johnkary/phpunit-speedtrap": "^1.0", "mikey179/vfsStream": "~1.6", - "phploc/phploc": "*", + "phploc/phploc": "2.*", "phpunit/phpunit": "4.8.*", - "sebastian/phpcpd": "*", + "sebastian/phpcpd": "2.*", "squizlabs/php_codesniffer": "2.*" }, "minimum-stability": "dev" From 30764fe702b1be43579b92ab53afd030a97cfe75 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 15 Jun 2016 12:37:36 +0800 Subject: [PATCH 382/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3reflection-docblock?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 0618a62e..5d3e5b43 100644 --- a/composer.json +++ b/composer.json @@ -20,12 +20,12 @@ "topthink/think-installer": "*" }, "require-dev": { + "phpunit/phpunit": "4.8.*", "johnkary/phpunit-speedtrap": "^1.0", "mikey179/vfsStream": "~1.6", "phploc/phploc": "2.*", - "phpunit/phpunit": "4.8.*", "sebastian/phpcpd": "2.*", - "squizlabs/php_codesniffer": "2.*" - }, - "minimum-stability": "dev" + "squizlabs/php_codesniffer": "2.*", + "phpdocumentor/reflection-docblock": "^2.0" + } } From 116a289cf79991fd15b67d96e7c4e9872710c23c Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 15 Jun 2016 14:59:31 +0800 Subject: [PATCH 383/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Bdebug=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E6=97=B6console=E4=B8=8B=E5=BC=82=E5=B8=B8=E7=9A=84?= =?UTF-8?q?=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/exception/Handle.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index 0946b941..fde2f248 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -86,6 +86,9 @@ class Handle */ public function renderForConsole(Output $output, Exception $e) { + if (APP_DEBUG) { + $output->setVerbosity(Output::VERBOSITY_DEBUG); + } (new Console)->renderException($e, $output); } From cabf5c4fdf8fd0ec920c7fb063a57fd7c3a38861 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 15 Jun 2016 15:45:42 +0800 Subject: [PATCH 384/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BConnection=E7=B1=BB?= =?UTF-8?q?=E7=9A=84getResult=E6=96=B9=E6=B3=95=20=E6=94=B9=E8=BF=9BApp?= =?UTF-8?q?=E7=B1=BB=E7=9A=84run=E6=96=B9=E6=B3=95=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E5=80=BC=20Builder=E7=B1=BB=E7=9A=84parseValue=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E5=A2=9E=E5=8A=A0field=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 4 ++-- library/think/Input.php | 2 +- library/think/db/Builder.php | 15 ++++++++------- library/think/db/Connection.php | 15 +++++---------- 4 files changed, 16 insertions(+), 20 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 0c710b51..ea833258 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -113,11 +113,11 @@ class App // 输出数据到客户端 if ($data instanceof Response) { return $data; - } elseif (!is_null($data)) { + } else { // 默认自动识别响应输出类型 $isAjax = $request->isAjax(); $type = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type'); - return Response::create($data, $type); + return Response::create( is_null($data) ? '' : $data, $type); } } diff --git a/library/think/Input.php b/library/think/Input.php index 21953722..5a5a9291 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -245,7 +245,7 @@ class Input $item[$key] = $val; }else{ $item[$key] = new File($val['tmp_name'], $val); - } + } } return $item; } elseif (isset($array[$name])) { diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index 18a4e8bf..ab7d226c 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -130,17 +130,18 @@ abstract class Builder /** * value分析 * @access protected - * @param mixed $value + * @param mixed $value + * @param string $field * @return string|array */ - protected function parseValue($value) + protected function parseValue($value, $field = '') { if (is_string($value)) { $value = strpos($value, ':') === 0 && $this->query->isBind(substr($value, 1)) ? $value : $this->connection->quote($value); } elseif (is_array($value) && is_string($value[0]) && strtolower($value[0]) == 'exp') { $value = $value[1]; } elseif (is_array($value)) { - $value = array_map([$this, 'parseValue'], $value); + $value = array_map([$this, 'parseValue'], $value, $field); } elseif (is_bool($value)) { $value = $value ? '1' : '0'; } elseif (is_null($value)) { @@ -311,7 +312,7 @@ abstract class Builder $whereStr = ''; if (in_array($exp, ['=', '<>', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE'])) { // 比较运算 及 模糊匹配 - $whereStr .= $key . ' ' . $exp . ' ' . $this->parseValue($value); + $whereStr .= $key . ' ' . $exp . ' ' . $this->parseValue($value, $field); } elseif ('EXP' == $exp) { // 表达式查询 $whereStr .= '( ' . $key . ' ' . $value . ' )'; @@ -324,13 +325,13 @@ abstract class Builder $whereStr .= $key . ' ' . $exp . ' ' . $this->parseClosure($value); } else { $value = is_array($value) ? $value : explode(',', $value); - $zone = implode(',', $this->parseValue($value)); + $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); - $whereStr .= $key . ' ' . $exp . ' ' . $this->parseValue($data[0]) . ' AND ' . $this->parseValue($data[1]); + $whereStr .= $key . ' ' . $exp . ' ' . $this->parseValue($data[0], $field) . ' AND ' . $this->parseValue($data[1], $field); } elseif (in_array($exp, ['NOT EXISTS', 'EXISTS'])) { // EXISTS 查询 if ($value instanceof \Closure) { @@ -614,7 +615,7 @@ abstract class Builder } unset($data[$key]); } elseif (is_scalar($val)) { - $data[$key] = $this->parseValue($val); + $data[$key] = $this->parseValue($val, $key); } else { // 过滤掉非标量数据 unset($data[$key]); diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index f9ea922c..7884442a 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -480,17 +480,12 @@ abstract class Connection if (!empty($class)) { // 返回指定数据集对象类 - return new $class($result); - } - switch ($this->resultSetType) { - case 'collection': - // 返回数据集Collection对象 - $result = new Collection($result); - break; - case 'array': - default: - // 返回二维数组 + $result = new $class($result); + } elseif ('collection' == $this->resultSetType){ + // 返回数据集Collection对象 + $result = new Collection($result); } + return $result; } From 343252324a613d1406b1a95afbdc49eb70646bd9 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 15 Jun 2016 15:57:12 +0800 Subject: [PATCH 385/670] =?UTF-8?q?start=E6=96=87=E4=BB=B6=E8=B0=83?= =?UTF-8?q?=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- start.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/start.php b/start.php index 036716bc..20a7817c 100644 --- a/start.php +++ b/start.php @@ -64,8 +64,5 @@ if (isset($mode['tags'])) { // 是否自动运行 if (APP_AUTO_RUN) { - $response = App::run(); - if($response instanceof Response){ - $response->send(); - } + App::run()->send(); } From 4c848c4a7443fa164c0df1f80ed836e50cb91380 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 15 Jun 2016 16:43:31 +0800 Subject: [PATCH 386/670] =?UTF-8?q?=E5=8F=96=E6=B6=88=20APP=5FDEBUG=20?= =?UTF-8?q?=E5=B8=B8=E9=87=8F=20=E6=94=B9=E4=B8=BA=20App::$debug=20?= =?UTF-8?q?=E5=B1=9E=E6=80=A7=E8=8E=B7=E5=8F=96=20=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E8=B0=83=E8=AF=95=E6=A8=A1=E5=BC=8F=20=E6=94=B9=E4=B8=BA=20app?= =?UTF-8?q?=5Fdebug=20=E9=85=8D=E7=BD=AE=E5=8F=82=E6=95=B0=20=E5=9C=A8?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E4=B8=AD?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 2 ++ library/think/App.php | 16 ++++++++++++---- library/think/Cache.php | 4 +++- library/think/Config.php | 4 +++- library/think/Db.php | 3 ++- library/think/Error.php | 3 ++- library/think/Hook.php | 5 +++-- library/think/Lang.php | 3 ++- library/think/Loader.php | 5 +++-- library/think/Log.php | 6 ++++-- library/think/Route.php | 3 ++- library/think/Session.php | 3 ++- library/think/Url.php | 3 ++- library/think/cache/driver/Redisd.php | 3 ++- library/think/controller/Hprose.php | 4 +++- library/think/controller/Rpc.php | 3 ++- library/think/db/Connection.php | 3 ++- library/think/exception/Handle.php | 11 ++++++----- library/think/view/driver/Php.php | 2 +- library/think/view/driver/Think.php | 2 +- start.php | 5 ----- tests/application/database.php | 2 +- tests/mock.php | 2 -- tests/thinkphp/baseTest.php | 1 - tpl/think_exception.tpl | 4 ++-- 25 files changed, 62 insertions(+), 40 deletions(-) diff --git a/convention.php b/convention.php index d1e1edd9..d69685a1 100644 --- a/convention.php +++ b/convention.php @@ -5,6 +5,8 @@ return [ // | 应用设置 // +---------------------------------------------------------------------- + // 应用调试模式 + 'app_debug' => true, // 应用模式状态 'app_status' => '', // 是否支持多模块 diff --git a/library/think/App.php b/library/think/App.php index ea833258..626b0845 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -39,6 +39,11 @@ class App */ public static $modulePath; + /** + * @var bool 应用调试模式 + */ + public static $debug = true; + /** * 执行应用程序 * @access public @@ -72,7 +77,7 @@ class App $dispatch = self::route($request, $config); } // 记录路由信息 - APP_DEBUG && Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info'); + self::$debug && Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info'); // 监听app_begin Hook::listen('app_begin', $dispatch); @@ -133,7 +138,7 @@ class App $reflect = new \ReflectionFunction($function); $args = self::bindParams($reflect, $vars); // 记录执行信息 - APP_DEBUG && Log::record('[ RUN ] ' . $reflect->getFileName() . '[ ' . var_export($vars, true) . ' ]', 'info'); + self::$debug && Log::record('[ RUN ] ' . $reflect->getFileName() . '[ ' . var_export($vars, true) . ' ]', 'info'); return $reflect->invokeArgs($args); } @@ -159,7 +164,7 @@ class App } $args = self::bindParams($reflect, $vars); // 记录执行信息 - APP_DEBUG && Log::record('[ RUN ] ' . $reflect->getFileName() . '[ ' . var_export($args, true) . ' ]', 'info'); + self::$debug && Log::record('[ RUN ] ' . $reflect->getFileName() . '[ ' . var_export($args, true) . ' ]', 'info'); return $reflect->invokeArgs(isset($class) ? $class : null, $args); } @@ -280,7 +285,7 @@ class App if (method_exists($instance, '_empty')) { $method = new \ReflectionMethod($instance, '_empty'); $data = $method->invokeArgs($instance, [$action, '']); - APP_DEBUG && Log::record('[ RUN ] ' . $method->getFileName(), 'info'); + self::$debug && Log::record('[ RUN ] ' . $method->getFileName(), 'info'); } else { throw new HttpException(404, 'method [ ' . (new \ReflectionClass($instance))->getName() . '->' . $action . ' ] not exists '); } @@ -297,6 +302,9 @@ class App // 初始化应用 self::$init = $config = self::init(); + // 是否调试模式 + self::$debug = Config::get('app_debug'); + // 注册根命名空间 if (!empty($config['root_namespace'])) { Loader::addNamespace($config['root_namespace']); diff --git a/library/think/Cache.php b/library/think/Cache.php index 3dccefb0..fd011d5d 100644 --- a/library/think/Cache.php +++ b/library/think/Cache.php @@ -11,6 +11,8 @@ namespace think; +use think\App; + class Cache { protected static $instance = []; @@ -42,7 +44,7 @@ class Cache $class = (!empty($options['namespace']) ? $options['namespace'] : '\\think\\cache\\driver\\') . ucwords($type); // 记录初始化信息 - APP_DEBUG && Log::record('[ CACHE ] INIT ' . $type . ':' . var_export($options, true), 'info'); + App::$debug && Log::record('[ CACHE ] INIT ' . $type . ':' . var_export($options, true), 'info'); if (true === $name) { return new $class($options); } else { diff --git a/library/think/Config.php b/library/think/Config.php index 774a58a4..63cfa10d 100644 --- a/library/think/Config.php +++ b/library/think/Config.php @@ -11,6 +11,8 @@ namespace think; +use think\App; + class Config { // 配置参数 @@ -59,7 +61,7 @@ class Config } if (is_file($file)) { // 记录加载信息 - APP_DEBUG && Log::record('[ CONFIG ] ' . $file, 'info'); + App::$debug && Log::record('[ CONFIG ] ' . $file, 'info'); $type = pathinfo($file, PATHINFO_EXTENSION); if ('php' != $type) { return self::parse($file, $type, $name, $range); diff --git a/library/think/Db.php b/library/think/Db.php index 06ba04c7..ed44c659 100644 --- a/library/think/Db.php +++ b/library/think/Db.php @@ -11,6 +11,7 @@ namespace think; +use think\App; use think\Collection; use think\db\Query; @@ -68,7 +69,7 @@ class Db } $class = (!empty($options['namespace']) ? $options['namespace'] : '\\think\\db\\connector\\') . ucwords($options['type']); // 记录初始化信息 - APP_DEBUG && Log::record('[ DB ] INIT ' . $options['type'] . ':' . var_export($options, true), 'info'); + App::$debug && Log::record('[ DB ] INIT ' . $options['type'] . ':' . var_export($options, true), 'info'); if (true === $name) { return new $class($options); } else { diff --git a/library/think/Error.php b/library/think/Error.php index 140fbb24..22334bb3 100644 --- a/library/think/Error.php +++ b/library/think/Error.php @@ -11,6 +11,7 @@ namespace think; +use think\App; use think\console\Output as ConsoleOutput; use think\exception\ErrorException; use think\exception\Handle; @@ -29,7 +30,7 @@ class Error set_exception_handler([__CLASS__, 'appException']); register_shutdown_function([__CLASS__, 'appShutdown']); - if (!APP_DEBUG) { + if (!App::$debug) { ini_set('display_errors', 'Off'); } } diff --git a/library/think/Hook.php b/library/think/Hook.php index 0a1fe9e4..7076918e 100644 --- a/library/think/Hook.php +++ b/library/think/Hook.php @@ -11,6 +11,7 @@ namespace think; +use think\App; use think\Debug; use think\Log; @@ -100,7 +101,7 @@ class Hook if (isset(self::$tags[$tag])) { foreach (self::$tags[$tag] as $name) { - if (APP_DEBUG) { + if (App::$debug) { Debug::remark('behavior_start', 'time'); } @@ -110,7 +111,7 @@ class Hook return $result; } - if (APP_DEBUG) { + if (App::$debug) { Debug::remark('behavior_end', 'time'); if ($name instanceof \Closure) { $name = 'Closure'; diff --git a/library/think/Lang.php b/library/think/Lang.php index fe94bf7e..fd606ba6 100644 --- a/library/think/Lang.php +++ b/library/think/Lang.php @@ -11,6 +11,7 @@ namespace think; +use think\App; use think\Cookie; use think\Log; @@ -78,7 +79,7 @@ class Lang foreach ($file as $_file) { if (is_file($_file)) { // 记录加载信息 - APP_DEBUG && Log::record('[ LANG ] ' . $_file, 'info'); + App::$debug && Log::record('[ LANG ] ' . $_file, 'info'); $_lang = include $_file; } else { $_lang = []; diff --git a/library/think/Loader.php b/library/think/Loader.php index 0cef94b7..3453d714 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -11,6 +11,7 @@ namespace think; +use think\App; use think\exception\HttpException; use think\exception\ClassNotFoundException; use think\Request; @@ -78,7 +79,7 @@ class Loader $filename = $path . str_replace('\\', DS, $class) . EXT; if (is_file($filename)) { // 开启调试模式Win环境严格区分大小写 - if (APP_DEBUG && IS_WIN && false === strpos(realpath($filename), $class . EXT)) { + if (App::$debug && IS_WIN && false === strpos(realpath($filename), $class . EXT)) { return false; } include $filename; @@ -253,7 +254,7 @@ class Loader $filename = $baseUrl . $class . $ext; if (is_file($filename)) { // 开启调试模式Win环境严格区分大小写 - if (APP_DEBUG && IS_WIN && false === strpos(realpath($filename), $class . $ext)) { + if (App::$debug && IS_WIN && false === strpos(realpath($filename), $class . $ext)) { return false; } include $filename; diff --git a/library/think/Log.php b/library/think/Log.php index 76474c21..709da31e 100644 --- a/library/think/Log.php +++ b/library/think/Log.php @@ -11,6 +11,8 @@ namespace think; +use think\App; + class Log { const LOG = 'log'; @@ -45,7 +47,7 @@ class Log unset($config['type']); self::$driver = new $class($config); // 记录初始化信息 - APP_DEBUG && Log::record('[ LOG ] INIT ' . $type . ': ' . var_export($config, true), 'info'); + App::$debug && Log::record('[ LOG ] INIT ' . $type . ': ' . var_export($config, true), 'info'); } /** @@ -59,7 +61,7 @@ class Log unset($config['type']); self::$alarm = new $class($config['alarm']); // 记录初始化信息 - APP_DEBUG && Log::record('[ CACHE ] ALARM ' . $type . ': ' . var_export($config, true), 'info'); + App::$debug && Log::record('[ CACHE ] ALARM ' . $type . ': ' . var_export($config, true), 'info'); } /** diff --git a/library/think/Route.php b/library/think/Route.php index 56f5cef4..5694b86d 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -11,6 +11,7 @@ namespace think; +use think\App; use think\Config; use think\Hook; use think\Log; @@ -766,7 +767,7 @@ class Route { if (!empty(self::$bind['type'])) { // 记录绑定信息 - APP_DEBUG && Log::record('[ BIND ] ' . var_export(self::$bind, true), 'info'); + App::$debug && Log::record('[ BIND ] ' . var_export(self::$bind, true), 'info'); // 如果有URL绑定 则进行绑定检测 switch (self::$bind['type']) { case 'class': diff --git a/library/think/Session.php b/library/think/Session.php index e9855a9e..5bc2a856 100644 --- a/library/think/Session.php +++ b/library/think/Session.php @@ -11,6 +11,7 @@ namespace think; +use think\App; use think\exception\ClassNotFoundException; class Session @@ -45,7 +46,7 @@ class Session $config = Config::get('session'); } // 记录初始化信息 - APP_DEBUG && Log::record('[ SESSION ] INIT ' . var_export($config, true), 'info'); + 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); diff --git a/library/think/Url.php b/library/think/Url.php index 0df14419..a0d774b6 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -11,6 +11,7 @@ namespace think; +use think\App; use think\Cache; use think\Config; use think\Request; @@ -326,7 +327,7 @@ class Url $route = is_array($route) ? $route[0] : $route; $item[$route][] = [$rule, [], []]; } - !APP_DEBUG && Cache::set('think_route_map', $item); + !App::$debug && Cache::set('think_route_map', $item); return $item; } diff --git a/library/think/cache/driver/Redisd.php b/library/think/cache/driver/Redisd.php index ad59cf90..0a424fb2 100644 --- a/library/think/cache/driver/Redisd.php +++ b/library/think/cache/driver/Redisd.php @@ -11,6 +11,7 @@ namespace think\cache\driver; +use think\App; use think\Cache; use think\Exception; use think\Log; @@ -148,7 +149,7 @@ class Redisd $this->handler->setOption(\Redis::OPT_PREFIX, $this->options['prefix']); } - APP_DEBUG && Log::record("[ CACHE ] INIT Redisd : {$host}:{$port} master->" . var_export($master, true), Log::ALERT); + App::$debug && Log::record("[ CACHE ] INIT Redisd : {$host}:{$port} master->" . var_export($master, true), Log::ALERT); } catch (\RedisException $e) { //phpredis throws a RedisException object if it can't reach the Redis server. //That can happen in case of connectivity issues, if the Redis service is down, or if the redis host is overloaded. diff --git a/library/think/controller/Hprose.php b/library/think/controller/Hprose.php index d6ab39d2..ae30ac04 100644 --- a/library/think/controller/Hprose.php +++ b/library/think/controller/Hprose.php @@ -11,6 +11,8 @@ namespace think\controller; +use think\App; + /** * ThinkPHP Hprose控制器类 */ @@ -45,7 +47,7 @@ abstract class Hprose $methods = array_diff($methods, array('__construct', '__call', '_initialize')); } $server->addMethods($methods, $this); - if (APP_DEBUG || $this->debug) { + if (App::$debug || $this->debug) { $server->setDebugEnabled(true); } // Hprose设置 diff --git a/library/think/controller/Rpc.php b/library/think/controller/Rpc.php index 2a014c16..e16fce2a 100644 --- a/library/think/controller/Rpc.php +++ b/library/think/controller/Rpc.php @@ -11,6 +11,7 @@ namespace think\controller; +use think\App; /** * ThinkPHP RPC控制器类 */ @@ -43,7 +44,7 @@ abstract class Rpc } $server->add($methods, $this); - if (APP_DEBUG || $this->debug) { + if (App::$debug || $this->debug) { $server->setDebugMode(true); } $server->setEnableGZIP(true); diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 7884442a..6fc5b777 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -13,6 +13,7 @@ namespace think\db; use PDO; use PDOStatement; +use think\App; use think\Collection; use think\Db; use think\db\Query; @@ -260,7 +261,7 @@ abstract class Connection } $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params); // 记录数据库连接信息 - APP_DEBUG && Log::record('[ DB ] CONNECT: ' . $config['dsn'], 'info'); + App::$debug && Log::record('[ DB ] CONNECT: ' . $config['dsn'], 'info'); } catch (\PDOException $e) { if ($autoConnection) { Log::record($e->getMessage(), 'error'); diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index fde2f248..cc93842c 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -12,6 +12,7 @@ namespace think\exception; use Exception; +use think\App; use think\Config; use think\Console; use think\console\Output; @@ -35,7 +36,7 @@ class Handle { if (!$this->isIgnoreReport($exception)) { // 收集异常数据 - if (APP_DEBUG) { + if (App::$debug) { $data = [ 'file' => $exception->getFile(), 'line' => $exception->getLine(), @@ -86,7 +87,7 @@ class Handle */ public function renderForConsole(Output $output, Exception $e) { - if (APP_DEBUG) { + if (App::$debug) { $output->setVerbosity(Output::VERBOSITY_DEBUG); } (new Console)->renderException($e, $output); @@ -100,7 +101,7 @@ class Handle { $status = $e->getStatusCode(); $template = Config::get('http_exception_template'); - if (!APP_DEBUG && !empty($template[$status])) { + if (!App::$debug && !empty($template[$status])) { return Response::create($template[$status], 'view')->vars(['e' => $e])->send(); } else { return $this->convertExceptionToResponse($e); @@ -114,7 +115,7 @@ class Handle protected function convertExceptionToResponse(Exception $exception) { // 收集异常数据 - if (APP_DEBUG) { + if (App::$debug) { // 调试模式,获取详细的错误信息 $data = [ 'name' => get_class($exception), @@ -144,7 +145,7 @@ class Handle ]; } - if (!APP_DEBUG && !Config::get('show_error_msg')) { + if (!App::$debug && !Config::get('show_error_msg')) { // 不显示详细错误信息 $data['message'] = Config::get('error_message'); } diff --git a/library/think/view/driver/Php.php b/library/think/view/driver/Php.php index 98660690..f5866e8a 100644 --- a/library/think/view/driver/Php.php +++ b/library/think/view/driver/Php.php @@ -66,7 +66,7 @@ class Php throw new TemplateNotFoundException('template file not exists:' . $template, $template); } // 记录视图信息 - APP_DEBUG && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); + App::$debug && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); extract($data, EXTR_OVERWRITE); include $template; } diff --git a/library/think/view/driver/Think.php b/library/think/view/driver/Think.php index be9a763c..2a443aad 100644 --- a/library/think/view/driver/Think.php +++ b/library/think/view/driver/Think.php @@ -76,7 +76,7 @@ class Think throw new TemplateNotFoundException('template file not exists:' . $template, $template); } // 记录视图信息 - APP_DEBUG && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); + App::$debug && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info'); $this->template->fetch($template, $data, $config); } diff --git a/start.php b/start.php index 20a7817c..b75d94f3 100644 --- a/start.php +++ b/start.php @@ -27,11 +27,6 @@ if (is_file(ROOT_PATH . 'env' . EXT)) { putenv("$name=$val"); } } -// 自动识别调试模式 -if (!defined('APP_DEBUG')) { - $debug = getenv(ENV_PREFIX . 'APP_DEBUG'); - define('APP_DEBUG', $debug); -} // 加载模式定义文件 $mode = require MODE_PATH . APP_MODE . EXT; diff --git a/tests/application/database.php b/tests/application/database.php index 885ebf84..24434efb 100644 --- a/tests/application/database.php +++ b/tests/application/database.php @@ -32,7 +32,7 @@ return [ // 数据库表前缀 'prefix' => '', // 数据库调试模式 - 'debug' => APP_DEBUG, + 'debug' => true, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'deploy' => 0, // 数据库读写是否分离 主从式有效 diff --git a/tests/mock.php b/tests/mock.php index 536d559d..4a620b0b 100644 --- a/tests/mock.php +++ b/tests/mock.php @@ -15,8 +15,6 @@ $_SERVER['REQUEST_METHOD'] = 'GET'; define('TEST_PATH', __DIR__ . '/'); // 定义项目路径 define('APP_PATH', __DIR__ . '/application/'); -// 开启调试模式 -define('APP_DEBUG', true); // 关闭应用自动执行 define('APP_AUTO_RUN', false); // 加载框架引导文件 diff --git a/tests/thinkphp/baseTest.php b/tests/thinkphp/baseTest.php index b61ad444..d8b2ce30 100644 --- a/tests/thinkphp/baseTest.php +++ b/tests/thinkphp/baseTest.php @@ -34,7 +34,6 @@ class baseTest extends \PHPUnit_Framework_TestCase $this->assertNotEmpty(TEMP_PATH); $this->assertNotEmpty(VENDOR_PATH); $this->assertNotEmpty(EXT); - $this->assertTrue(is_bool(APP_DEBUG)); $this->assertNotEmpty(ENV_PREFIX); $this->assertTrue(is_bool(IS_API)); $this->assertNotEmpty(APP_MODE); diff --git a/tpl/think_exception.tpl b/tpl/think_exception.tpl index 4e46f6ee..725fa9ba 100644 --- a/tpl/think_exception.tpl +++ b/tpl/think_exception.tpl @@ -181,7 +181,7 @@ - +
@@ -309,7 +309,7 @@ V { 十年磨一剑-为API开发设计的高性能框架 }
- + - -'.end($names).''; - } - - function parse_file($file, $line) - { - return ''.basename($file)." line {$line}".''; - } - - function parse_args($args) - { - $result = []; - - foreach ($args as $key => $item) { - switch (true) { - case is_object($item): - $value = sprintf('object(%s)', parse_class(get_class($item))); - break; - case is_array($item): - if(count($item) > 3){ - $value = sprintf('[%s, ...]', parse_args(array_slice($item, 0, 3))); - } else { - $value = sprintf('[%s]', parse_args($item)); - } - break; - case is_string($item): - if(strlen($item) > 20){ - $value = sprintf( - '\'%s...\'', - htmlentities($item), - htmlentities(substr($item, 0, 20)) - ); - } else { - $value = sprintf("'%s'", htmlentities($item)); - } - break; - case is_int($item): - case is_float($item): - $value = $item; - break; - case is_null($item): - $value = 'null'; - break; - case is_bool($item): - $value = '' . ($item ? 'true' : 'false') . ''; - break; - case is_resource($item): - $value = 'resource'; - break; - default: - $value = htmlentities(str_replace("\n", '', var_export(strval($item), true))); - break; - } - - $result[] = is_int($key) ? $value : "'{$key}' => {$value}"; - } - - return implode(', ', $result); - } + \ No newline at end of file From 5ffb2359cc3a975a8f62cda982bd66250dbb9c18 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 14:11:23 +0800 Subject: [PATCH 477/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BLoader=E7=B1=BB?= =?UTF-8?q?=E7=9A=84register=E6=96=B9=E6=B3=95=20alias.php=20=E6=9B=B4?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=20classmap.php=20addMap=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E6=9B=B4=E6=94=B9=E4=B8=BA=20addClassMap=20base.php=E5=92=8Cst?= =?UTF-8?q?art.php=E6=96=87=E4=BB=B6=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 24 ++++++++++++ alias.php => classmap.php | 0 library/think/App.php | 2 +- library/think/Loader.php | 18 ++++++--- start.php | 41 ++------------------- tests/thinkphp/library/think/appTest.php | 4 +- tests/thinkphp/library/think/loaderTest.php | 4 +- 7 files changed, 45 insertions(+), 48 deletions(-) rename alias.php => classmap.php (100%) diff --git a/base.php b/base.php index b1e1b373..9ed85ffc 100644 --- a/base.php +++ b/base.php @@ -37,3 +37,27 @@ defined('AUTO_SCAN_PACKAGE') or define('AUTO_SCAN_PACKAGE', false); // 是否自 // 环境常量 define('IS_CLI', PHP_SAPI == 'cli' ? true : false); define('IS_WIN', strstr(PHP_OS, 'WIN') ? true : false); + +// 载入Loader类 +require CORE_PATH . 'Loader.php'; + +// 加载环境变量配置文件 +if (is_file(ROOT_PATH . 'env' . EXT)) { + $env = include ROOT_PATH . 'env' . EXT; + foreach ($env as $key => $val) { + $name = ENV_PREFIX . $key; + if (is_bool($val)) { + $val = $val ? 1 : 0; + } + putenv("$name=$val"); + } +} + +// 注册自动加载 +\think\Loader::register(); + +// 注册错误和异常处理机制 +\think\Error::register(); + +// 加载模式配置文件 +\think\Config::set(include THINK_PATH . 'convention' . EXT); diff --git a/alias.php b/classmap.php similarity index 100% rename from alias.php rename to classmap.php diff --git a/library/think/App.php b/library/think/App.php index e3724e98..78989242 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -399,7 +399,7 @@ class App // 加载别名文件 if (is_file(CONF_PATH . $module . 'alias' . EXT)) { - Loader::addMap(include CONF_PATH . $module . 'alias' . EXT); + Loader::addClassMap(include CONF_PATH . $module . 'alias' . EXT); } // 加载行为扩展文件 diff --git a/library/think/Loader.php b/library/think/Loader.php index 316bd4c2..a94da475 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -91,7 +91,7 @@ class Loader } // 注册classmap - public static function addMap($class, $map = '') + public static function addClassMap($class, $map = '') { if (is_array($class)) { self::$map = array_merge(self::$map, $class); @@ -125,7 +125,16 @@ class Loader { // 注册系统自动加载 spl_autoload_register($autoload ?: 'think\\Loader::autoload'); + // 注册命名空间定义 + self::addNamespace([ + 'think' => LIB_PATH . 'think' . DS, + 'behavior' => LIB_PATH . 'behavior' . DS, + 'traits' => LIB_PATH . 'traits' . DS, + ]); + // 加载类库映射文件 + self::addClassMap(include THINK_PATH . 'classmap' . EXT); + // Composer自动加载支持 if (is_dir(VENDOR_PATH . 'composer')) { // 注册Composer自动加载 self::registerComposerLoader(); @@ -134,7 +143,7 @@ class Loader // 读取Composer自动加载文件 $autoload = include VENDOR_PATH . 'think_autoload.php'; if (is_array($autoload)) { - self::addMap($autoload); + self::addClassMap($autoload); } } elseif (is_file(RUNTIME_PATH . 'autoload_composer.php')) { $autoload = include RUNTIME_PATH . 'autoload_composer.php'; @@ -161,7 +170,7 @@ class Loader $content = " $val) { - $name = ENV_PREFIX . $key; - if (is_bool($val)) { - $val = $val ? 1 : 0; - } - putenv("$name=$val"); - } -} - -// 注册命名空间定义 -Loader::addNamespace([ - 'think' => LIB_PATH . 'think' . DS, - 'behavior' => LIB_PATH . 'behavior' . DS, - 'traits' => LIB_PATH . 'traits' . DS, -]); - -// 注册自动加载 -Loader::register(); - -// 加载别名定义 -Loader::addMap(include THINK_PATH . 'alias' . EXT); - -// 注册错误和异常处理机制 -Error::register(); - -// 加载模式配置文件 -Config::set(include THINK_PATH . 'convention' . EXT); - -// 是否自动运行 -if (APP_AUTO_RUN) { - App::run()->send(); -} +// 执行应用 +App::run()->send(); diff --git a/tests/thinkphp/library/think/appTest.php b/tests/thinkphp/library/think/appTest.php index b29bd459..f019cb7b 100644 --- a/tests/thinkphp/library/think/appTest.php +++ b/tests/thinkphp/library/think/appTest.php @@ -48,7 +48,6 @@ class appTest extends \PHPUnit_Framework_TestCase { public function testRun() { - Config::set('root_namespace', ['/path/']); App::run(Request::create("http://www.example.com"))->send(); $expectOutputString = '

:)

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

[ V5.0 版本由 七牛云 独家赞助发布 ]
'; @@ -57,7 +56,8 @@ class appTest extends \PHPUnit_Framework_TestCase $rc = new ReflectionClass('\think\Loader'); $ns = $rc->getProperty('namespace'); $ns->setAccessible(true); - $this->assertEquals(true, in_array('/path/', $ns->getValue())); + $namespace = $ns->getValue(); + $this->assertEquals(TEST_PATH, $namespace['tests']); $this->assertEquals(true, function_exists('lang')); $this->assertEquals(true, function_exists('config')); diff --git a/tests/thinkphp/library/think/loaderTest.php b/tests/thinkphp/library/think/loaderTest.php index faa9e434..4c9acd77 100644 --- a/tests/thinkphp/library/think/loaderTest.php +++ b/tests/thinkphp/library/think/loaderTest.php @@ -28,9 +28,9 @@ class loaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals(false, Loader::autoload('my\HelloTest')); } - public function testAddMap() + public function testAddClassMap() { - Loader::addMap('my\hello\Test', __DIR__ . DS . 'loader' . DS . 'Test.php'); + Loader::addClassMap('my\hello\Test', __DIR__ . DS . 'loader' . DS . 'Test.php'); } public function testAddNamespace() From f14ef530e8c8648eee325fa86f95fee14ca041b5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 14:17:14 +0800 Subject: [PATCH 478/670] =?UTF-8?q?=E5=8F=96=E6=B6=88APP=5FAUTO=5FRUN?= =?UTF-8?q?=E5=B8=B8=E9=87=8F=20=E8=B0=83=E6=95=B4=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E5=85=A5=E5=8F=A3=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 1 - tests/mock.php | 6 ++---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/base.php b/base.php index 9ed85ffc..052febe7 100644 --- a/base.php +++ b/base.php @@ -31,7 +31,6 @@ 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_'); // 环境变量的配置前缀 defined('IS_API') or define('IS_API', false); // 是否API接口 -defined('APP_AUTO_RUN') or define('APP_AUTO_RUN', true); // 是否自动运行 defined('AUTO_SCAN_PACKAGE') or define('AUTO_SCAN_PACKAGE', false); // 是否自动扫描非Composer安装类库 // 环境常量 diff --git a/tests/mock.php b/tests/mock.php index 4a620b0b..28471ee2 100644 --- a/tests/mock.php +++ b/tests/mock.php @@ -15,8 +15,6 @@ $_SERVER['REQUEST_METHOD'] = 'GET'; define('TEST_PATH', __DIR__ . '/'); // 定义项目路径 define('APP_PATH', __DIR__ . '/application/'); -// 关闭应用自动执行 -define('APP_AUTO_RUN', false); -// 加载框架引导文件 -require __DIR__ . '/../start.php'; +// 加载框架基础文件 +require __DIR__ . '/../base.php'; \think\Loader::addNamespace('tests', TEST_PATH); From b454adeef54ea1e0c0b24ca6d3488d217fc520f9 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 14:54:28 +0800 Subject: [PATCH 479/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BLoader=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=8A=A0=E8=BD=BD=20=E6=94=AF=E6=8C=81=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E5=91=BD=E5=90=8D=E7=A9=BA=E9=97=B4=E5=AF=B9=E5=BA=94?= =?UTF-8?q?=E5=A4=9A=E4=B8=AA=E8=B7=AF=E5=BE=84=20=E5=85=BC=E5=AE=B9compos?= =?UTF-8?q?er?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/library/think/Loader.php b/library/think/Loader.php index a94da475..6149751c 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -76,8 +76,17 @@ class Loader } else { return false; } - $filename = $path . str_replace('\\', DS, $class) . EXT; - if (is_file($filename)) { + // 定位文件 + $match = false; + foreach ((array) $path as $p) { + $filename = $p . str_replace('\\', DS, $class) . EXT; + if (is_file($filename)) { + $match = true; + break; + } + } + + if ($match) { // 开启调试模式Win环境严格区分大小写 if (IS_WIN && false === strpos(realpath($filename), $class . EXT)) { return false; @@ -87,7 +96,6 @@ class Loader return false; } } - return true; } // 注册classmap @@ -143,12 +151,13 @@ class Loader // 读取Composer自动加载文件 $autoload = include VENDOR_PATH . 'think_autoload.php'; if (is_array($autoload)) { - self::addClassMap($autoload); - } - } elseif (is_file(RUNTIME_PATH . 'autoload_composer.php')) { - $autoload = include RUNTIME_PATH . 'autoload_composer.php'; - if (is_array($autoload)) { - self::addNamespace($autoload); + // 命名空间和类库映射注册 + self::addNamespace($autoload['namespace']); + self::addClassMap($autoload['classmap']); + // 载入composer包的文件列表 + foreach ($autoload['files'] as $file) { + include $file; + } } } elseif (AUTO_SCAN_PACKAGE && is_dir(VENDOR_PATH)) { self::scanComposerPackage(VENDOR_PATH); From 7a00c1c14a6e51d0dc77e614b6fbe7c1494f52a7 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 22 Jun 2016 15:00:11 +0800 Subject: [PATCH 480/670] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E5=8F=B0=E5=85=A5=E5=8F=A3=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- console.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 console.php diff --git a/console.php b/console.php new file mode 100644 index 00000000..5947d3fe --- /dev/null +++ b/console.php @@ -0,0 +1,20 @@ + +// +---------------------------------------------------------------------- + +namespace think; + +// ThinkPHP 引导文件 +// 加载基础文件 +require __DIR__ . '/base.php'; + +// 执行应用 +App::initCommon(); +Console::init(); \ No newline at end of file From 897be354e4cddb8da1b774f8df6753c60607ef3f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 15:20:42 +0800 Subject: [PATCH 481/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BLoader=E7=B1=BB?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=8A=A0=E8=BD=BD=E7=9A=84=E6=96=87=E6=A1=A3?= =?UTF-8?q?=E5=AE=9A=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/library/think/Loader.php b/library/think/Loader.php index 6149751c..330bfdc9 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -60,7 +60,7 @@ class Loader return false; } $item = explode('\\', $class); - // 解析命名空间 + // 解析命名空间所在的路径 if (count($item) > 2 && isset(self::$namespace[$item[0] . '\\' . $item[1]])) { // 子命名空间定义(仅支持二级) list($ns1, $ns2, $class) = explode('\\', $class, 3); @@ -81,16 +81,16 @@ class Loader foreach ((array) $path as $p) { $filename = $p . str_replace('\\', DS, $class) . EXT; if (is_file($filename)) { + // Win环境严格区分大小写 + if (IS_WIN && false === strpos(realpath($filename), $class . EXT)) { + continue; + } $match = true; break; } } if ($match) { - // 开启调试模式Win环境严格区分大小写 - if (IS_WIN && false === strpos(realpath($filename), $class . EXT)) { - return false; - } include $filename; } else { return false; From b696d6186bd0ccc3f9bed2264ee916f6ac87a93d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 15:26:17 +0800 Subject: [PATCH 482/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 1 + 1 file changed, 1 insertion(+) diff --git a/library/think/Loader.php b/library/think/Loader.php index 330bfdc9..f9aa28e1 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -96,6 +96,7 @@ class Loader return false; } } + return true; } // 注册classmap From 54d16627d7bed8abd900e428e59bc962b04209c0 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 15:41:36 +0800 Subject: [PATCH 483/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Blang=E7=B1=BB?= =?UTF-8?q?=E7=9A=84detect=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Lang.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Lang.php b/library/think/Lang.php index b049dc01..571921be 100644 --- a/library/think/Lang.php +++ b/library/think/Lang.php @@ -102,7 +102,7 @@ class Lang public static function has($name, $range = '') { $range = $range ?: self::$range; - return isset(self::$lang[$range][strtolower($name)]); + return isset(self::$lang[$range][strtolower($name)]); } /** @@ -169,7 +169,7 @@ class Lang } if (empty(self::$allowLangList) || in_array($langSet, self::$allowLangList)) { // 合法的语言 - self::$range = $langSet; + self::$range = $langSet ?: self::$range; } return self::$range; } From 98084c7a47d447299362c23779c08322d02e6b3c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 15:45:39 +0800 Subject: [PATCH 484/670] =?UTF-8?q?Request=E7=B1=BB=E7=9A=84input=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=94=AF=E6=8C=81default=5Ffilter=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 1 + 1 file changed, 1 insertion(+) diff --git a/library/think/Request.php b/library/think/Request.php index 6013448e..b41b135a 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -126,6 +126,7 @@ class Request $this->$name = $item; } } + $this->filter = Config::get('default_filter'); } public function __call($method, $args) From 18a4eee00f1d070a3c2855245af694411aa770b5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 16:00:03 +0800 Subject: [PATCH 485/670] =?UTF-8?q?Loader=E7=B1=BB=E7=9A=84composer?= =?UTF-8?q?=E5=8C=85=E6=89=AB=E6=8F=8F=E6=96=B9=E6=B3=95=E6=94=B9=E4=B8=BA?= =?UTF-8?q?public=20=E4=BE=9B=E5=91=BD=E4=BB=A4=E8=A1=8C=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 66 ++++++++++++++-------------------------- 1 file changed, 23 insertions(+), 43 deletions(-) diff --git a/library/think/Loader.php b/library/think/Loader.php index f9aa28e1..334f2a1e 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -160,64 +160,44 @@ class Loader include $file; } } - } elseif (AUTO_SCAN_PACKAGE && is_dir(VENDOR_PATH)) { - self::scanComposerPackage(VENDOR_PATH); } } // 扫描composer package - private static function scanComposerPackage($path) + public static function scanComposerPackage($path) { // 自动扫描下载Composer安装类库 - $dirs = scandir($path, 1); + $dirs = scandir($path, 1); + $namespace = $files = $classmap = []; foreach ($dirs as $dir) { if ('.' != $dir && '..' != $dir && is_dir($path . $dir) && is_file($path . $dir . DS . 'composer.json')) { // 解析Composer 包 - self::parseComposerPackage($path . $dir . DS); - } - } + $content = file_get_contents($path . $dir . DS . 'composer.json'); + $result = json_decode($content, true); - $content = " $path) { + $namespace[rtrim($ns, '\\')] = realpath($package . $path . DS . str_replace('\\', DS, $ns)) . DS; + } + } - if (!empty(self::$namespace)) { - $content .= "return " . var_export(self::$namespace, true) . ';' . PHP_EOL; - } - // 生成缓存 - file_put_contents(RUNTIME_PATH . 'autoload_composer.php', $content); - } + if (isset($autoload['psr-4'])) { + foreach ($autoload['psr-4'] as $ns => $path) { + $namespace[rtrim($ns, '\\')] = realpath($package . $path) . DS; + } + } - // 解析Composer Package - private static function parseComposerPackage($package) - { - $content = file_get_contents($package . 'composer.json'); - $result = json_decode($content, true); - - if (!empty($result['autoload'])) { - $autoload = $result['autoload']; - if (isset($autoload['psr-0'])) { - foreach ($autoload['psr-0'] as $ns => $path) { - self::$namespace[rtrim($ns, '\\')] = realpath($package . $path . DS . str_replace('\\', DS, $ns)) . DS; - } - } - - if (isset($autoload['psr-4'])) { - foreach ($autoload['psr-4'] as $ns => $path) { - self::$namespace[rtrim($ns, '\\')] = realpath($package . $path) . DS; - } - } - - if (isset($autoload['files'])) { - foreach ($autoload['files'] as $file) { - self::$load[] = realpath($package . $file); - require $package . $file; + if (isset($autoload['files'])) { + foreach ($autoload['files'] as $file) { + $files[] = realpath($package . $file); + } + } } } } + return ['namespace' => $namespace, 'files' => $files, 'classmap' => $classmap]; } // 注册composer自动加载 From c654eab7e9db84df3fc4bb7bb3c9f3cbfa0fca53 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 16:23:23 +0800 Subject: [PATCH 486/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Request=E7=B1=BB?= =?UTF-8?q?=E7=9A=84input=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index b41b135a..f72d6bb5 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -984,7 +984,7 @@ class Request $value = $default; break; } - } else { + } elseif (!empty($filter)) { // filter函数不存在时, 则使用filter_var进行过滤 // filter为非整形值时, 调用filter_id取得过滤id $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter)); From 9beac2bba404f2ff49f6510915b13d0534866757 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 17:53:00 +0800 Subject: [PATCH 487/670] =?UTF-8?q?Loader=E7=B1=BBscanComposerPackage?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E5=A2=9E=E5=8A=A0classmap=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 54 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/library/think/Loader.php b/library/think/Loader.php index 334f2a1e..dddc4163 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -172,23 +172,48 @@ class Loader foreach ($dirs as $dir) { if ('.' != $dir && '..' != $dir && is_dir($path . $dir) && is_file($path . $dir . DS . 'composer.json')) { // 解析Composer 包 - $content = file_get_contents($path . $dir . DS . 'composer.json'); + $package = $path . $dir . DS; + $content = file_get_contents($package . 'composer.json'); $result = json_decode($content, true); if (!empty($result['autoload'])) { $autoload = $result['autoload']; if (isset($autoload['psr-0'])) { - foreach ($autoload['psr-0'] as $ns => $path) { - $namespace[rtrim($ns, '\\')] = realpath($package . $path . DS . str_replace('\\', DS, $ns)) . DS; + foreach ($autoload['psr-0'] as $ns => $val) { + $namespace[rtrim($ns, '\\')] = realpath($package . $val . DS . str_replace('\\', DS, $ns)) . DS; } } if (isset($autoload['psr-4'])) { - foreach ($autoload['psr-4'] as $ns => $path) { - $namespace[rtrim($ns, '\\')] = realpath($package . $path) . DS; + foreach ($autoload['psr-4'] as $ns => $val) { + $namespace[rtrim($ns, '\\')] = realpath($package . $val) . DS; } } + if (isset($autoload['classmap'])) { + foreach ($autoload['classmap'] as $val) { + if (strpos($val, '/')) { + // 扫描目录 + $files = scandir($package . $val); + foreach ($files as $file) { + if ('php' == pathinfo($file, PATHINFO_EXTENSION)) { + $file = realpath($package . $val . DS . $file); + $info = self::parsePhpNamespace($file); + foreach ($info as $class) { + $classmap[$class] = $file; + } + } + } + } else { + // 解析文件 + $file = realpath($package . $val); + $info = self::parsePhpNamespace($file); + foreach ($info as $class) { + $classmap[$class] = $file; + } + } + } + } if (isset($autoload['files'])) { foreach ($autoload['files'] as $file) { $files[] = realpath($package . $file); @@ -200,6 +225,25 @@ class Loader return ['namespace' => $namespace, 'files' => $files, 'classmap' => $classmap]; } + private static function parsePhpNamespace($file) + { + $content = php_strip_whitespace($file); + $content = substr($content, 5); + if (0 === strpos(ltrim($content), 'namespace')) { + preg_match('/\snamespace\s(.*?);/', $content, $matches); + $namespace = $matches[1] . '\\'; + } else { + $namespace = ''; + } + preg_match_all('/\sclass\s(\w+)\s?\{/', $content, $matches); + + $info = []; + foreach ($matches[1] as $class) { + $info[] = $namespace . $class; + } + return $info; + } + // 注册composer自动加载 private static function registerComposerLoader() { From eebcadc976f522054a65bf278e998a4139498f86 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 18:06:35 +0800 Subject: [PATCH 488/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BLoader=E7=B1=BB?= =?UTF-8?q?=E7=9A=84parsePhpNamespace=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/library/think/Loader.php b/library/think/Loader.php index dddc4163..6b59f4f5 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -225,17 +225,18 @@ class Loader return ['namespace' => $namespace, 'files' => $files, 'classmap' => $classmap]; } + // 解析PHP文件 获取类的命名空间 private static function parsePhpNamespace($file) { $content = php_strip_whitespace($file); $content = substr($content, 5); if (0 === strpos(ltrim($content), 'namespace')) { - preg_match('/\snamespace\s(.*?);/', $content, $matches); + preg_match('/\snamespace\s(.*?);/is', $content, $matches); $namespace = $matches[1] . '\\'; } else { $namespace = ''; } - preg_match_all('/\sclass\s(\w+)\s?\{/', $content, $matches); + preg_match_all('/[\s|\;\}]class\s(\w+)\s?\{/is', $content, $matches); $info = []; foreach ($matches[1] as $class) { From 8ac769f343db48d85d70c09f5fc51c9c922130bd Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 18:09:46 +0800 Subject: [PATCH 489/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E4=B8=80=E5=A4=84?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/Loader.php b/library/think/Loader.php index 6b59f4f5..a63dfe04 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -194,8 +194,8 @@ class Loader foreach ($autoload['classmap'] as $val) { if (strpos($val, '/')) { // 扫描目录 - $files = scandir($package . $val); - foreach ($files as $file) { + $items = scandir($package . $val); + foreach ($items as $file) { if ('php' == pathinfo($file, PATHINFO_EXTENSION)) { $file = realpath($package . $val . DS . $file); $info = self::parsePhpNamespace($file); From 13103c84c7505208eb89253da7cb66a93428f071 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 18:14:25 +0800 Subject: [PATCH 490/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 135 ++++++++++++++++++++++++++--------------------------- 1 file changed, 67 insertions(+), 68 deletions(-) diff --git a/helper.php b/helper.php index 8e7908c8..adaa31c1 100644 --- a/helper.php +++ b/helper.php @@ -29,8 +29,8 @@ use think\View; /** * 快速导入Traits PHP5.5以上无需调用 - * @param string $class trait库 - * @param string $ext 类库后缀 + * @param string $class trait库 + * @param string $ext 类库后缀 * @return boolean */ function load_trait($class, $ext = EXT) @@ -41,9 +41,9 @@ function load_trait($class, $ext = EXT) /** * 抛出异常处理 * - * @param string $msg 异常消息 - * @param integer $code 异常代码 默认为0 - * @param string $exception 异常类 + * @param string $msg 异常消息 + * @param integer $code 异常代码 默认为0 + * @param string $exception 异常类 * * @throws Exception */ @@ -55,9 +55,9 @@ function exception($msg, $code = 0, $exception = '') /** * 记录时间(微秒)和内存使用情况 - * @param string $start 开始标签 - * @param string $end 结束标签 - * @param integer|string $dec 小数位 如果是m 表示统计内存占用 + * @param string $start 开始标签 + * @param string $end 结束标签 + * @param integer|string $dec 小数位 如果是m 表示统计内存占用 * @return mixed */ function debug($start, $end = '', $dec = 6) @@ -71,9 +71,9 @@ function debug($start, $end = '', $dec = 6) /** * 获取语言变量值 - * @param string $name 语言变量名 - * @param array $vars 动态变量值 - * @param string $lang 语言 + * @param string $name 语言变量名 + * @param array $vars 动态变量值 + * @param string $lang 语言 * @return mixed */ function lang($name, $vars = [], $lang = '') @@ -83,9 +83,9 @@ function lang($name, $vars = [], $lang = '') /** * 获取和设置配置参数 - * @param string|array $name 参数名 - * @param mixed $value 参数值 - * @param string $range 作用域 + * @param string|array $name 参数名 + * @param mixed $value 参数值 + * @param string $range 作用域 * @return mixed */ function config($name = '', $value = null, $range = '') @@ -99,10 +99,9 @@ function config($name = '', $value = null, $range = '') /** * 获取输入数据 支持默认值和过滤 - * @param string $key 获取的变量名 - * @param mixed $default 默认值 - * @param string $filter 过滤方法 - * @param bool $merge 是否合并系统默认过滤方法 + * @param string $key 获取的变量名 + * @param mixed $default 默认值 + * @param string $filter 过滤方法 * @return mixed */ function input($key, $default = null, $filter = null) @@ -123,17 +122,17 @@ function input($key, $default = null, $filter = null) // 默认为自动判断 $method = 'param'; } - if(isset($has)){ + if (isset($has)) { return request()->has($key, $method, $default); - }else{ + } else { return request()->$method($key, $default, $filter); } } /** * 渲染输出Widget - * @param string $name Widget名称 - * @param array $data 传人的参数 + * @param string $name Widget名称 + * @param array $data 传人的参数 * @return mixed */ function widget($name, $data = []) @@ -143,9 +142,9 @@ function widget($name, $data = []) /** * 实例化Model - * @param string $name Model名称 - * @param string $layer 业务层名称 - * @param bool $appendSuffix 是否添加类名后缀 + * @param string $name Model名称 + * @param string $layer 业务层名称 + * @param bool $appendSuffix 是否添加类名后缀 * @return \think\Model */ function model($name = '', $layer = 'model', $appendSuffix = false) @@ -155,9 +154,9 @@ function model($name = '', $layer = 'model', $appendSuffix = false) /** * 实例化验证器 - * @param string $name 验证器名称 - * @param string $layer 业务层名称 - * @param bool $appendSuffix 是否添加类名后缀 + * @param string $name 验证器名称 + * @param string $layer 业务层名称 + * @param bool $appendSuffix 是否添加类名后缀 * @return \think\Validate */ function validate($name = '', $layer = 'validate', $appendSuffix = false) @@ -167,8 +166,8 @@ function validate($name = '', $layer = 'validate', $appendSuffix = false) /** * 实例化数据库类 - * @param string $name 操作的数据表名称(不含前缀) - * @param array|string $config 数据库配置参数 + * @param string $name 操作的数据表名称(不含前缀) + * @param array|string $config 数据库配置参数 * @return \think\db\Query */ function db($name = '', $config = []) @@ -178,9 +177,9 @@ function db($name = '', $config = []) /** * 实例化控制器 格式:[模块/]控制器 - * @param string $name 资源地址 - * @param string $layer 控制层名称 - * @param bool $appendSuffix 是否添加类名后缀 + * @param string $name 资源地址 + * @param string $layer 控制层名称 + * @param bool $appendSuffix 是否添加类名后缀 * @return \think\Controller */ function controller($name, $layer = 'controller', $appendSuffix = false) @@ -190,10 +189,10 @@ function controller($name, $layer = 'controller', $appendSuffix = false) /** * 调用模块的操作方法 参数格式 [模块/控制器/]操作 - * @param string $url 调用地址 - * @param string|array $vars 调用参数 支持字符串和数组 - * @param string $layer 要调用的控制层名称 - * @param bool $appendSuffix 是否添加类名后缀 + * @param string $url 调用地址 + * @param string|array $vars 调用参数 支持字符串和数组 + * @param string $layer 要调用的控制层名称 + * @param bool $appendSuffix 是否添加类名后缀 * @return mixed */ function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) @@ -203,9 +202,9 @@ function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) /** * 导入所需的类库 同java的Import 本函数有缓存功能 - * @param string $class 类库命名空间字符串 - * @param string $baseUrl 起始路径 - * @param string $ext 导入的文件扩展名 + * @param string $class 类库命名空间字符串 + * @param string $baseUrl 起始路径 + * @param string $ext 导入的文件扩展名 * @return boolean */ function import($class, $baseUrl = '', $ext = EXT) @@ -215,8 +214,8 @@ function import($class, $baseUrl = '', $ext = EXT) /** * 快速导入第三方框架类库 所有第三方框架的类库文件统一放到 系统的Vendor目录下面 - * @param string $class 类库 - * @param string $ext 类库后缀 + * @param string $class 类库 + * @param string $ext 类库后缀 * @return boolean */ function vendor($class, $ext = EXT) @@ -226,9 +225,9 @@ function vendor($class, $ext = EXT) /** * 浏览器友好的变量输出 - * @param mixed $var 变量 - * @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串 - * @param string $label 标签 默认为空 + * @param mixed $var 变量 + * @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串 + * @param string $label 标签 默认为空 * @return void|string */ function dump($var, $echo = true, $label = null) @@ -238,10 +237,10 @@ function dump($var, $echo = true, $label = null) /** * Url生成 - * @param string $url 路由地址 - * @param string|array $value 变量 - * @param bool|string $suffix 前缀 - * @param bool|string $domain 域名 + * @param string $url 路由地址 + * @param string|array $value 变量 + * @param bool|string $suffix 前缀 + * @param bool|string $domain 域名 * @return string */ function url($url = '', $vars = '', $suffix = true, $domain = false) @@ -251,9 +250,9 @@ function url($url = '', $vars = '', $suffix = true, $domain = false) /** * Session管理 - * @param string|array $name session名称,如果为数组表示进行session设置 - * @param mixed $value session值 - * @param string $prefix 前缀 + * @param string|array $name session名称,如果为数组表示进行session设置 + * @param mixed $value session值 + * @param string $prefix 前缀 * @return mixed */ function session($name, $value = '', $prefix = null) @@ -278,9 +277,9 @@ function session($name, $value = '', $prefix = null) /** * Cookie管理 - * @param string|array $name cookie名称,如果为数组表示进行cookie设置 - * @param mixed $value cookie值 - * @param mixed $option 参数 + * @param string|array $name cookie名称,如果为数组表示进行cookie设置 + * @param mixed $value cookie值 + * @param mixed $option 参数 * @return mixed */ function cookie($name, $value = '', $option = null) @@ -305,9 +304,9 @@ function cookie($name, $value = '', $option = null) /** * 缓存管理 - * @param mixed $name 缓存名称,如果为数组表示进行缓存设置 - * @param mixed $value 缓存值 - * @param mixed $options 缓存参数 + * @param mixed $name 缓存名称,如果为数组表示进行缓存设置 + * @param mixed $value 缓存值 + * @param mixed $options 缓存参数 * @return mixed */ function cache($name, $value = '', $options = null) @@ -338,8 +337,8 @@ function cache($name, $value = '', $options = null) /** * 记录日志信息 - * @param mixed $log log信息 支持字符串和数组 - * @param string $level 日志级别 + * @param mixed $log log信息 支持字符串和数组 + * @param string $level 日志级别 * @return void|array */ function trace($log = '[think]', $level = 'log') @@ -375,9 +374,9 @@ function response($data = [], $code = 200, $header = [], $type = 'html') /** * 渲染模板输出 - * @param string $template 模板文件 - * @param array $vars 模板变量 - * @param integer $code 状态码 + * @param string $template 模板文件 + * @param array $vars 模板变量 + * @param integer $code 状态码 * @return \think\response\View */ function view($template = '', $vars = [], $code = 200) @@ -426,9 +425,9 @@ function xml($data = [], $code = 200, $header = [], $options = []) /** * 获取\think\response\Redirect对象实例 - * @param mixed $url 重定向地址 支持Url::build方法的地址 + * @param mixed $url 重定向地址 支持Url::build方法的地址 * @param array|integer $params 额外参数 - * @param integer $code 状态码 + * @param integer $code 状态码 * @return \think\response\Redirect */ function redirect($url = [], $params = [], $code = 302) @@ -442,9 +441,9 @@ function redirect($url = [], $params = [], $code = 302) /** * 抛出HTTP异常 - * @param integer $code 状态码 - * @param string $message 错误信息 - * @param array $header 参数 + * @param integer $code 状态码 + * @param string $message 错误信息 + * @param array $header 参数 */ function abort($code, $message = null, $header = []) { From 62de83358a86190ba8aa935afd176797b5c4f2e6 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 22:28:41 +0800 Subject: [PATCH 491/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Merge=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Merge.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 8ade20ce..2239af73 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -250,7 +250,7 @@ class Merge extends Model return $result; } catch (\Exception $e) { $db->rollback(); - return false; + throw $e; } } @@ -283,9 +283,9 @@ class Merge extends Model $this->trigger('after_delete', $this); $db->commit(); return $result; - } catch (\PDOException $e) { + } catch (\Exception $e) { $db->rollback(); - return false; + throw $e; } } From 275d93cc38a634208278690686fdb846c6661a5d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 23:44:49 +0800 Subject: [PATCH 492/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Connection=E7=B1=BB?= =?UTF-8?q?=E7=9A=84batchQuery?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Connection.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 410c661f..73669031 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -647,9 +647,9 @@ abstract class Connection } // 提交事务 $this->commit(); - } catch (\PDOException $e) { + } catch (\Exception $e) { $this->rollback(); - return false; + throw $e; } return true; } From 34579bfa4456495e648b938d083c743948a46588 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 22 Jun 2016 23:51:20 +0800 Subject: [PATCH 493/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB?= =?UTF-8?q?=E7=9A=84relation=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index a9be8662..ddeeb95e 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -164,10 +164,17 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 获取关联模型实例 * @access protected - * @return Relation + * @param string|array $relation 关联查询 + * @return Relation|Query */ - protected function relation() + protected function relation($relation = null) { + if (!is_null($relation)) { + // 执行关联查询 + return $this->db->relation($relation); + } + + // 获取关联对象实例 if (is_null($this->relation)) { $this->relation = new Relation($this); } From 5b061cd99826a50305cb89a921c3b9f51898f883 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 23 Jun 2016 12:07:25 +0800 Subject: [PATCH 494/670] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E8=AF=BB=E5=8F=96=E6=94=B9=E4=B8=BA=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=20=E4=BF=9D=E6=8C=81=E6=95=B0=E6=8D=AE=E5=BA=93=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E5=A4=A7=E5=B0=8F=E5=86=99=20Connection=E7=B1=BBfield?= =?UTF-8?q?Case=E6=96=B9=E6=B3=95=E6=94=B9=E4=B8=BApublic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 4 ++-- library/think/db/Connection.php | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index ddeeb95e..450675dc 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -257,11 +257,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess list($type, $param) = explode(':', $type, 2); } switch ($type) { - case 'timestamp': + case 'datetime': $format = !empty($param) ? $param : $this->dateFormat; $value = date($format, $_SERVER['REQUEST_TIME']); break; - case 'datetime': + case 'timestamp': $value = $_SERVER['REQUEST_TIME']; break; } diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 73669031..bfdafe6c 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -16,11 +16,11 @@ use PDOStatement; use think\App; use think\Collection; use think\Db; +use think\db\exception\BindParamException; use think\db\Query; use think\Debug; use think\Exception; use think\exception\PDOException; -use think\db\exception\BindParamException; use think\Log; abstract class Connection @@ -102,7 +102,7 @@ abstract class Connection // PDO连接参数 protected $params = [ - PDO::ATTR_CASE => PDO::CASE_LOWER, + PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, @@ -188,7 +188,7 @@ abstract class Connection * @param array $info 字段信息 * @return array */ - protected function fieldCase($info) + public function fieldCase($info) { // 字段大小写转换 switch ($this->attrCase) { @@ -330,7 +330,7 @@ abstract class Connection } // 根据参数绑定组装最终的SQL语句 $this->queryStr = $this->getRealSql($sql, $bind); - + //释放前次的查询结果 if (!empty($this->PDOStatement)) { $this->free(); @@ -482,7 +482,7 @@ abstract class Connection if (!empty($class)) { // 返回指定数据集对象类 $result = new $class($result); - } elseif ('collection' == $this->resultSetType){ + } elseif ('collection' == $this->resultSetType) { // 返回数据集Collection对象 $result = new Collection($result); } @@ -551,7 +551,7 @@ abstract class Connection ++$this->transTimes; - if ($this->transTimes == 1) { + if (1 == $this->transTimes) { $this->linkID->beginTransaction(); } elseif ($this->transTimes > 1 && $this->supportSavepoint()) { $this->linkID->exec( @@ -570,7 +570,7 @@ abstract class Connection { $this->initConnect(true); - if ($this->transTimes == 1) { + if (1 == $this->transTimes) { $this->linkID->commit(); } @@ -587,7 +587,7 @@ abstract class Connection { $this->initConnect(true); - if ($this->transTimes == 1) { + if (1 == $this->transTimes) { $this->linkID->rollBack(); } elseif ($this->transTimes > 1 && $this->supportSavepoint()) { $this->linkID->exec( From dc73254db320c64acafe9eb6b2977a4810bd4b96 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 23 Jun 2016 17:08:12 +0800 Subject: [PATCH 495/670] =?UTF-8?q?reamde=E6=96=87=E4=BB=B6=E4=BF=AE?= =?UTF-8?q?=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 38 ++++++++++----------------------- library/think/db/Connection.php | 2 +- 2 files changed, 12 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index f4a0a628..2696a35b 100644 --- a/README.md +++ b/README.md @@ -39,12 +39,8 @@ ThinkPHP5在保持快速开发和大道至简的核心理念不变的同时,PH ~~~ www WEB部署目录(或者子目录) -├─composer.json composer定义文件 -├─README.md README文件 -├─LICENSE.txt 授权说明文件 ├─application 应用目录 │ ├─common 公共模块目录(可以更改) -│ ├─runtime 应用的运行时目录(可写,可定制) │ ├─module_name 模块目录 │ │ ├─config.php 模块配置文件 │ │ ├─common.php 模块函数文件 @@ -53,6 +49,7 @@ www WEB部署目录(或者子目录) │ │ ├─view 视图目录 │ │ └─ ... 更多类库目录 │ │ +│ ├─command.php 命令行工具配置文件 │ ├─common.php 公共函数文件 │ ├─config.php 公共配置文件 │ ├─route.php 路由配置文件 @@ -60,6 +57,7 @@ www WEB部署目录(或者子目录) │ ├─public WEB目录(对外访问目录) │ ├─index.php 入口文件 +│ ├─router.php 快速测试文件 │ └─.htaccess 用于apache的重写 │ ├─thinkphp 框架系统目录 @@ -68,17 +66,24 @@ www WEB部署目录(或者子目录) │ │ ├─think Think类库包目录 │ │ └─traits 系统Trait目录 │ │ -│ ├─mode 应用模式目录 │ ├─tpl 系统模板目录 │ ├─tests 单元测试文件目录 │ ├─base.php 基础定义文件 +│ ├─classmap.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支持,可用于快速测试 @@ -87,28 +92,7 @@ www WEB部署目录(或者子目录) ## 命名规范 -ThinkPHP5的命名规范如下: - -### 目录和文件 - -* 目录不强制规范,驼峰和小写+下划线模式均支持; -* 类库、函数文件统一以`.php`为后缀; -* 类的文件名均以命名空间定义,并且命名空间的路径和类库文件所在路径一致; -* 类名和类文件名保持一致,统一采用驼峰法命名(首字母大写); - -### 函数和类、属性命名 -* 类的命名采用驼峰法,并且首字母大写,例如 `User`、`UserType`,不需要添加后缀,例如UserController应该直接命名为User; -* 函数的命名使用小写字母和下划线(小写字母开头)的方式,例如 `get_client_ip`; -* 方法的命名使用驼峰法,并且首字母小写或者使用下划线“_”,例如 `getUserName`,`_parseType`,通常下划线开头的方法属于私有方法; -* 属性的命名使用驼峰法,并且首字母小写或者使用下划线“_”,例如 `tableName`、`_instance`,通常下划线开头的属性属于私有属性; -* 以双下划线“__”打头的函数或方法作为魔法方法,例如 `__call` 和 `__autoload`; - -### 常量和配置 -* 常量以大写字母和下划线命名,例如 `APP_DEBUG`和 `APP_MODE`; -* 配置参数以小写字母和下划线命名,例如 `url_route_on`; - -### 数据表和字段 -* 数据表和字段采用小写加下划线方式命名,并注意字段名不要以下划线开头,例如 think_user 表和 user_name字段,类似 _username 这样的数据表字段可能会被过滤。 +ThinkPHP5的命名规范遵循PSR-2规范以及PSR-4自动加载规范。 ## 参与开发 注册并登录 Github 帐号, fork 本项目并进行改动。 diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index bfdafe6c..a45d8d3e 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -474,6 +474,7 @@ abstract class Connection return $this->PDOStatement; } if ($procedure) { + // 存储过程返回结果 return $this->procedure($class); } $result = $this->PDOStatement->fetchAll($this->fetchType); @@ -486,7 +487,6 @@ abstract class Connection // 返回数据集Collection对象 $result = new Collection($result); } - return $result; } From 38124ccd12adf26f6a8874c21b9a32257fdc0bb4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 23 Jun 2016 17:13:07 +0800 Subject: [PATCH 496/670] =?UTF-8?q?Request=E7=B1=BB=E6=B7=BB=E5=8A=A0getCo?= =?UTF-8?q?ntent=E6=96=B9=E6=B3=95=EF=BC=8Ccreate=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0content=E5=8F=82=E6=95=B0=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E4=BC=AA=E9=80=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index f72d6bb5..8d4f6c78 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -109,6 +109,8 @@ class Request 'csv' => 'text/csv', ]; + protected $content; + // 全局过滤规则 protected $filter; // Hook扩展方法 @@ -178,9 +180,10 @@ class Request * @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 = []) + public static function create($uri, $method = 'GET', $params = [], $cookie = [], $files = [], $server = [], $content = null) { $server['PATH_INFO'] = ''; $server['REQUEST_METHOD'] = strtoupper($method); @@ -236,6 +239,7 @@ class Request $options['pathinfo'] = ltrim($info['path'], '/'); $options['method'] = $server['REQUEST_METHOD']; $options['domain'] = $server['HTTP_HOST']; + $options['content'] = $content; self::$instance = new self($options); return self::$instance; } @@ -1367,4 +1371,16 @@ class Request } } + /** + * 设置或者获取当前请求的content + * @access public + * @return string + */ + public function getContent() + { + if (null === $this->content) { + $this->content = file_get_contents('php://input'); + } + return $this->content; + } } From ebc862e5fbe1fc09f80f98ec168a297b6e8a9ce4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 23 Jun 2016 17:49:38 +0800 Subject: [PATCH 497/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB?= =?UTF-8?q?=E5=8F=AF=E9=80=89=E5=8F=82=E6=95=B0=E7=9A=84=E5=AE=8C=E6=95=B4?= =?UTF-8?q?=E5=8C=B9=E9=85=8D=E6=A3=80=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index dbb9cd64..b484a4f7 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -210,8 +210,8 @@ class Route */ public static function rule($rule, $route = '', $type = '*', $option = [], $pattern = [], $group = '') { - $group = $group ?: self::$group; - $type = strtoupper($type); + $group = $group ?: self::$group; + $type = strtoupper($type); if (strpos($type, '|')) { foreach (explode('|', $type) as $val) { self::rule($rule, $route, $val, $option, $pattern, $group); @@ -522,7 +522,7 @@ class Route /** * 检测子域名部署 * @access public - * @param Request $request Request请求对象 + * @param Request $request Request请求对象 * @return void */ public static function checkDomain($request) @@ -910,7 +910,7 @@ class Route if ($len1 >= $len2 || strpos($rule, '[')) { if ('$' == substr($rule, -1, 1)) { // 完整匹配 - if (!$merge && $len1 != $len2 && false === strpos($rule, '[')) { + if (!$merge && $len1 != $len2 && (false === strpos($rule, '[') || $len1 > $len2 || $len1 < $len2 - substr_count($rule, '['))) { return false; } else { $rule = substr($rule, 0, -1); @@ -924,12 +924,12 @@ class Route if ($option['after_behavior'] instanceof \Closure) { $result = call_user_func_array($option['after_behavior'], [$route]); } else { - foreach((array)$option['after_behavior'] as $behavior){ + foreach ((array) $option['after_behavior'] as $behavior) { $result = Hook::exec($behavior, '', $route); if (!is_null($result)) { break; } - } + } } // 路由规则重定向 if ($result instanceof Response) { From 57ca7a376bcfd505ea6685b8fe3a90fa068d9292 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 23 Jun 2016 18:37:46 +0800 Subject: [PATCH 498/670] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A0=87=E7=AD=BE?= =?UTF-8?q?=E5=BA=93=E7=9A=84=E6=96=B9=E6=B3=95=E5=91=BD=E5=90=8D=20?= =?UTF-8?q?=E5=8F=96=E6=B6=88=20import=E6=A0=87=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 +- library/think/Template.php | 2 +- library/think/template/TagLib.php | 4 +- library/think/template/taglib/Cx.php | 119 ++++++++++----------------- 4 files changed, 46 insertions(+), 81 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 8d4f6c78..39981afe 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -1378,7 +1378,7 @@ class Request */ public function getContent() { - if (null === $this->content) { + if (is_null($this->content)) { $this->content = file_get_contents('php://input'); } return $this->content; diff --git a/library/think/Template.php b/library/think/Template.php index 18a37d86..a0f27706 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -672,7 +672,7 @@ class Template */ public function parseTagLib($tagLib, &$content, $hide = false) { - if (strpos($tagLib, '\\')) { + if (false !== strpos($tagLib, '\\')) { // 支持指定标签库的命名空间 $className = $tagLib; $tagLib = substr($tagLib, strrpos($tagLib, '\\') + 1); diff --git a/library/think/template/TagLib.php b/library/think/template/TagLib.php index 456036e0..54e09da3 100644 --- a/library/think/template/TagLib.php +++ b/library/think/template/TagLib.php @@ -138,7 +138,7 @@ class TagLib $alias = $_lib . $name != $node['name'] ? ($_lib ? strstr($node['name'], $_lib) : $node['name']) : ''; // 解析标签属性 $attrs = $this->parseAttr($node['begin'][0], $name, $alias); - $method = '_' . $name; + $method = 'tag' . $name; // 读取标签库中对应的标签内容 replace[0]用来替换标签头,replace[1]用来替换标签尾 $replace = explode($break, $this->$method($attrs, $break)); if (count($replace) > 1) { @@ -176,7 +176,7 @@ class TagLib $alias = $_lib . $name != $matches[1] ? ($_lib ? strstr($matches[1], $_lib) : $matches[1]) : ''; // 解析标签属性 $attrs = $this->parseAttr($matches[0], $name, $alias); - $method = '_' . $name; + $method = 'tag' . $name; return $this->$method($attrs, ''); }, $content); } diff --git a/library/think/template/taglib/Cx.php b/library/think/template/taglib/Cx.php index b085b83a..021178b3 100644 --- a/library/think/template/taglib/Cx.php +++ b/library/think/template/taglib/Cx.php @@ -43,8 +43,7 @@ class Cx extends Taglib 'notpresent' => ['attr' => 'name'], 'defined' => ['attr' => 'name'], 'notdefined' => ['attr' => 'name'], - 'import' => ['attr' => 'file,href,type,value,basepath', 'close' => 0], - 'load' => ['attr' => 'file,href,type,value,basepath', 'close' => 0, 'alias' => ['css,js', 'type']], + 'load' => ['attr' => 'file,href,type,value,basepath', 'close' => 0, 'alias' => ['import,css,js', 'type']], 'assign' => ['attr' => 'name,value', 'close' => 0], 'define' => ['attr' => 'name,value', 'close' => 0], 'for' => ['attr' => 'start,end,name,comparison,step'], @@ -61,7 +60,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _php($tag, $content) + public function tagPhp($tag, $content) { $parseStr = ''; return $parseStr; @@ -79,7 +78,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string|void */ - public function _volist($tag, $content) + public function tagVolist($tag, $content) { $name = $tag['name']; $id = $tag['id']; @@ -131,7 +130,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string|void */ - public function _foreach($tag, $content) + public function tagForeach($tag, $content) { // 直接使用表达式 if (!empty($tag['expression'])) { @@ -212,7 +211,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _if($tag, $content) + public function tagIf($tag, $content) { $condition = !empty($tag['expression']) ? $tag['expression'] : $tag['condition']; $condition = $this->parseCondition($condition); @@ -228,7 +227,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _elseif($tag, $content) + public function tagElseif($tag, $content) { $condition = !empty($tag['expression']) ? $tag['expression'] : $tag['condition']; $condition = $this->parseCondition($condition); @@ -243,7 +242,7 @@ class Cx extends Taglib * @param array $tag 标签属性 * @return string */ - public function _else($tag) + public function tagElse($tag) { $parseStr = ''; return $parseStr; @@ -262,7 +261,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _switch($tag, $content) + public function tagSwitch($tag, $content) { $name = !empty($tag['expression']) ? $tag['expression'] : $tag['name']; $name = $this->autoBuildVar($name); @@ -277,7 +276,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _case($tag, $content) + public function tagCase($tag, $content) { $value = !empty($tag['expression']) ? $tag['expression'] : $tag['value']; $flag = substr($value, 0, 1); @@ -309,7 +308,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _default($tag) + public function tagDefault($tag) { $parseStr = ''; return $parseStr; @@ -324,7 +323,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _compare($tag, $content) + public function tagCompare($tag, $content) { $name = $tag['name']; $value = $tag['value']; @@ -359,7 +358,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _range($tag, $content) + public function tagRange($tag, $content) { $name = $tag['name']; $value = $tag['value']; @@ -394,7 +393,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _present($tag, $content) + public function tagPresent($tag, $content) { $name = $tag['name']; $name = $this->autoBuildVar($name); @@ -411,7 +410,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _notpresent($tag, $content) + public function tagNotpresent($tag, $content) { $name = $tag['name']; $name = $this->autoBuildVar($name); @@ -428,7 +427,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _empty($tag, $content) + public function tagEmpty($tag, $content) { $name = $tag['name']; $name = $this->autoBuildVar($name); @@ -445,7 +444,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _notempty($tag, $content) + public function tagNotempty($tag, $content) { $name = $tag['name']; $name = $this->autoBuildVar($name); @@ -460,7 +459,7 @@ class Cx extends Taglib * @param string $content * @return string */ - public function _defined($tag, $content) + public function tagDefined($tag, $content) { $name = $tag['name']; $parseStr = '' . $content . ''; @@ -474,7 +473,7 @@ class Cx extends Taglib * @param string $content * @return string */ - public function _notdefined($tag, $content) + public function tagNotdefined($tag, $content) { $name = $tag['name']; $parseStr = '' . $content . ''; @@ -482,19 +481,17 @@ class Cx extends Taglib } /** - * import 标签解析 {import file="Js.Base" /} - * 格式:{import file="Css.Base" type="css" /} + * load 标签解析 {load file="/static/js/base.js" /} + * 格式:{load file="/static/css/base.css" /} * @access public * @param array $tag 标签属性 * @param string $content 标签内容 - * @param boolean $isFile 是否文件方式 - * @param string $type 类型 * @return string */ - public function _import($tag, $content, $isFile = false) + public function tagLoad($tag, $content) { $file = isset($tag['file']) ? $tag['file'] : $tag['href']; - $type = isset($tag['type']) ? strtolower($tag['type']) : ($isFile ? null : 'js'); + $type = isset($tag['type']) ? strtolower($tag['type']) : ''; $parseStr = ''; $endStr = ''; // 判断是否存在加载条件 允许使用函数判断(默认为isset) @@ -505,58 +502,26 @@ class Cx extends Taglib $parseStr .= ''; $endStr = ''; } - if ($isFile) { - // 文件方式导入 - $array = explode(',', $file); - foreach ($array as $val) { - if (!$type || isset($reset)) { - $type = $reset = strtolower(substr(strrchr($val, '.'), 1)); - } - switch ($type) { - case 'js': - $parseStr .= ''; - break; - case 'css': - $parseStr .= ''; - break; - case 'php': - $parseStr .= ''; - break; - } - } - } else { - // 命名空间导入模式 - $basepath = !empty($tag['basepath']) ? $tag['basepath'] : '/public'; - // 命名空间方式导入外部文件 - $array = explode(',', $file); - foreach ($array as $val) { - if (strpos($val, '?')) { - list($val, $version) = explode('?', $val); - } else { - $version = ''; - } - switch ($type) { - case 'js': - $parseStr .= ''; - break; - case 'css': - $parseStr .= ''; - break; - case 'php': - $parseStr .= ''; - break; - } + + // 文件方式导入 + $array = explode(',', $file); + foreach ($array as $val) { + $type = $reset = strtolower(substr(strrchr($val, '.'), 1)); + switch ($type) { + case 'js': + $parseStr .= ''; + break; + case 'css': + $parseStr .= ''; + break; + case 'php': + $parseStr .= ''; + break; } } return $parseStr . $endStr; } - // import别名 采用文件方式加载(要使用命名空间必须用import) 例如 - public function _load($tag, $content) - { - return $this->_import($tag, $content, true); - } - /** * assign标签解析 * 在模板中给某个变量赋值 支持变量赋值 @@ -566,7 +531,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _assign($tag, $content) + public function tagAssign($tag, $content) { $name = $this->autoBuildVar($tag['name']); $flag = substr($tag['value'], 0, 1); @@ -588,7 +553,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _define($tag, $content) + public function tagDefine($tag, $content) { $name = '\'' . $tag['name'] . '\''; $flag = substr($tag['value'], 0, 1); @@ -612,7 +577,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _for($tag, $content) + public function tagFor($tag, $content) { //设置默认值 $start = 0; @@ -663,7 +628,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _url($tag, $content) + public function tagUrl($tag, $content) { $url = isset($tag['link']) ? $tag['link'] : ''; $vars = isset($tag['vars']) ? $tag['vars'] : ''; @@ -689,7 +654,7 @@ class Cx extends Taglib * @param string $content 标签内容 * @return string */ - public function _function($tag, $content) + public function tagFunction($tag, $content) { $name = !empty($tag['name']) ? $tag['name'] : 'func'; $vars = !empty($tag['vars']) ? $tag['vars'] : ''; From 588a4a5bd4af59c0b9ee9a10fa1deeabfc9b7da9 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 23 Jun 2016 18:48:19 +0800 Subject: [PATCH 499/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../library/think/template/taglib/cxTest.php | 27 ------------------- 1 file changed, 27 deletions(-) diff --git a/tests/thinkphp/library/think/template/taglib/cxTest.php b/tests/thinkphp/library/think/template/taglib/cxTest.php index 4a94410c..5e239cbe 100644 --- a/tests/thinkphp/library/think/template/taglib/cxTest.php +++ b/tests/thinkphp/library/think/template/taglib/cxTest.php @@ -447,33 +447,6 @@ EOF; $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); - $content = << Date: Thu, 23 Jun 2016 19:08:57 +0800 Subject: [PATCH 500/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E6=A0=87=E7=AD=BE?= =?UTF-8?q?=E5=BA=93=E7=9A=84=E4=B8=8D=E5=8C=BA=E5=88=86=E5=A4=A7=E5=B0=8F?= =?UTF-8?q?=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/template/TagLib.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/think/template/TagLib.php b/library/think/template/TagLib.php index 54e09da3..7e95c463 100644 --- a/library/think/template/TagLib.php +++ b/library/think/template/TagLib.php @@ -87,7 +87,7 @@ class TagLib public function parseTag(&$content, $lib = '') { $tags = []; - $_lib = $lib ? $lib . ':' : ''; + $_lib = $lib ? strtolower($lib) . ':' : ''; foreach ($this->tags as $name => $val) { $close = !isset($val['close']) || $val['close'] ? 1 : 0; $tags[$close][$_lib . $name] = $name; @@ -108,7 +108,7 @@ class TagLib $right = []; foreach ($matches as $match) { if ('' == $match[1][0]) { - $name = $match[2][0]; + $name = strtolower($match[2][0]); // 如果有没闭合的标签头则取出最后一个 if (!empty($right[$name])) { // $match[0][1]为标签结束符在模板中的位置 @@ -172,7 +172,7 @@ class TagLib $regex = $this->getRegex(array_keys($tags[0]), 0); $content = preg_replace_callback($regex, function ($matches) use (&$tags, &$_lib) { // 对应的标签名 - $name = $tags[0][$matches[1]]; + $name = $tags[0][strtolower($matches[1])]; $alias = $_lib . $name != $matches[1] ? ($_lib ? strstr($matches[1], $_lib) : $matches[1]) : ''; // 解析标签属性 $attrs = $this->parseAttr($matches[0], $name, $alias); From 689c4aa4ead72b4367b1e545aebe527a761e085d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 23 Jun 2016 19:21:49 +0800 Subject: [PATCH 501/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E6=A0=87=E7=AD=BE?= =?UTF-8?q?=E5=BA=93=E8=A7=A3=E6=9E=90=E4=B8=80=E5=A4=84=E5=8F=AF=E8=83=BD?= =?UTF-8?q?=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/template/TagLib.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/library/think/template/TagLib.php b/library/think/template/TagLib.php index 7e95c463..8c506361 100644 --- a/library/think/template/TagLib.php +++ b/library/think/template/TagLib.php @@ -286,6 +286,9 @@ class TagLib */ public function parseCondition($condition) { + 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: 此句能解析表达式中用|分隔的函数,但表达式中如果有|、||这样的逻辑运算就产生了歧异 From 0c63b2a172efda43d495554e1002942c552f5351 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 23 Jun 2016 22:38:21 +0800 Subject: [PATCH 502/670] =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=88=86=E7=BB=84MIS?= =?UTF-8?q?S=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 42 +++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index b484a4f7..676263e0 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -497,11 +497,12 @@ class Route * @param string $route 路由地址 * @param string $method 请求类型 * @param array $option 路由参数 + * @param string $group 路由分组 * @return void */ - public static function miss($route, $method = '*', $option = []) + public static function miss($route, $method = '*', $option = [], $group = '') { - self::rule('__miss__', $route, $method, $option, []); + self::rule('__miss__', $route, $method, $option, [], $group); } /** @@ -678,11 +679,6 @@ class Route // 路由规则检测 if (!empty($rules)) { - if (isset($rules['__miss__'])) { - // 指定未匹配路由的处理 - $miss = $rules['__miss__']; - unset($rules['__miss__']); - } foreach ($rules as $rule => $val) { $option = isset($val['option']) ? $val['option'] : []; $pattern = isset($val['pattern']) ? $val['pattern'] : []; @@ -691,7 +687,11 @@ class Route if (!self::checkOption($option, $url, $request)) { continue; } - + if ('__miss__' == $rule) { + // 指定分组MISS路由 + $miss = $val['route']; + continue; + } if (!empty($val['routes'])) { // 分组路由 if (($pos = strpos($rule, ':')) || ($pos = strpos($rule, '<'))) { @@ -702,13 +702,12 @@ class Route if (0 !== strpos($url, $str)) { continue; } + $missGroup = false; // 匹配到路由分组 foreach ($val['routes'] as $key => $route) { if (is_numeric($key)) { $key = array_shift($route); } - - $key = $rule . ($key ? '/' . ltrim($key, '/') : ''); // 检查规则路由 if (is_array($route)) { $option1 = $route[1]; @@ -720,12 +719,27 @@ class Route $route = $route[0]; $option = array_merge($option, $option1); } + if ('__miss__' == $key) { + // 指定分组MISS路由 + $missGroup = $route; + continue; + } + $key = $rule . ($key ? '/' . ltrim($key, '/') : ''); $result = self::checkRule($key, $route, $url, $pattern, $option); if (false !== $result) { $request->route(['rule' => $key, 'route' => $route, 'pattern' => $pattern, 'option' => $option]); return $result; } } + if ($missGroup) { + // 未匹配所有路由的路由规则处理 + if ($missGroup instanceof \Closure) { + // 执行闭包 + return ['type' => 'function', 'function' => $missGroup, 'params' => []]; + } else { + return self::parseRule('', $missGroup, $url, []); + } + } } else { if (is_numeric($rule)) { $rule = array_shift($val); @@ -742,11 +756,11 @@ class Route } if (isset($miss)) { // 未匹配所有路由的路由规则处理 - if ($miss['route'] instanceof \Closure) { + if ($miss instanceof \Closure) { // 执行闭包 - return ['type' => 'function', 'function' => $miss['route'], 'params' => []]; - } elseif (self::checkOption($miss['option'], $url, $request)) { - return self::parseRule('', $miss['route'], $url, []); + return ['type' => 'function', 'function' => $miss, 'params' => []]; + } else { + return self::parseRule('', $miss, $url, []); } } } From 1a8bbf67252870e17c5951a122e0fa9a90a846e8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 24 Jun 2016 11:09:26 +0800 Subject: [PATCH 503/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BTagLib=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/template/TagLib.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/library/think/template/TagLib.php b/library/think/template/TagLib.php index 8c506361..b0e40f57 100644 --- a/library/think/template/TagLib.php +++ b/library/think/template/TagLib.php @@ -87,15 +87,15 @@ class TagLib public function parseTag(&$content, $lib = '') { $tags = []; - $_lib = $lib ? strtolower($lib) . ':' : ''; + $lib = $lib ? strtolower($lib) . ':' : ''; foreach ($this->tags as $name => $val) { - $close = !isset($val['close']) || $val['close'] ? 1 : 0; - $tags[$close][$_lib . $name] = $name; + $close = !isset($val['close']) || $val['close'] ? 1 : 0; + $tags[$close][$lib . $name] = $name; if (isset($val['alias'])) { // 别名设置 $array = (array) $val['alias']; foreach (explode(',', $array[0]) as $v) { - $tags[$close][$_lib . $v] = $name; + $tags[$close][$lib . $v] = $name; } } } @@ -120,7 +120,7 @@ class TagLib } } else { // 标签头压入栈 - $right[$match[1][0]][] = $match[0]; + $right[strtolower($match[1][0])][] = $match[0]; } } unset($right, $matches); @@ -135,7 +135,7 @@ class TagLib foreach ($nodes as $pos => $node) { // 对应的标签名 $name = $tags[1][$node['name']]; - $alias = $_lib . $name != $node['name'] ? ($_lib ? strstr($node['name'], $_lib) : $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; @@ -170,10 +170,10 @@ class TagLib // 自闭合标签 if (!empty($tags[0])) { $regex = $this->getRegex(array_keys($tags[0]), 0); - $content = preg_replace_callback($regex, function ($matches) use (&$tags, &$_lib) { + $content = preg_replace_callback($regex, function ($matches) use (&$tags, &$lib) { // 对应的标签名 $name = $tags[0][strtolower($matches[1])]; - $alias = $_lib . $name != $matches[1] ? ($_lib ? strstr($matches[1], $_lib) : $matches[1]) : ''; + $alias = $lib . $name != $matches[1] ? ($lib ? strstr($matches[1], $lib) : $matches[1]) : ''; // 解析标签属性 $attrs = $this->parseAttr($matches[0], $name, $alias); $method = 'tag' . $name; From 87ad5e95bb16e0843c8e786b9ec029c34f38ae15 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 24 Jun 2016 12:33:07 +0800 Subject: [PATCH 504/670] =?UTF-8?q?Route=E7=B1=BB=E7=9A=84bind=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E5=8F=82=E6=95=B0=E9=A1=BA=E5=BA=8F=E8=B0=83=E6=95=B4?= =?UTF-8?q?=20=E5=A2=9E=E5=8A=A0getBind=E6=96=B9=E6=B3=95=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E8=8E=B7=E5=8F=96=E7=BB=91=E5=AE=9A=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 39 +++++++------- library/think/Route.php | 23 ++++++--- library/think/Url.php | 4 +- library/think/template/taglib/Cx.php | 2 +- tests/thinkphp/library/think/routeTest.php | 60 +++++++++++----------- 5 files changed, 67 insertions(+), 61 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 78989242..0bc19a86 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -41,27 +41,27 @@ class App /** * @var bool 应用调试模式 - */ + */ public static $debug = true; /** * @var string 应用类库命名空间 - */ + */ public static $namespace = 'app'; /** * @var bool 应用类库后缀 - */ + */ public static $suffix = false; /** * @var bool 应用路由检测 - */ + */ protected static $routeCheck; /** * @var bool 严格路由检测 - */ + */ protected static $routeMust; /** @@ -108,7 +108,7 @@ class App break; case 'module': // 模块/控制器/操作 - $data = self::module($dispatch['module'], $config, isset($dispatch['convert']) ? $dispatch['convert'] : null ); + $data = self::module($dispatch['module'], $config, isset($dispatch['convert']) ? $dispatch['convert'] : null); break; case 'controller': // 执行控制器操作 @@ -136,11 +136,11 @@ class App Hook::listen('app_end', $data); // 清空类的实例化 Loader::clearInstance(); - + // 输出数据到客户端 if ($data instanceof Response) { return $data; - } elseif(!is_null($data)) { + } elseif (!is_null($data)) { // 默认自动识别响应输出类型 $isAjax = $request->isAjax(); $type = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type'); @@ -222,7 +222,7 @@ class App } } // 全局过滤 - array_walk_recursive($args, [Request::instance(),'filterExp']); + array_walk_recursive($args, [Request::instance(), 'filterExp']); } return $args; } @@ -243,7 +243,7 @@ class App if ($config['app_multi_module']) { // 多模块部署 $module = strip_tags(strtolower($result[0] ?: $config['default_module'])); - $bind = Route::bind('module'); + $bind = Route::getBind('module'); $available = false; if ($bind) { // 绑定模块 @@ -270,7 +270,7 @@ class App App::$modulePath = APP_PATH . ($module ? $module . DS : ''); // 是否自动转换控制器和操作名 - $convert = is_bool($convert) ? $convert : $config['url_convert']; + $convert = is_bool($convert) ? $convert : $config['url_convert']; // 获取控制器名 $controller = strip_tags($result[1] ?: $config['default_controller']); $controller = $convert ? strtolower($controller) : $controller; @@ -327,17 +327,17 @@ class App { if (empty(self::$init)) { // 初始化应用 - $config = self::init(); - self::$suffix = $config['class_suffix']; - + $config = self::init(); + self::$suffix = $config['class_suffix']; + // 应用调试模式 - self::$debug = Config::get('app_debug'); + self::$debug = Config::get('app_debug'); if (!self::$debug) { ini_set('display_errors', 'Off'); } - + // 应用命名空间 - self::$namespace = $config['app_namespace']; + self::$namespace = $config['app_namespace']; Loader::addNamespace($config['app_namespace'], APP_PATH); if (!empty($config['root_namespace'])) { Loader::addNamespace($config['root_namespace']); @@ -364,7 +364,6 @@ class App return self::$init; } - /** * 初始化应用或模块 * @access public @@ -432,14 +431,14 @@ class App { // 检测URL禁用后缀 if ($config['url_deny_suffix'] && preg_match('/\.(' . $config['url_deny_suffix'] . ')$/i', $request->pathinfo())) { - throw new Exception('url suffix deny:'.$request->ext()); + throw new Exception('url suffix deny:' . $request->ext()); } $path = $request->path(); $depr = $config['pathinfo_depr']; $result = false; // 路由检测 - $check = !is_null(self::$routeCheck) ? self::$routeCheck : $config['url_route_on']; + $check = !is_null(self::$routeCheck) ? self::$routeCheck : $config['url_route_on']; if ($check) { // 开启路由 if (!empty($config['route'])) { diff --git a/library/think/Route.php b/library/think/Route.php index 676263e0..e5711c33 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -123,19 +123,26 @@ class Route } /** - * 设置和读取路由绑定 + * 设置路由绑定 * @access public - * @param string $type 请求类型 * @param mixed $bind 绑定信息 + * @param string $type 绑定类型 默认为module * @return mixed */ - public static function bind($type, $bind = '') + public static function bind($bind, $type = 'module') { - if ('' == $bind) { - return isset(self::$bind[$type]) ? self::$bind[$type] : null; - } else { - self::$bind = ['type' => $type, $type => $bind]; - } + self::$bind = ['type' => $type, $type => $bind]; + } + + /** + * 读取路由绑定 + * @access public + * @param string $type 绑定类型 + * @return mixed + */ + public static function getBind($type) + { + return isset(self::$bind[$type]) ? self::$bind[$type] : null; } /** diff --git a/library/think/Url.php b/library/think/Url.php index 9a840b50..6c938c04 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -78,9 +78,9 @@ class Url } // 检测URL绑定 - $type = Route::bind('type'); + $type = Route::getBind('type'); if ($type) { - $bind = Route::bind($type); + $bind = Route::getBind($type); if (0 === strpos($url, $bind)) { $url = substr($url, strlen($bind) + 1); } diff --git a/library/think/template/taglib/Cx.php b/library/think/template/taglib/Cx.php index 021178b3..7336db86 100644 --- a/library/think/template/taglib/Cx.php +++ b/library/think/template/taglib/Cx.php @@ -506,7 +506,7 @@ class Cx extends Taglib // 文件方式导入 $array = explode(',', $file); foreach ($array as $val) { - $type = $reset = strtolower(substr(strrchr($val, '.'), 1)); + $type = strtolower(substr(strrchr($val, '.'), 1)); switch ($type) { case 'js': $parseStr .= ''; diff --git a/tests/thinkphp/library/think/routeTest.php b/tests/thinkphp/library/think/routeTest.php index 1ebc89d6..751486f0 100644 --- a/tests/thinkphp/library/think/routeTest.php +++ b/tests/thinkphp/library/think/routeTest.php @@ -16,18 +16,18 @@ namespace tests\thinkphp\library\think; +use think\Config; use think\Request; use think\Route; -use think\Config; class routeTest extends \PHPUnit_Framework_TestCase { protected function setUp() { - Config::set('app_multi_module',true); + Config::set('app_multi_module', true); } - + public function testRegister() { $request = Request::instance(); @@ -48,19 +48,19 @@ class routeTest extends \PHPUnit_Framework_TestCase $request = Request::instance(); Route::resource('res', 'index/blog'); Route::resource(['res' => ['index/blog']]); - $result = Route::check($request, 'res'); + $result = Route::check($request, 'res'); $this->assertEquals(['index', 'blog', 'index'], $result['module']); - $result = Route::check($request, 'res/create'); + $result = Route::check($request, 'res/create'); $this->assertEquals(['index', 'blog', 'create'], $result['module']); - $result = Route::check($request, 'res/8'); + $result = Route::check($request, 'res/8'); $this->assertEquals(['index', 'blog', 'read'], $result['module']); - $result = Route::check($request, 'res/8/edit'); + $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'); + $result = Route::check($request, 'blog/8/comment/10'); $this->assertEquals(['index', 'comment', 'read'], $result['module']); - $result = Route::check($request, 'blog/8/comment/10/edit'); + $result = Route::check($request, 'blog/8/comment/10/edit'); $this->assertEquals(['index', 'comment', 'edit'], $result['module']); } @@ -83,7 +83,7 @@ class routeTest extends \PHPUnit_Framework_TestCase $request = Request::instance(); Route::map('hello', 'index/hello'); $this->assertEquals('index/hello', Route::map('hello')); - $result = Route::check($request, 'hello'); + $result = Route::check($request, 'hello'); $this->assertEquals(['index', 'hello', null], $result['module']); } @@ -91,13 +91,13 @@ class routeTest extends \PHPUnit_Framework_TestCase { $request = Request::instance(); Route::get('hello-', 'index/hello', [], ['name' => '\w+']); - $result = Route::check($request, 'hello-thinkphp'); + $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'); + $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'); + $result = Route::check($request, 'hello-thinkphp/2016'); $this->assertEquals([null, 'index', 'hello'], $result['module']); } @@ -124,9 +124,9 @@ class routeTest extends \PHPUnit_Framework_TestCase $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'); + $result = Route::check($request, 'blog/5'); $this->assertEquals([null, 'blog', 'read'], $result['module']); - $result = Route::check($request, 'hello/thinkphp/abc/test'); + $result = Route::check($request, 'hello/thinkphp/abc/test'); $this->assertEquals([null, 'index', 'hello'], $result['module']); } @@ -136,11 +136,11 @@ class routeTest extends \PHPUnit_Framework_TestCase Route::pattern(['id' => '\d+', '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'); + $result = Route::check($request, 'group/think'); $this->assertEquals([null, 'index', 'say'], $result['module']); - $result = Route::check($request, 'group/10'); + $result = Route::check($request, 'group/10'); $this->assertEquals([null, 'index', 'hello'], $result['module']); - $result = Route::check($request, 'group/thinkphp'); + $result = Route::check($request, 'group/thinkphp'); $this->assertEquals([null, 'index', 'say'], $result['module']); } @@ -151,9 +151,9 @@ class routeTest extends \PHPUnit_Framework_TestCase 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'); + $result = Route::check($request, 'hello/thinkphp'); $this->assertEquals([null, 'index', 'hello'], $result['module']); - $result = Route::check($request, 'blog/5'); + $result = Route::check($request, 'blog/5'); $this->assertEquals([null, 'blog', 'read'], $result['module']); } @@ -183,18 +183,18 @@ class routeTest extends \PHPUnit_Framework_TestCase public function testBind() { $request = Request::instance(); - Route::bind('module', 'index/blog'); - $result = Route::parseUrl('read/10'); + Route::bind('index/blog'); + $result = Route::parseUrl('read/10'); $this->assertEquals(['index', 'blog', 'read'], $result['module']); Route::get('index/blog/:id', 'index/blog/read'); - $result = Route::check($request, '10'); + $result = Route::check($request, '10'); $this->assertEquals(['index', 'blog', 'read'], $result['module']); - Route::bind('namespace', '\app\index\controller'); + Route::bind('\app\index\controller', 'namespace'); $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check($request, 'blog/read')); - Route::bind('class', '\app\index\controller\blog'); + Route::bind('\app\index\controller\blog', 'class'); $this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\blog', 'read'], 'params' => []], Route::check($request, 'read')); } @@ -204,24 +204,24 @@ class routeTest extends \PHPUnit_Framework_TestCase Route::domain('subdomain.thinkphp.cn', 'sub?abc=test&status=1'); Route::checkDomain($request); $this->assertEquals('sub?abc=test&status=1', Route::domain('subdomain.thinkphp.cn')); - $this->assertEquals('sub', Route::bind('module')); + $this->assertEquals('sub', Route::getbind('module')); $this->assertEquals('test', $_GET['abc']); $this->assertEquals(1, $_GET['status']); Route::domain('subdomain.thinkphp.cn', function () {return ['type' => 'module', 'module' => 'sub2'];}); Route::checkDomain($request); - $this->assertEquals('sub2', Route::bind('module')); + $this->assertEquals('sub2', Route::getbind('module')); Route::domain('subdomain.thinkphp.cn', '\app\index\controller'); Route::checkDomain($request); - $this->assertEquals('\app\index\controller', Route::bind('namespace')); + $this->assertEquals('\app\index\controller', Route::getbind('namespace')); Route::domain('subdomain.thinkphp.cn', '@\app\index\controller\blog'); Route::checkDomain($request); - $this->assertEquals('\app\index\controller\blog', Route::bind('class')); + $this->assertEquals('\app\index\controller\blog', Route::getbind('class')); Route::domain('subdomain.thinkphp.cn', '[sub3]'); Route::checkDomain($request); - $this->assertEquals('sub3', Route::bind('group')); + $this->assertEquals('sub3', Route::getbind('group')); } } From 75f855757b06030263c9f1df73eb4b740214585c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 24 Jun 2016 14:59:18 +0800 Subject: [PATCH 505/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BApp=E7=9A=84=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 0bc19a86..e2632e68 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -240,6 +240,7 @@ class App if (is_string($result)) { $result = explode('/', $result); } + $request = Request::instance(); if ($config['app_multi_module']) { // 多模块部署 $module = strip_tags(strtolower($result[0] ?: $config['default_module'])); @@ -258,6 +259,7 @@ class App // 模块初始化 if ($module && $available) { // 初始化模块 + $request->module($module); $config = self::init($module); } else { throw new HttpException(404, 'module not exists:' . $module); @@ -265,6 +267,7 @@ class App } else { // 单一模块部署 $module = ''; + $request->module($module); } // 当前模块路径 App::$modulePath = APP_PATH . ($module ? $module . DS : ''); @@ -285,9 +288,8 @@ class App throw new \InvalidArgumentException('illegal controller name:' . $controller); } - // 设置当前请求的模块、控制器、操作 - $request = Request::instance(); - $request->module($module)->controller($controller)->action($actionName); + // 设置当前请求的控制器、操作 + $request->controller($controller)->action($actionName); // 监听module_init Hook::listen('module_init', $request); From 1e21d9af34cdd7fd68291217afb6c8ba2e6273cf Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 24 Jun 2016 17:13:31 +0800 Subject: [PATCH 506/670] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E5=99=A8=E5=90=8D=E7=9A=84=E6=A3=80=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 6 ------ 1 file changed, 6 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index e2632e68..8a46c4fb 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -282,12 +282,6 @@ class App $actionName = strip_tags($result[2] ?: $config['default_action']); $actionName = $convert ? strtolower($actionName) : $actionName; - // 执行操作 - if (!preg_match('/^[A-Za-z](\/|\.|\w)*$/', $controller)) { - // 安全检测 - throw new \InvalidArgumentException('illegal controller name:' . $controller); - } - // 设置当前请求的控制器、操作 $request->controller($controller)->action($actionName); From 73f1ae289d6538b86c903c841ce22d5c30bb8fc4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 24 Jun 2016 17:30:47 +0800 Subject: [PATCH 507/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRequest=E7=B1=BB?= =?UTF-8?q?=E7=9A=84dispatch=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index 39981afe..4b83c3b1 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -1296,13 +1296,16 @@ class Request /** * 获取当前请求的调度信息 * @access public - * @param array $dispatch 调度信息 + * @param array|string $dispatch 调度信息 + * @param string $type 调度类型 * @return array */ - public function dispatch($dispatch = []) + public function dispatch($dispatch = null, $type = null, $params = []) { - if (!empty($dispatch)) { - $this->dispatch = $dispatch; + if (!is_null($dispatch)) { + $this->dispatch = is_array($dispatch) ? + $dispatch : + ['type' => $type, $type => $dispatch, 'params' => $param]; } return $this->dispatch; } From d3d7fdb83dd87b6ef0f79226db3746cd8b146f45 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 24 Jun 2016 17:31:58 +0800 Subject: [PATCH 508/670] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index 4b83c3b1..b6ef5c7f 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -1294,10 +1294,11 @@ class Request } /** - * 获取当前请求的调度信息 + * 设置或者获取当前请求的调度信息 * @access public * @param array|string $dispatch 调度信息 * @param string $type 调度类型 + * @param array $params 参数 * @return array */ public function dispatch($dispatch = null, $type = null, $params = []) From 2839d9b31d88c755bd6fe4570bf1c402e026248d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 24 Jun 2016 17:40:36 +0800 Subject: [PATCH 509/670] =?UTF-8?q?Request=E7=B1=BBdispatch=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/library/think/Request.php b/library/think/Request.php index b6ef5c7f..a88c70c3 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -1301,12 +1301,10 @@ class Request * @param array $params 参数 * @return array */ - public function dispatch($dispatch = null, $type = null, $params = []) + public function dispatch($dispatch = null, $type = 'module', $params = []) { if (!is_null($dispatch)) { - $this->dispatch = is_array($dispatch) ? - $dispatch : - ['type' => $type, $type => $dispatch, 'params' => $param]; + $this->dispatch = ['type' => $type, $type => $dispatch, 'params' => $param]; } return $this->dispatch; } From c4ef774882e244a86d4d5aeea8cb39efd7fe67f7 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 24 Jun 2016 17:45:27 +0800 Subject: [PATCH 510/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Request.php b/library/think/Request.php index a88c70c3..493f7ad9 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -1304,7 +1304,7 @@ class Request public function dispatch($dispatch = null, $type = 'module', $params = []) { if (!is_null($dispatch)) { - $this->dispatch = ['type' => $type, $type => $dispatch, 'params' => $param]; + $this->dispatch = ['type' => $type, $type => $dispatch, 'params' => $params]; } return $this->dispatch; } From 7f13d70d0b4eb5cb813fe1b38dd637119ede262d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Fri, 24 Jun 2016 23:41:02 +0800 Subject: [PATCH 511/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BApp=E7=B1=BB=E5=92=8C?= =?UTF-8?q?Request=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 25 ++++++++++++++++++++----- library/think/Request.php | 8 +++----- library/think/db/builder/Sqlsrv.php | 11 ++++++----- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 8a46c4fb..2ebf6d52 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -64,6 +64,8 @@ class App */ protected static $routeMust; + protected static $dispatch; + /** * 执行应用程序 * @access public @@ -90,12 +92,14 @@ class App } } - // 获取当前请求的调度信息 - $dispatch = $request->dispatch(); + // 获取应用调度信息 + $dispatch = self::$dispatch; if (empty($dispatch)) { // 未指定调度类型 则进行URL路由检测 $dispatch = self::routeCheck($request, $config); } + // 记录当前调度信息 + $request->dispatch($dispatch); // 记录路由信息 self::$debug && Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info'); // 监听app_begin @@ -150,6 +154,19 @@ class App } } + /** + * 设置当前请求的调度信息 + * @access public + * @param array|string $dispatch 调度信息 + * @param string $type 调度类型 + * @param array $params 参数 + * @return void + */ + public static function dispatch($dispath, $type = 'module', $params = []) + { + self::$dispatch = ['type' => $type, $type => $dispatch, 'params' => $params]; + } + /** * 执行函数或者闭包方法 支持参数调用 * @access public @@ -453,9 +470,7 @@ class App // 路由无效 解析模块/控制器/操作/参数... 支持控制器自动搜索 $result = Route::parseUrl($path, $depr, $config['controller_auto_search'], $config['url_param_type']); } - - // 注册调度机制 - return $request->dispatch($result); + return $result; } /** diff --git a/library/think/Request.php b/library/think/Request.php index 493f7ad9..8d5e9ad4 100644 --- a/library/think/Request.php +++ b/library/think/Request.php @@ -1296,15 +1296,13 @@ class Request /** * 设置或者获取当前请求的调度信息 * @access public - * @param array|string $dispatch 调度信息 - * @param string $type 调度类型 - * @param array $params 参数 + * @param array $dispatch 调度信息 * @return array */ - public function dispatch($dispatch = null, $type = 'module', $params = []) + public function dispatch($dispatch = null) { if (!is_null($dispatch)) { - $this->dispatch = ['type' => $type, $type => $dispatch, 'params' => $params]; + $this->dispatch = $dispatch; } return $this->dispatch; } diff --git a/library/think/db/builder/Sqlsrv.php b/library/think/db/builder/Sqlsrv.php index 4010fe3c..8cc0f324 100644 --- a/library/think/db/builder/Sqlsrv.php +++ b/library/think/db/builder/Sqlsrv.php @@ -18,10 +18,10 @@ use think\db\Builder; */ 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 $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% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; - protected $deleteSql = 'DELETE FROM %TABLE% %USING% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; + protected $updateSql = 'UPDATE %TABLE% SET %SET% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; + protected $deleteSql = 'DELETE FROM %TABLE% %USING% %JOIN% %WHERE% %LIMIT% %LOCK%%COMMENT%'; /** * order分析 @@ -79,9 +79,10 @@ class Sqlsrv extends Builder } return 'WHERE ' . $limitStr; } - public function selectInsert($fields, $table, $options) + + public function selectInsert($fields, $table, $options) { - $this->selectSql=$this->selectInsertSql; + $this->selectSql = $this->selectInsertSql; return parent::selectInsert($fields, $table, $options); } From f58aeede7ac3a76a6bbc06d38c8c524c5aed6173 Mon Sep 17 00:00:00 2001 From: WeakSun Date: Sat, 25 Jun 2016 13:30:43 +0800 Subject: [PATCH 512/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3scope=E6=96=B9?= =?UTF-8?q?=E6=B3=95$name=E5=8F=82=E6=95=B0=E4=BC=A0=E5=85=A5array?= =?UTF-8?q?=E5=BC=95=E8=B5=B7$names=E5=8F=98=E9=87=8F=E4=B8=8D=E5=AD=98?= =?UTF-8?q?=E5=9C=A8=E7=9A=84=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1.修正$name为array类型时的BUG 2.范围方法调用支持多参数传入 --- library/think/Model.php | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 450675dc..de4b4db6 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -978,25 +978,27 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * 命名范围 * @access public * @param string|array|Closure $name 命名范围名称 逗号分隔 - * @param mixed $params 参数调用 + * @param mixed ...$params 参数调用 * @return Model */ - public static function scope($name, $params = []) + public static function scope($name) { - $model = new static(); - $query = $model->db(); - if ($name instanceof \Closure) { - call_user_func_array($name, [ & $query, $params]); - } elseif ($name instanceof Query) { + if ($name instanceof Query) { return $name; - } else { - if (is_string($name)) { - $names = explode(',', $name); - } - foreach ($names as $scope) { + } + $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)) { - $model->$method($query, $params); + call_user_func_array([$model, $method], $params); } } } From f80e82f491595bc8d82414865f0dbc0d529ec83b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 25 Jun 2016 18:11:24 +0800 Subject: [PATCH 513/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BURL=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=20=E4=BF=9D=E7=95=99=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E5=90=8D=E7=A7=B0=E5=A4=A7=E5=B0=8F=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Route.php b/library/think/Route.php index e5711c33..47f9449d 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -1212,7 +1212,7 @@ class Route $var += explode('/', $url); } else { preg_replace_callback('/(\w+)\/([^\/]+)/', function ($match) use (&$var) { - $var[strtolower($match[1])] = strip_tags($match[2]); + $var[$match[1]] = strip_tags($match[2]); }, $url); } } From 5cc58747303830b78acae040630c350ce1ae8d17 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 26 Jun 2016 12:05:31 +0800 Subject: [PATCH 514/670] =?UTF-8?q?Model=E7=B1=BB=E7=9A=84allowField?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E6=94=AF=E6=8C=81=E4=BC=A0=E5=85=A5true=20?= =?UTF-8?q?=E8=A1=A8=E7=A4=BA=E5=8F=AA=E5=85=81=E8=AE=B8=E5=86=99=E5=85=A5?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E8=A1=A8=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/Model.php b/library/think/Model.php index 450675dc..ea1738a2 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -556,6 +556,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // 检测字段 if (!empty($this->field)) { + if (true === $this->field) { + $this->field = $this->db->getTableInfo('', 'fields'); + } foreach ($this->data as $key => $val) { if (!in_array($key, $this->field)) { unset($this->data[$key]); @@ -673,7 +676,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * 设置允许写入的字段 * @access public - * @param bool $update + * @param bool|array $field 允许写入的字段 如果为true只允许写入数据表字段 * @return $this */ public function allowField($field) From 5fee111484e705f35da96063ebc51e65c41222c3 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 26 Jun 2016 23:31:53 +0800 Subject: [PATCH 515/670] =?UTF-8?q?IS=5FAPI=20=E4=B8=8B=E9=9D=A2=E4=B8=8D?= =?UTF-8?q?=E9=80=9A=E8=BF=87=E8=B7=AF=E7=94=B1=E8=A7=A3=E6=9E=90=20?= =?UTF-8?q?=E7=9B=B4=E6=8E=A5=E8=A7=A3=E6=9E=90=E5=88=B0API=E7=B1=BB?= =?UTF-8?q?=E6=89=80=E5=9C=A8=E7=9A=84=E5=91=BD=E5=90=8D=E7=A9=BA=E9=97=B4?= =?UTF-8?q?=20Route=E7=B1=BB=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 2 ++ library/think/App.php | 11 ++++++-- library/think/Route.php | 61 +++++++++++++++++++++++++++++------------ 3 files changed, 54 insertions(+), 20 deletions(-) diff --git a/convention.php b/convention.php index eca9e883..a95b6b50 100644 --- a/convention.php +++ b/convention.php @@ -93,6 +93,8 @@ return [ 'url_controller_layer' => 'controller', // 表单请求类型伪装变量 'var_method' => '_method', + // URL解析方式 module controller class namespace + 'url_parse_type' => 'module', // +---------------------------------------------------------------------- // | 模板引擎设置 diff --git a/library/think/App.php b/library/think/App.php index 2ebf6d52..d4c40b09 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -95,8 +95,13 @@ class App // 获取应用调度信息 $dispatch = self::$dispatch; if (empty($dispatch)) { - // 未指定调度类型 则进行URL路由检测 - $dispatch = self::routeCheck($request, $config); + if (IS_API) { + // 直接绑定到控制器类命名空间 URL区分大小写 v1/User/getInfo + $dispatch = Route::bindToApi($request->path(), self::$namespace, $config['pathinfo_depr']); + } else { + // 进行URL路由检测 + $dispatch = self::routeCheck($request, $config); + } } // 记录当前调度信息 $request->dispatch($dispatch); @@ -468,7 +473,7 @@ class App } if (false === $result) { // 路由无效 解析模块/控制器/操作/参数... 支持控制器自动搜索 - $result = Route::parseUrl($path, $depr, $config['controller_auto_search'], $config['url_param_type']); + $result = Route::parseUrl($path, $depr, $config['controller_auto_search'], $config['url_param_type'], $config['url_parse_type']); } return $result; } diff --git a/library/think/Route.php b/library/think/Route.php index 47f9449d..59ee4bdd 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -656,13 +656,13 @@ class Route // 路由不匹配 } elseif (0 === strpos($rule, '\\')) { // 路由到类 - return self::bindToClass($array[1], substr($rule, 1)); + return self::bindToClass($array[1], substr($rule, 1), $depr); } elseif (0 === strpos($url, '@')) { // 路由到控制器类 - return self::bindToController($array[1], substr($rule, 1)); + return self::bindToController($array[1], substr($rule, 1), $depr); } else { // 路由到模块/控制器 - return self::bindToModule($array[1], $rule); + return self::bindToModule($array[1], $rule, $depr); } } @@ -679,7 +679,7 @@ class Route self::checkDomain($request); } // 检测URL绑定 - $return = self::checkUrlBind($url, $rules); + $return = self::checkUrlBind($url, $rules, $depr); if ($return) { return $return; } @@ -779,9 +779,10 @@ class Route * @access private * @param string $url URL地址 * @param array $rules 路由规则 + * @param string $depr URL分隔符 * @return false */ - private static function checkUrlBind(&$url, &$rules) + private static function checkUrlBind(&$url, &$rules, $depr = '/') { if (!empty(self::$bind['type'])) { // 记录绑定信息 @@ -790,10 +791,10 @@ class Route switch (self::$bind['type']) { case 'class': // 绑定到类 - return self::bindToClass($url, self::$bind['class']); + return self::bindToClass($url, self::$bind['class'], $depr); case 'namespace': // 绑定到命名空间 - return self::bindToNamespace($url, self::$bind['namespace']); + return self::bindToNamespace($url, self::$bind['namespace'], $depr); case 'module': // 如果有模块/控制器绑定 针对路由到 模块/控制器 有效 $url = self::$bind['module'] . '/' . $url; @@ -814,11 +815,12 @@ class Route * @access public * @param string $url URL地址 * @param string $class 类名(带命名空间) + * @param string $depr URL分隔符 * @return array */ - public static function bindToClass($url, $class) + public static function bindToClass($url, $class, $depr = '/') { - $array = explode('/', $url, 2); + $array = explode($depr, $url, 2); if (!empty($array[1])) { self::parseUrlParams($array[1]); } @@ -830,11 +832,12 @@ class Route * @access public * @param string $url URL地址 * @param string $namespace 命名空间 + * @param string $depr URL分隔符 * @return array */ - public static function bindToNamespace($url, $namespace) + public static function bindToNamespace($url, $namespace, $depr = '/') { - $array = explode('/', $url, 3); + $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])) { @@ -848,11 +851,12 @@ class Route * @access public * @param string $url URL地址 * @param string $module 模块名 + * @param string $depr URL分隔符 * @return array */ - public static function bindToController($url, $controller) + public static function bindToController($url, $controller, $depr = '/') { - $array = explode('/', $url, 2); + $array = explode($depr, $url, 2); $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); if (!empty($array[1])) { self::parseUrlParams($array[1]); @@ -865,11 +869,12 @@ class Route * @access public * @param string $url URL地址 * @param string $class 控制器类名(带命名空间) + * @param string $depr URL分隔符 * @return array */ - public static function bindToModule($url, $controller) + public static function bindToModule($url, $controller, $depr = '/') { - $array = explode('/', $url, 2); + $array = explode($depr, $url, 2); $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); if (!empty($array[1])) { self::parseUrlParams($array[1]); @@ -877,6 +882,27 @@ class Route return ['type' => 'module', 'module' => $controller . '/' . $action]; } + /** + * 绑定到API + * @access public + * @param string $url URL地址 + * @param string $namespace 命名空间 + * @param string $depr URL分隔符 + * @return array + */ + public static function bindToApi($url, $namespace, $depr = '/') + { + $array = explode($depr, $url, 4); + $module = !empty($array[0]) ? $array[0] : Config::get('default_module'); + $class = !empty($array[1]) ? $array[1] : Config::get('default_controller'); + $method = !empty($array[2]) ? $array[2] : Config::get('default_action'); + $layer = Config::get('url_controller_layer'); + if (!empty($array[3])) { + self::parseUrlParams($array[3]); + } + return ['type' => 'method', 'method' => [$namespace . '\\' . $module . '\\' . $layer . '\\' . $class, $method], 'params' => []]; + } + /** * 路由参数有效性检查 * @access private @@ -976,9 +1002,10 @@ class Route * @param string $depr URL分隔符 * @param bool $autoSearch 是否自动深度搜索控制器 * @param integer $paramType URL参数解析方式 0 名称解析 1 顺序解析 + * @param string $type 路由类型 * @return array */ - public static function parseUrl($url, $depr = '/', $autoSearch = false, $paramType = 0) + public static function parseUrl($url, $depr = '/', $autoSearch = false, $paramType = 0, $type = 'module') { if (isset(self::$bind['module'])) { // 如果有模块/控制器绑定 @@ -994,7 +1021,7 @@ class Route if (!empty($result['var'])) { $_GET = array_merge($result['var'], $_GET); } - return ['type' => 'module', 'module' => $result['route']]; + return ['type' => $type, $type => $result['route']]; } /** From 15577f75ce457ea80ca61182072f8f4b2dc60574 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Mon, 27 Jun 2016 10:53:56 +0800 Subject: [PATCH 516/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3composer=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=8A=A0=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Loader.php | 84 +------------------------- library/think/session/driver/Redis.php | 13 +++- 2 files changed, 11 insertions(+), 86 deletions(-) diff --git a/library/think/Loader.php b/library/think/Loader.php index a63dfe04..00f758dd 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -146,8 +146,8 @@ class Loader // Composer自动加载支持 if (is_dir(VENDOR_PATH . 'composer')) { // 注册Composer自动加载 - self::registerComposerLoader(); self::$composerLoader = true; + self::registerComposerLoader(); } elseif (is_file(VENDOR_PATH . 'think_autoload.php')) { // 读取Composer自动加载文件 $autoload = include VENDOR_PATH . 'think_autoload.php'; @@ -163,88 +163,6 @@ class Loader } } - // 扫描composer package - public static function scanComposerPackage($path) - { - // 自动扫描下载Composer安装类库 - $dirs = scandir($path, 1); - $namespace = $files = $classmap = []; - foreach ($dirs as $dir) { - if ('.' != $dir && '..' != $dir && is_dir($path . $dir) && is_file($path . $dir . DS . 'composer.json')) { - // 解析Composer 包 - $package = $path . $dir . DS; - $content = file_get_contents($package . 'composer.json'); - $result = json_decode($content, true); - - if (!empty($result['autoload'])) { - $autoload = $result['autoload']; - if (isset($autoload['psr-0'])) { - foreach ($autoload['psr-0'] as $ns => $val) { - $namespace[rtrim($ns, '\\')] = realpath($package . $val . DS . str_replace('\\', DS, $ns)) . DS; - } - } - - if (isset($autoload['psr-4'])) { - foreach ($autoload['psr-4'] as $ns => $val) { - $namespace[rtrim($ns, '\\')] = realpath($package . $val) . DS; - } - } - - if (isset($autoload['classmap'])) { - foreach ($autoload['classmap'] as $val) { - if (strpos($val, '/')) { - // 扫描目录 - $items = scandir($package . $val); - foreach ($items as $file) { - if ('php' == pathinfo($file, PATHINFO_EXTENSION)) { - $file = realpath($package . $val . DS . $file); - $info = self::parsePhpNamespace($file); - foreach ($info as $class) { - $classmap[$class] = $file; - } - } - } - } else { - // 解析文件 - $file = realpath($package . $val); - $info = self::parsePhpNamespace($file); - foreach ($info as $class) { - $classmap[$class] = $file; - } - } - } - } - if (isset($autoload['files'])) { - foreach ($autoload['files'] as $file) { - $files[] = realpath($package . $file); - } - } - } - } - } - return ['namespace' => $namespace, 'files' => $files, 'classmap' => $classmap]; - } - - // 解析PHP文件 获取类的命名空间 - private static function parsePhpNamespace($file) - { - $content = php_strip_whitespace($file); - $content = substr($content, 5); - if (0 === strpos(ltrim($content), 'namespace')) { - preg_match('/\snamespace\s(.*?);/is', $content, $matches); - $namespace = $matches[1] . '\\'; - } else { - $namespace = ''; - } - preg_match_all('/[\s|\;\}]class\s(\w+)\s?\{/is', $content, $matches); - - $info = []; - foreach ($matches[1] as $class) { - $info[] = $namespace . $class; - } - return $info; - } - // 注册composer自动加载 private static function registerComposerLoader() { diff --git a/library/think/session/driver/Redis.php b/library/think/session/driver/Redis.php index 65db47e3..367df10c 100644 --- a/library/think/session/driver/Redis.php +++ b/library/think/session/driver/Redis.php @@ -16,6 +16,7 @@ use think\Exception; class Redis extends SessionHandler { + /** @var \Redis */ protected $handler = null; protected $config = [ 'host' => '127.0.0.1', // redis主机 @@ -35,8 +36,10 @@ 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) { @@ -72,6 +75,7 @@ class Redis extends SessionHandler * 读取Session * @access public * @param string $sessID + * @return bool|string */ public function read($sessID) { @@ -83,6 +87,7 @@ class Redis extends SessionHandler * @access public * @param string $sessID * @param String $sessData + * @return bool */ public function write($sessID, $sessData) { @@ -97,16 +102,18 @@ class Redis extends SessionHandler * 删除Session * @access public * @param string $sessID + * @return bool|void */ public function destroy($sessID) { - return $this->handler->delete($this->config['session_name'] . $sessID) ? true : false; + $this->handler->delete($this->config['session_name'] . $sessID); } /** * Session 垃圾回收 * @access public * @param string $sessMaxLifeTime + * @return bool */ public function gc($sessMaxLifeTime) { From d17643dfd921dfee6e97c70b5eb3ef0f8067041c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 27 Jun 2016 11:53:21 +0800 Subject: [PATCH 517/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRoute=E7=B1=BB?= =?UTF-8?q?=E5=9C=A8=E5=A4=9A=E7=A7=8D=E8=B7=AF=E7=94=B1=E5=9C=B0=E5=9D=80?= =?UTF-8?q?=E4=B8=8B=E9=9D=A2=E5=AF=B9URL=E9=A2=9D=E5=A4=96=E5=8F=82?= =?UTF-8?q?=E6=95=B0=E7=9A=84=E6=94=AF=E6=8C=81=20=E4=BF=AE=E6=AD=A3=20bin?= =?UTF-8?q?dtoController=E6=96=B9=E6=B3=95=20App=E7=B1=BB=E8=B0=83?= =?UTF-8?q?=E6=95=B4=E5=AF=B9bindToApi=E7=9A=84=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 9 +---- library/think/Route.php | 82 ++++++++++++++++++----------------------- 2 files changed, 37 insertions(+), 54 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index d4c40b09..374df826 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -95,13 +95,8 @@ class App // 获取应用调度信息 $dispatch = self::$dispatch; if (empty($dispatch)) { - if (IS_API) { - // 直接绑定到控制器类命名空间 URL区分大小写 v1/User/getInfo - $dispatch = Route::bindToApi($request->path(), self::$namespace, $config['pathinfo_depr']); - } else { - // 进行URL路由检测 - $dispatch = self::routeCheck($request, $config); - } + // 进行URL路由检测 + $dispatch = self::routeCheck($request, $config); } // 记录当前调度信息 $request->dispatch($dispatch); diff --git a/library/think/Route.php b/library/think/Route.php index 59ee4bdd..bc804e5f 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -820,11 +820,12 @@ class Route */ public static function bindToClass($url, $class, $depr = '/') { - $array = explode($depr, $url, 2); + $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, $array[0] ?: Config::get('default_action')], 'params' => []]; + return ['type' => 'method', 'method' => [$class, $action], 'params' => []]; } /** @@ -846,11 +847,32 @@ class Route return ['type' => 'method', 'method' => [$namespace . '\\' . $class, $method], 'params' => []]; } + /** + * 绑定到应用 直接进行控制器类库访问 + * @access public + * @param string $url URL地址 + * @param string $depr URL分隔符 + * @return array + */ + public static function bindToApp($url, $depr = '/') + { + $array = explode($depr, $url, 4); + $module = !empty($array[0]) ? $array[0] : Config::get('default_module'); + $controller = !empty($array[1]) ? $array[1] : Config::get('default_controller'); + $method = !empty($array[2]) ? $array[2] : Config::get('default_action'); + $layer = Config::get('url_controller_layer'); + $class = App::$namespace . '\\' . $module . '\\' . $layer . '\\' . $controller; + if (!empty($array[3])) { + self::parseUrlParams($array[3]); + } + return ['type' => 'method', 'method' => [$class, $method], 'params' => []]; + } + /** * 绑定到控制器类 * @access public * @param string $url URL地址 - * @param string $module 模块名 + * @param string $controller 控制器名 (支持带模块名 index/user ) * @param string $depr URL分隔符 * @return array */ @@ -861,7 +883,7 @@ class Route if (!empty($array[1])) { self::parseUrlParams($array[1]); } - return ['type' => 'method', 'method' => [$controller, $action], 'params' => []]; + return ['type' => 'controller', 'controller' => $controller . '/' . $action, 'params' => []]; } /** @@ -882,27 +904,6 @@ class Route return ['type' => 'module', 'module' => $controller . '/' . $action]; } - /** - * 绑定到API - * @access public - * @param string $url URL地址 - * @param string $namespace 命名空间 - * @param string $depr URL分隔符 - * @return array - */ - public static function bindToApi($url, $namespace, $depr = '/') - { - $array = explode($depr, $url, 4); - $module = !empty($array[0]) ? $array[0] : Config::get('default_module'); - $class = !empty($array[1]) ? $array[1] : Config::get('default_controller'); - $method = !empty($array[2]) ? $array[2] : Config::get('default_action'); - $layer = Config::get('url_controller_layer'); - if (!empty($array[3])) { - self::parseUrlParams($array[3]); - } - return ['type' => 'method', 'method' => [$namespace . '\\' . $module . '\\' . $layer . '\\' . $class, $method], 'params' => []]; - } - /** * 路由参数有效性检查 * @access private @@ -1016,12 +1017,8 @@ class Route $url = str_replace($depr, '/', $url); } - $result = self::parseRoute($url, $autoSearch, true, $paramType); - - if (!empty($result['var'])) { - $_GET = array_merge($result['var'], $_GET); - } - return ['type' => $type, $type => $result['route']]; + $route = self::parseRoute($url, $autoSearch, true, $paramType); + return ['type' => $type, $type => $route]; } /** @@ -1077,15 +1074,7 @@ class Route // 解析操作 $action = !empty($path) ? array_shift($path) : null; // 解析额外参数 - if (!empty($path)) { - if ($paramType) { - $var += $path; - } else { - preg_replace_callback('/([^\/]+)\/([^\/]+)/', function ($match) use (&$var) { - $var[strtolower($match[1])] = strip_tags($match[2]); - }, implode('/', $path)); - } - } + self::parseUrlParams(empty($path) ? '' : implode('/', $path)); } else { $action = array_pop($path); $controller = !empty($path) ? array_pop($path) : null; @@ -1098,11 +1087,12 @@ class Route // 操作方法前缀支持 $action = 0 !== strpos($action, self::$methodPrefix[$method]) ? self::$methodPrefix[$method] . $action : $action; } + $_GET = array_merge($_GET, $var); } // 封装路由 $route = [$module, $controller, $action]; } - return ['route' => $route, 'var' => $var]; + return $route; } /** @@ -1215,13 +1205,12 @@ class Route $result = ['type' => 'controller', 'controller' => substr($url, 1), 'params' => $matches]; } else { // 解析路由地址 - $result = self::parseRoute($url); - $var = array_merge($matches, $result['var']); - // 解析剩余的URL参数 - self::parseUrlParams(implode('/', $paths), $var); + $route = self::parseRoute($url); // 路由到模块/控制器/操作 - $result = ['type' => 'module', 'module' => $result['route'], 'convert' => false]; + $result = ['type' => 'module', 'module' => $route, 'convert' => false]; } + // 解析额外参数 + self::parseUrlParams(empty($paths) ? '' : implode('/', $paths), $matches); return $result; } @@ -1243,7 +1232,6 @@ class Route }, $url); } } - // 设置当前请求的参数 Request::instance()->param(array_merge($var, $_GET)); } From 66607ae1803bdce64432bbe2dea726804a8e4aa2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 27 Jun 2016 12:11:47 +0800 Subject: [PATCH 518/670] =?UTF-8?q?=E4=BC=98=E5=8C=96Route=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 99 +++++++++++++++++++---------------------- 1 file changed, 45 insertions(+), 54 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index bc804e5f..69c02bc1 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -1017,20 +1017,46 @@ class Route $url = str_replace($depr, '/', $url); } - $route = self::parseRoute($url, $autoSearch, true, $paramType); + list($path, $var) = self::parseUrlPath($url); + $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 : '') . 'controller'; + $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]; + } return ['type' => $type, $type => $route]; } /** - * 解析规范的路由地址 地址格式 [模块/控制器/操作?]参数1=值1&参数2=值2... + * 解析URL的pathinfo参数和变量 * @access private * @param string $url URL地址 - * @param bool $autoSearch 是否自动深度搜索控制器 - * @param bool $reverse 是否反转解析URL - * @param integer $paramType URL参数解析方式 0 名称解析 1 顺序解析 * @return array */ - private static function parseRoute($url, $autoSearch = false, $reverse = false, $paramType = 0) + private static function parseUrlPath($url) { $url = trim($url, '/'); $var = []; @@ -1048,51 +1074,7 @@ class Route } else { $path = [$url]; } - $route = [null, null, null]; - if (isset($path)) { - if ($reverse) { - // 解析模块 - $module = Config::get('app_multi_module') ? array_shift($path) : null; - if ($autoSearch) { - // 自动搜索控制器 - $dir = APP_PATH . ($module ? $module . DS : '') . 'controller'; - $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)); - } else { - $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(); - // REST 操作方法支持 - if ('[rest]' == $action) { - $action = $method; - } elseif (Config::get('use_action_prefix') && !empty(self::$methodPrefix[$method])) { - // 操作方法前缀支持 - $action = 0 !== strpos($action, self::$methodPrefix[$method]) ? self::$methodPrefix[$method] . $action : $action; - } - $_GET = array_merge($_GET, $var); - } - // 封装路由 - $route = [$module, $controller, $action]; - } - return $route; + return [$path, $var]; } /** @@ -1204,10 +1186,19 @@ class Route // 路由到控制器 $result = ['type' => 'controller', 'controller' => substr($url, 1), 'params' => $matches]; } else { - // 解析路由地址 - $route = self::parseRoute($url); // 路由到模块/控制器/操作 - $result = ['type' => 'module', 'module' => $route, 'convert' => false]; + list($path, $var) = self::parseUrlPath($url); + $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; + } + $_GET = array_merge($_GET, $var); + // 路由到模块/控制器/操作 + $result = ['type' => 'module', 'module' => [$module, $controller, $action], 'convert' => false]; } // 解析额外参数 self::parseUrlParams(empty($paths) ? '' : implode('/', $paths), $matches); From 32c5e00bf496169f52c72cac4c215d0c6f75e376 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 27 Jun 2016 12:31:59 +0800 Subject: [PATCH 519/670] =?UTF-8?q?=E7=AE=80=E5=8C=96Route=E7=B1=BB?= =?UTF-8?q?=E7=9A=84parseUrl=E6=96=B9=E6=B3=95=20=E5=8F=96=E6=B6=88url=5Fp?= =?UTF-8?q?arse=5Ftype=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 2 -- library/think/App.php | 2 +- library/think/Route.php | 8 +++----- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/convention.php b/convention.php index a95b6b50..eca9e883 100644 --- a/convention.php +++ b/convention.php @@ -93,8 +93,6 @@ return [ 'url_controller_layer' => 'controller', // 表单请求类型伪装变量 'var_method' => '_method', - // URL解析方式 module controller class namespace - 'url_parse_type' => 'module', // +---------------------------------------------------------------------- // | 模板引擎设置 diff --git a/library/think/App.php b/library/think/App.php index 374df826..266475f2 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -468,7 +468,7 @@ class App } if (false === $result) { // 路由无效 解析模块/控制器/操作/参数... 支持控制器自动搜索 - $result = Route::parseUrl($path, $depr, $config['controller_auto_search'], $config['url_param_type'], $config['url_parse_type']); + $result = Route::parseUrl($path, $depr, $config['controller_auto_search']); } return $result; } diff --git a/library/think/Route.php b/library/think/Route.php index 69c02bc1..088dcdb7 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -931,8 +931,8 @@ class Route * 检测路由规则 * @access private * @param string $rule 路由规则 - * @param string $url URL地址 * @param string $route 路由地址 + * @param string $url URL地址 * @param array $pattern 变量规则 * @param array $option 路由参数 * @return array|false @@ -1002,11 +1002,9 @@ class Route * @param string $url URL地址 * @param string $depr URL分隔符 * @param bool $autoSearch 是否自动深度搜索控制器 - * @param integer $paramType URL参数解析方式 0 名称解析 1 顺序解析 - * @param string $type 路由类型 * @return array */ - public static function parseUrl($url, $depr = '/', $autoSearch = false, $paramType = 0, $type = 'module') + public static function parseUrl($url, $depr = '/', $autoSearch = false) { if (isset(self::$bind['module'])) { // 如果有模块/控制器绑定 @@ -1047,7 +1045,7 @@ class Route // 封装路由 $route = [$module, $controller, $action]; } - return ['type' => $type, $type => $route]; + return ['type' => 'module', 'module' => $route]; } /** From 5bf12f6c18f8de7073df43409184f1156f962e18 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 27 Jun 2016 15:28:35 +0800 Subject: [PATCH 520/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Url=E7=B1=BB=E7=9A=84?= =?UTF-8?q?getRouteUrl=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Url.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/library/think/Url.php b/library/think/Url.php index 6c938c04..cd763e32 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -241,8 +241,11 @@ class Url } $match = true; } - if (empty($pattern) && empty($param)) { + if (empty($pattern)) { // 没有任何变量 + if ($param) { + $vars = array_diff_key($array, $param); + } return $url; } elseif ($match && (empty($param) || array_intersect_assoc($param, $array) == $param)) { // 存在变量定义 From b018a9395542f197848cab62ff33c020b245bfcd Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 27 Jun 2016 16:42:07 +0800 Subject: [PATCH 521/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BUrl=E7=B1=BB=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E5=9C=B0=E5=9D=80=E7=94=9F=E6=88=90=E7=9A=84=E5=8C=B9?= =?UTF-8?q?=E9=85=8D=E6=A3=80=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Url.php | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/library/think/Url.php b/library/think/Url.php index cd763e32..d531d231 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -241,13 +241,10 @@ class Url } $match = true; } - if (empty($pattern)) { - // 没有任何变量 - if ($param) { - $vars = array_diff_key($array, $param); - } - return $url; - } elseif ($match && (empty($param) || array_intersect_assoc($param, $array) == $param)) { + if (!empty($param) && array_intersect_assoc($param, $array) != $param) { + $match = false; + } + if ($match) { // 存在变量定义 $vars = array_diff_key($array, $param); return $url; From 75f09e94e046196648e7421f8cfa32d7f444a8be Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 27 Jun 2016 17:08:38 +0800 Subject: [PATCH 522/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BUrl=E7=94=9F=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Url.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/library/think/Url.php b/library/think/Url.php index d531d231..774fc6e5 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -240,6 +240,8 @@ class Url } } $match = true; + } elseif (empty($pattern) && array_intersect_assoc($param, $array) == $param) { + $match = true; } if (!empty($param) && array_intersect_assoc($param, $array) != $param) { $match = false; From 63837e22134c70c462a8e92f7a0d5162683bae64 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 27 Jun 2016 17:35:09 +0800 Subject: [PATCH 523/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BUrl=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Url.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/Url.php b/library/think/Url.php index 774fc6e5..0a88bf7a 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -243,7 +243,7 @@ class Url } elseif (empty($pattern) && array_intersect_assoc($param, $array) == $param) { $match = true; } - if (!empty($param) && array_intersect_assoc($param, $array) != $param) { + if ($match && !empty($param) && array_intersect_assoc($param, $array) != $param) { $match = false; } if ($match) { From 0295340e4b9b6f7add00cee206cfe65ac4069da2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 27 Jun 2016 18:40:21 +0800 Subject: [PATCH 524/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Url=E7=B1=BB=E4=B8=80?= =?UTF-8?q?=E5=A4=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Url.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/library/think/Url.php b/library/think/Url.php index 0a88bf7a..0d9bd418 100644 --- a/library/think/Url.php +++ b/library/think/Url.php @@ -324,10 +324,6 @@ class Url // 分析路由规则中的变量 private static function parseVar($rule) { - // 检测是否设置了参数分隔符 - if ($depr = Config::get('url_params_depr')) { - $rule = str_replace($depr, '/', $rule); - } // 提取路由规则中的变量 $var = []; foreach (explode('/', $rule) as $val) { @@ -344,6 +340,9 @@ class Url } } + if ('$' == substr($val, -1, 1)) { + $val = substr($val, 0, -1); + } if (0 === strpos($val, '[:')) { // 可选参数 $optional = true; From 9ca4911c44be743459d788ad00a16c9c77d1bdc4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 27 Jun 2016 23:29:33 +0800 Subject: [PATCH 525/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E5=85=B3=E8=81=94?= =?UTF-8?q?=E9=A2=84=E8=BD=BD=E5=85=A5=E6=9F=A5=E8=AF=A2=20=E4=B8=A4?= =?UTF-8?q?=E4=B8=AA=E7=9B=B8=E5=90=8C=E6=A8=A1=E5=9E=8B=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 2 +- library/think/model/Relation.php | 9 ++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index df66fa07..0f92143a 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1466,7 +1466,7 @@ class Query unset($this->options['with_field']); } } - $this->field($field, false, $joinTable, $joinAlias, $joinName . '__'); + $this->field($field, false, $joinTable, $joinAlias, $relation . '__'); $i++; } elseif ($closure) { $with[$key] = $closure; diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index 070f6ea1..a065524c 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -302,23 +302,22 @@ class Relation */ protected function match($model, $relation, &$result) { - $modelName = Loader::parseName(basename(str_replace('\\', '/', $model))); // 重新组装模型数据 foreach ($result->toArray() as $key => $val) { if (strpos($key, '__')) { list($name, $attr) = explode('__', $key, 2); - if ($name == $modelName) { + if ($name == $relation) { $list[$name][$attr] = $val; unset($result->$key); } } } - if (!isset($list[$modelName])) { + if (!isset($list[$relation])) { // 设置关联模型属性 - $list[$modelName] = []; + $list[$relation] = []; } - $result->setAttr($relation, new $model($list[$modelName])); + $result->setAttr($relation, new $model($list[$relation])); } /** From ab1ee18364c192f448fa194292130edc3166f6df Mon Sep 17 00:00:00 2001 From: oldrind Date: Tue, 28 Jun 2016 10:14:50 +0800 Subject: [PATCH 526/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3block=E6=A0=87?= =?UTF-8?q?=E7=AD=BE=E5=B5=8C=E5=A5=97=E4=B8=8D=E8=83=BD=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98=EF=BC=8C=E6=94=B9=E8=BF=9B=E5=AF=B9?= =?UTF-8?q?=E6=9C=AA=E5=AE=9A=E4=B9=89=E5=8F=98=E9=87=8F=E8=BE=93=E5=87=BA?= =?UTF-8?q?=E7=9A=84=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Template.php | 43 +++++++++++-------- tests/thinkphp/library/think/templateTest.php | 12 +++--- 2 files changed, 31 insertions(+), 24 deletions(-) diff --git a/library/think/Template.php b/library/think/Template.php index a0f27706..bada4d2f 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -556,9 +556,15 @@ class Template $children[$parent][] = $name; continue; } + } elseif (!empty($val['parent'])) { + // 如果子标签没有被继承则用原值 + $children[$val['parent']][] = $name; + $blocks[$name] = $val; + } + if (!$val['parent']) { + // 替换模板中的顶级block标签 + $extend = str_replace($val['begin'] . $val['content'] . $val['end'], $replace, $extend); } - // 替换模板中的block标签 - $extend = str_replace($val['begin'] . $val['content'] . $val['end'], $replace, $extend); } } $content = $extend; @@ -735,20 +741,15 @@ class Template $str = trim(substr($str, $pos + 1)); $this->parseVar($str); $first = substr($str, 0, 1); - if (isset($array[1])) { - $this->parseVar($array[2]); - $name .= $array[1] . $array[2]; - if ('=' == $first) { - // {$varname?='xxx'} $varname为真时才输出xxx - $str = ''; - } else { - $str = ''; - } - } elseif (')' == substr($name, -1, 1)) { + if (strpos($name, ')')) { // $name为对象或是自动识别,或者含有函数 + if (isset($array[1])) { + $this->parseVar($array[2]); + $name .= $array[1] . $array[2]; + } switch ($first) { case '?': - $str = ''; + $str = ''; break; case '=': $str = ''; @@ -757,26 +758,32 @@ class Template $str = ''; } } else { + if (isset($array[1])) { + $this->parseVar($array[2]); + $_name = ' && ' . $name . $array[1] . $array[2]; + } else { + $_name = ''; + } // $name为数组 switch ($first) { case '?': // {$varname??'xxx'} $varname有定义则输出$varname,否则输出xxx - $str = ''; + $str = ''; break; case '=': // {$varname?='xxx'} $varname为真时才输出xxx - $str = ''; + $str = ''; break; case ':': // {$varname?:'xxx'} $varname为真时输出$varname,否则输出xxx - $str = ''; + $str = ''; break; default: if (strpos($str, ':')) { // {$varname ? 'a' : 'b'} $varname为真时输出a,否则输出b - $str = ''; + $str = ''; } else { - $str = ''; + $str = ''; } } } diff --git a/tests/thinkphp/library/think/templateTest.php b/tests/thinkphp/library/think/templateTest.php index 9b21028f..df9aff65 100644 --- a/tests/thinkphp/library/think/templateTest.php +++ b/tests/thinkphp/library/think/templateTest.php @@ -78,7 +78,7 @@ EOF; {\$name.a==\$name.b?='test'} EOF; $data = << + EOF; $template->parse($content); @@ -88,7 +88,7 @@ EOF; {\$name.a==\$name.b?'a':'b'} EOF; $data = << + EOF; $template->parse($content); @@ -98,7 +98,7 @@ EOF; {\$name.a|default='test'==\$name.b?'a':'b'} EOF; $data = << + EOF; $template->parse($content); @@ -210,7 +210,7 @@ EOF; <#\$info.a??'test'#> EOF; $data = <<a) ? (is_array(\$info)?\$info['a']:\$info->a) : 'test'; ?> +a)) ? (is_array(\$info)?\$info['a']:\$info->a) : 'test'; ?> EOF; $template->parse($content); @@ -326,7 +326,7 @@ EOF; ]; $data = ['name' => 'value']; $template->layout('layout')->fetch('display', $data, $config); - $this->expectOutputString('value'); + $this->expectOutputString('
value
'); } public function testDisplay() @@ -407,7 +407,7 @@ EOF; public function testIsCache() { $template = new Template(['cache_id' => '__CACHE_ID__', 'display_cache' => true]); - $this->assertTrue(!$template->isCache('__CACHE_ID__')); + $this->assertTrue($template->isCache('__CACHE_ID__')); $template->display_cache = false; $this->assertTrue(!$template->isCache('__CACHE_ID__')); } From ada4a71e780a7b5543a84b883731b9a610dd883c Mon Sep 17 00:00:00 2001 From: oldrind Date: Tue, 28 Jun 2016 10:39:01 +0800 Subject: [PATCH 527/670] =?UTF-8?q?=E4=BF=AE=E6=94=B9template=E7=B1=BB?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/thinkphp/library/think/templateTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/thinkphp/library/think/templateTest.php b/tests/thinkphp/library/think/templateTest.php index df9aff65..593b73dc 100644 --- a/tests/thinkphp/library/think/templateTest.php +++ b/tests/thinkphp/library/think/templateTest.php @@ -326,7 +326,7 @@ EOF; ]; $data = ['name' => 'value']; $template->layout('layout')->fetch('display', $data, $config); - $this->expectOutputString('
value
'); + $this->expectOutputString('value'); } public function testDisplay() @@ -407,7 +407,7 @@ EOF; public function testIsCache() { $template = new Template(['cache_id' => '__CACHE_ID__', 'display_cache' => true]); - $this->assertTrue($template->isCache('__CACHE_ID__')); + $this->assertTrue(!$template->isCache('__CACHE_ID__')); $template->display_cache = false; $this->assertTrue(!$template->isCache('__CACHE_ID__')); } From f794dcfa83537a8888c46db47959469f938f42f6 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Tue, 28 Jun 2016 11:30:26 +0800 Subject: [PATCH 528/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3RestController?= =?UTF-8?q?=E5=B1=9E=E6=80=A7=E5=90=8D=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/controller/Rest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/controller/Rest.php b/library/think/controller/Rest.php index 84ac3ed5..a58743b3 100644 --- a/library/think/controller/Rest.php +++ b/library/think/controller/Rest.php @@ -70,7 +70,7 @@ abstract class Rest 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)) { + } 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; From 25ad8a61f382ed0f76665e01d59bd5f6854eefd3 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Tue, 28 Jun 2016 11:31:12 +0800 Subject: [PATCH 529/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/controller/Yar.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/controller/Yar.php b/library/think/controller/Yar.php index 0a876326..fcf5ced1 100644 --- a/library/think/controller/Yar.php +++ b/library/think/controller/Yar.php @@ -30,7 +30,7 @@ abstract class Yar //判断扩展是否存在 if (!extension_loaded('yar')) { - throw new Exception('not support yar'); + throw new \Exception('not support yar'); } //实例化Yar_Server From 802ead16a855e6704bdfce6caca2424bc70f6451 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 28 Jun 2016 17:05:47 +0800 Subject: [PATCH 530/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=87=A0=E5=A4=84BUG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 2 +- library/think/File.php | 4 ++-- library/think/db/Builder.php | 2 -- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 266475f2..b927071d 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -162,7 +162,7 @@ class App * @param array $params 参数 * @return void */ - public static function dispatch($dispath, $type = 'module', $params = []) + public static function dispatch($dispatch, $type = 'module', $params = []) { self::$dispatch = ['type' => $type, $type => $dispatch, 'params' => $params]; } diff --git a/library/think/File.php b/library/think/File.php index 6701d93d..ef5d69da 100644 --- a/library/think/File.php +++ b/library/think/File.php @@ -29,9 +29,9 @@ class File extends SplFileObject // 上传文件信息 protected $info; - public function __construct($filename, $mode = 'r', $useIncludePath = false, $context = null) + public function __construct($filename, $mode = 'r') { - parent::__construct($filename, $mode, $useIncludePath, $context); + parent::__construct($filename, $mode); $this->filename = $this->getRealPath(); } diff --git a/library/think/db/Builder.php b/library/think/db/Builder.php index f07eca0c..ab95753d 100644 --- a/library/think/db/Builder.php +++ b/library/think/db/Builder.php @@ -138,8 +138,6 @@ abstract class Builder { if (is_string($value)) { $value = strpos($value, ':') === 0 && $this->query->isBind(substr($value, 1)) ? $value : $this->connection->quote($value); - } elseif (is_array($value) && is_string($value[0]) && strtolower($value[0]) == 'exp') { - $value = $value[1]; } elseif (is_array($value)) { $value = array_map([$this, 'parseValue'], $value); } elseif (is_bool($value)) { From ef71b5e81d9182fdc76b09ad4a5bf98889127bac Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 28 Jun 2016 17:42:28 +0800 Subject: [PATCH 531/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E5=99=A8=E7=B1=BB=E4=B8=8D=E5=AD=98=E5=9C=A8=E7=9A=84=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lang/zh-cn.php | 87 ++++++++++++++++++++-------------------- library/think/App.php | 4 +- library/think/Loader.php | 2 - 3 files changed, 47 insertions(+), 46 deletions(-) diff --git a/lang/zh-cn.php b/lang/zh-cn.php index 9a92c17a..be26c53a 100644 --- a/lang/zh-cn.php +++ b/lang/zh-cn.php @@ -11,49 +11,50 @@ // 核心中文语言包 return [ - // 系统错误提示 - 'Undefined variable' => '未定义变量', - 'Undefined index' => '未定义索引', - 'Parse error' => '语法解析错误', - 'Type error' => '类型错误', - 'Fatal error' => '致命错误', + // 系统错误提示 + 'Undefined variable' => '未定义变量', + 'Undefined index' => '未定义索引', + 'Parse error' => '语法解析错误', + 'Type error' => '类型错误', + 'Fatal error' => '致命错误', // 框架核心错误提示 - 'dispatch type not support' => '不支持的调度类型', - 'method param miss' => '方法参数错误', - 'method not exists' => '方法不存在', - 'module not exists' => '模块不存在', - 'class 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 写入错误', + 'dispatch type not support' => '不支持的调度类型', + 'method param miss' => '方法参数错误', + 'method not exists' => '方法不存在', + 'module not exists' => '模块不存在', + 'controller not exists' => '控制器不存在', + 'class 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 写入错误', ]; diff --git a/library/think/App.php b/library/think/App.php index b927071d..99613ac6 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -307,7 +307,9 @@ class App 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:' . $controller); + } // 获取当前操作名 $action = $actionName . $config['action_suffix']; if (!preg_match('/^[A-Za-z](\w)*$/', $action)) { diff --git a/library/think/Loader.php b/library/think/Loader.php index 00f758dd..97e92140 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -351,8 +351,6 @@ class Loader return new $class(Request::instance()); } elseif ($empty && class_exists($emptyClass = self::parseClass($module, $layer, $empty, $appendSuffix))) { return new $emptyClass(Request::instance()); - } else { - throw new ClassNotFoundException('class not exists:' . $class, $class); } } From 93882f4c8f065a6f4ec3e6669a36e417913aa8b5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 28 Jun 2016 18:52:56 +0800 Subject: [PATCH 532/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Query=E7=B1=BB?= =?UTF-8?q?=E7=9A=84query=E5=92=8Cexecute=E6=96=B9=E6=B3=95=E5=8F=82?= =?UTF-8?q?=E6=95=B0=20=E5=8E=BB=E6=8E=89fetch=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 0f92143a..edeefb72 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -178,16 +178,15 @@ class Query * @access public * @param string $sql sql指令 * @param array $bind 参数绑定 - * @param boolean $fetch 不执行只是获取SQL * @param boolean $master 是否在主服务器读操作 * @param bool|string $class 指定返回的数据集对象 * @return mixed * @throws BindParamException * @throws PDOException */ - public function query($sql, $bind = [], $fetch = false, $master = false, $class = false) + public function query($sql, $bind = [], $master = false, $class = false) { - return $this->connection->query($sql, $bind, $fetch, $master, $class); + return $this->connection->query($sql, $bind, $master, $class); } /** @@ -195,16 +194,15 @@ class Query * @access public * @param string $sql sql指令 * @param array $bind 参数绑定 - * @param boolean $fetch 不执行只是获取SQL * @param boolean $getLastInsID 是否获取自增ID * @param boolean $sequence 自增序列名 * @return int * @throws BindParamException * @throws PDOException */ - public function execute($sql, $bind = [], $fetch = false, $getLastInsID = false, $sequence = null) + public function execute($sql, $bind = [], $getLastInsID = false, $sequence = null) { - return $this->connection->execute($sql, $bind, $fetch, $getLastInsID, $sequence); + return $this->connection->execute($sql, $bind, $getLastInsID, $sequence); } /** From 438330a4b2ffa4f1892784212d3963c2b65b11fb Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 28 Jun 2016 19:07:33 +0800 Subject: [PATCH 533/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BBdelete?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E5=8F=82=E6=95=B0=E9=BB=98=E8=AE=A4=E5=80=BC?= =?UTF-8?q?=E4=B8=BAnull=20=E5=BD=93=E5=8F=82=E6=95=B0=E4=B8=BAtrue?= =?UTF-8?q?=E7=9A=84=E6=97=B6=E5=80=99=20=E8=A1=A8=E7=A4=BA=E5=BC=BA?= =?UTF-8?q?=E5=88=B6=E5=88=A0=E9=99=A4=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index edeefb72..b6719410 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1871,7 +1871,7 @@ class Query * @throws Exception * @throws PDOException */ - public function selectOrFail($data = []) + public function selectOrFail($data = null) { return $this->failException(true)->select($data); } @@ -1885,7 +1885,7 @@ class Query * @throws Exception * @throws PDOException */ - public function findOrFail($data = []) + public function findOrFail($data = null) { return $this->failException(true)->find($data); } @@ -1948,22 +1948,22 @@ class Query /** * 删除记录 * @access public - * @param array $data 表达式 + * @param mixed $data 表达式 true 表示强制删除 * @return int * @throws Exception * @throws PDOException */ - public function delete($data = []) + public function delete($data = null) { // 分析查询表达式 $options = $this->parseExpress(); - if (!empty($data)) { + if (!is_null($data) && true !== $data) { // AR模式分析主键条件 $this->parsePkWhere($data, $options); } - if (empty($options['where'])) { + if (true !== $data && empty($options['where'])) { // 如果条件为空 不进行删除操作 除非设置 1=1 throw new Exception('delete without condition'); } From dea2a7203893a00f27c1dee5ce3dfa605195b9d4 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 28 Jun 2016 19:31:48 +0800 Subject: [PATCH 534/670] =?UTF-8?q?Template=E7=B1=BB=E6=94=B9=E8=BF=9B=20?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E8=A7=A3=E6=9E=90=E5=A2=9E=E5=8A=A0=20$Reque?= =?UTF-8?q?st.=20=E7=89=B9=E6=AE=8A=E5=8F=98=E9=87=8F=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Template.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/library/think/Template.php b/library/think/Template.php index bada4d2f..56a27453 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -559,7 +559,7 @@ class Template } elseif (!empty($val['parent'])) { // 如果子标签没有被继承则用原值 $children[$val['parent']][] = $name; - $blocks[$name] = $val; + $blocks[$name] = $val; } if (!$val['parent']) { // 替换模板中的顶级block标签 @@ -854,6 +854,11 @@ class Template if ('$Think' == $first) { // 所有以Think.打头的以特殊变量对待 无需模板赋值就可以输出 $parseStr = $this->parseThinkVar($vars); + } elseif ('$Request' == $first) { + // 获取Request请求对象参数 + $method = array_shift($vars); + $params = !empty($vars) ? '\'' . implode('.', $vars) . '\'' : ''; + $parseStr = '\think\Request::instance()->' . $method . '(' . $params . ')'; } else { switch ($this->config['tpl_var_identify']) { case 'array': // 识别为数组 From 177023fa0e21ff34268065ab27fcacac9cfbf27c Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 28 Jun 2016 22:07:25 +0800 Subject: [PATCH 535/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E6=A0=87=E7=AD=BE=20$Request.=20=E6=94=AF=E6=8C=81$Request.roo?= =?UTF-8?q?t.true=20=E7=94=A8=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Template.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/library/think/Template.php b/library/think/Template.php index 56a27453..97c01d4e 100644 --- a/library/think/Template.php +++ b/library/think/Template.php @@ -856,8 +856,15 @@ class Template $parseStr = $this->parseThinkVar($vars); } elseif ('$Request' == $first) { // 获取Request请求对象参数 - $method = array_shift($vars); - $params = !empty($vars) ? '\'' . implode('.', $vars) . '\'' : ''; + $method = array_shift($vars); + if (!empty($vars)) { + $params = implode('.', $vars); + if ('true' != $params) { + $params = '\'' . $params . '\''; + } + } else { + $params = ''; + } $parseStr = '\think\Request::instance()->' . $method . '(' . $params . ')'; } else { switch ($this->config['tpl_var_identify']) { From d9c175abc4f206be63793bbb3b7092f1a72030b2 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 29 Jun 2016 09:16:08 +0800 Subject: [PATCH 536/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E6=98=A0=E5=B0=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 51 ++++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index 088dcdb7..705c7e30 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -638,7 +638,7 @@ class Route if (isset(self::$map[$url])) { // URL映射(完整静态URL匹配) - return self::parseUrl(self::$map[$url], $depr); + return self::parseModule(self::$map[$url], $depr); } if (strpos($url, '/') && isset(self::$alias[strstr($url, '/', true)])) { @@ -1010,12 +1010,8 @@ class Route // 如果有模块/控制器绑定 $url = self::$bind['module'] . '/' . $url; } - // 分隔符替换 确保路由定义使用统一的分隔符 - if ('/' != $depr) { - $url = str_replace($depr, '/', $url); - } - list($path, $var) = self::parseUrlPath($url); + list($path, $var) = self::parseUrlPath($url, $depr); $route = [null, null, null]; if (isset($path)) { // 解析模块 @@ -1052,10 +1048,15 @@ class Route * 解析URL的pathinfo参数和变量 * @access private * @param string $url URL地址 + * @param string $depr URL分隔符 * @return array */ - private static function parseUrlPath($url) + private static function parseUrlPath($url, $depr = '/') { + // 分隔符替换 确保路由定义使用统一的分隔符 + if ('/' != $depr) { + $url = str_replace($depr, '/', $url); + } $url = trim($url, '/'); $var = []; if (false !== strpos($url, '?')) { @@ -1185,24 +1186,36 @@ class Route $result = ['type' => 'controller', 'controller' => substr($url, 1), 'params' => $matches]; } else { // 路由到模块/控制器/操作 - list($path, $var) = self::parseUrlPath($url); - $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; - } - $_GET = array_merge($_GET, $var); - // 路由到模块/控制器/操作 - $result = ['type' => 'module', 'module' => [$module, $controller, $action], 'convert' => false]; + $result = self::parseModule($url); } // 解析额外参数 self::parseUrlParams(empty($paths) ? '' : implode('/', $paths), $matches); 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; + } + $_GET = array_merge($_GET, $var); + // 路由到模块/控制器/操作 + return ['type' => 'module', 'module' => [$module, $controller, $action], 'convert' => false]; + } + /** * 解析URL地址中的参数Request对象 * @access private From b223dba4904f9986f05ff634d82e374b6039f9da Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 29 Jun 2016 12:48:34 +0800 Subject: [PATCH 537/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BLoader=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Lang.php | 2 +- library/think/Loader.php | 338 +++++++++++++++++++++------------------ 2 files changed, 181 insertions(+), 159 deletions(-) diff --git a/library/think/Lang.php b/library/think/Lang.php index 571921be..35c98f05 100644 --- a/library/think/Lang.php +++ b/library/think/Lang.php @@ -148,7 +148,7 @@ class Lang /** * 自动侦测设置获取语言选择 - * @return void + * @return string */ public static function detect() { diff --git a/library/think/Loader.php b/library/think/Loader.php index 97e92140..00ee74d3 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -11,28 +11,28 @@ namespace think; -use think\App; use think\exception\ClassNotFoundException; -use think\Request; class Loader { protected static $instance = []; // 类名映射 protected static $map = []; - // 加载列表 - protected static $load = []; - // 命名空间 - protected static $namespace = []; + // 命名空间别名 protected static $namespaceAlias = []; + // PSR-4 private static $prefixLengthsPsr4 = []; private static $prefixDirsPsr4 = []; + private static $fallbackDirsPsr4 = []; + // PSR-0 - private static $prefixesPsr0 = []; - // Composer自动加载 - private static $composerLoader = false; + private static $prefixesPsr0 = []; + private static $fallbackDirsPsr0 = []; + + // 自动加载的文件 + private static $autoloadFiles = []; // 自动加载 public static function autoload($class) @@ -48,55 +48,83 @@ class Loader } } - if (!empty(self::$map[$class])) { - // 类库映射 - include self::$map[$class]; - } elseif (self::$composerLoader && $file = self::findFileInComposer($class)) { - // Composer自动加载 - include $file; - } else { - // 命名空间自动加载 - if (!strpos($class, '\\')) { + if ($file = self::findFile($class)) { + + // Win环境严格区分大小写 + if (IS_WIN && pathinfo($file, PATHINFO_FILENAME) != pathinfo(realpath($file), PATHINFO_FILENAME)) { return false; } - $item = explode('\\', $class); - // 解析命名空间所在的路径 - if (count($item) > 2 && isset(self::$namespace[$item[0] . '\\' . $item[1]])) { - // 子命名空间定义(仅支持二级) - list($ns1, $ns2, $class) = explode('\\', $class, 3); - $path = self::$namespace[$ns1 . '\\' . $ns2]; - } elseif (isset(self::$namespace[$item[0]])) { - // 根命名空间定义 - list($name, $class) = explode('\\', $class, 2); - $path = self::$namespace[$name]; - } elseif (is_dir(EXTEND_PATH . $item[0])) { - // 扩展类库命名空间 - list($name, $class) = explode('\\', $class, 2); - $path = EXTEND_PATH . $name . DS; - } else { - return false; - } - // 定位文件 - $match = false; - foreach ((array) $path as $p) { - $filename = $p . str_replace('\\', DS, $class) . EXT; - if (is_file($filename)) { - // Win环境严格区分大小写 - if (IS_WIN && false === strpos(realpath($filename), $class . EXT)) { - continue; - } - $match = true; - break; - } - } - if ($match) { - include $filename; - } else { - return false; + includeFile($file); + return true; + } + } + + /** + * 查找文件 + * @param $class + * @return bool + */ + private static function findFile($class) + { + if (!empty(self::$map[$class])) { + // 类库映射 + return self::$map[$class]; + } + + // 查找 PSR-4 + $logicalPathPsr4 = strtr($class, '\\', DS) . EXT; + + $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))) { + return $file; + } + } + } } } - return true; + + // 查找 PSR-4 fallback dirs + foreach (self::$fallbackDirsPsr4 as $dir) { + if (is_file($file = $dir . DS . $logicalPathPsr4)) { + return $file; + } + } + + // 查找 PSR-0 + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DS); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DS) . EXT; + } + + 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)) { + return $file; + } + } + } + } + } + + // 查找 PSR-0 fallback dirs + foreach (self::$fallbackDirsPsr0 as $dir) { + if (is_file($file = $dir . DS . $logicalPathPsr0)) { + return $file; + } + } + + return self::$map[$class] = false; } // 注册classmap @@ -113,12 +141,40 @@ class Loader public static function addNamespace($namespace, $path = '') { if (is_array($namespace)) { - self::$namespace = array_merge(self::$namespace, $namespace); + foreach ($namespace as $prefix => $paths) { + self::setPsr4($prefix . '\\', rtrim($paths, DS)); + } } else { - self::$namespace[$namespace] = $path; + self::setPsr4($namespace . '\\', rtrim($path, DS)); } } + // 注册Psr0空间 + private static function setPsr0($prefix, $paths) + { + if (!$prefix) { + self::$fallbackDirsPsr0 = (array)$paths; + } else { + self::$prefixesPsr0[$prefix[0]][$prefix] = (array)$paths; + } + } + + // 注册Psr4空间 + private static function setPsr4($prefix, $paths) + { + if (!$prefix) { + self::$fallbackDirsPsr4 = (array)$paths; + } else { + $length = strlen($prefix); + 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; + } + } + + // 注册命名空间别名 public static function addNamespaceAlias($namespace, $original = '') { @@ -133,7 +189,7 @@ class Loader public static function register($autoload = '') { // 注册系统自动加载 - spl_autoload_register($autoload ?: 'think\\Loader::autoload'); + spl_autoload_register($autoload ?: 'think\\Loader::autoload', true, true); // 注册命名空间定义 self::addNamespace([ 'think' => LIB_PATH . 'think' . DS, @@ -141,26 +197,15 @@ class Loader 'traits' => LIB_PATH . 'traits' . DS, ]); // 加载类库映射文件 - self::addClassMap(include THINK_PATH . 'classmap' . EXT); + self::addClassMap(includeFile(THINK_PATH . 'classmap' . EXT)); // Composer自动加载支持 if (is_dir(VENDOR_PATH . 'composer')) { - // 注册Composer自动加载 - self::$composerLoader = true; self::registerComposerLoader(); - } elseif (is_file(VENDOR_PATH . 'think_autoload.php')) { - // 读取Composer自动加载文件 - $autoload = include VENDOR_PATH . 'think_autoload.php'; - if (is_array($autoload)) { - // 命名空间和类库映射注册 - self::addNamespace($autoload['namespace']); - self::addClassMap($autoload['classmap']); - // 载入composer包的文件列表 - foreach ($autoload['files'] as $file) { - include $file; - } - } } + + // 自动加载extend目录 + self::$fallbackDirsPsr4[] = rtrim(EXTEND_PATH, DS); } // 注册composer自动加载 @@ -169,19 +214,14 @@ class Loader if (is_file(VENDOR_PATH . 'composer/autoload_namespaces.php')) { $map = require VENDOR_PATH . 'composer/autoload_namespaces.php'; foreach ($map as $namespace => $path) { - self::$prefixesPsr0[$namespace[0]][$namespace] = (array) $path; + self::setPsr0($namespace, $path); } } if (is_file(VENDOR_PATH . 'composer/autoload_psr4.php')) { $map = require VENDOR_PATH . 'composer/autoload_psr4.php'; foreach ($map as $namespace => $path) { - $length = strlen($namespace); - if ('\\' !== $namespace[$length - 1]) { - throw new \InvalidArgumentException("PSR-4 error: A non-empty PSR-4 prefix must end with a namespace separator."); - } - self::$prefixLengthsPsr4[$namespace[0]][$namespace] = $length; - self::$prefixDirsPsr4[$namespace] = (array) $path; + self::setPsr4($namespace, $path); } } @@ -195,81 +235,34 @@ class Loader if (is_file(VENDOR_PATH . 'composer/autoload_files.php')) { $includeFiles = require VENDOR_PATH . 'composer/autoload_files.php'; foreach ($includeFiles as $fileIdentifier => $file) { - self::composerRequire($fileIdentifier, $file); - } - } - } - - private static function composerRequire($fileIdentifier, $file) - { - if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { - require $file; - $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; - } - } - - private static function findFileInComposer($class, $ext = '.php') - { - // PSR-4 lookup - $logicalPathPsr4 = strtr($class, '\\', DS) . $ext; - - $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 (file_exists($file = $dir . DS . substr($logicalPathPsr4, $length))) { - return $file; - } - } + if (empty(self::$autoloadFiles[$fileIdentifier])) { + requireFile($file); + self::$autoloadFiles[$fileIdentifier] = true; } } } - // PSR-0 lookup - if (false !== $pos = strrpos($class, '\\')) { - // namespaced class name - $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) - . strtr(substr($logicalPathPsr4, $pos + 1), '_', DS); - } else { - // PEAR-like class name - $logicalPathPsr0 = strtr($class, '_', DS) . $ext; - } - - if (isset(self::$prefixesPsr0[$first])) { - foreach (self::$prefixesPsr0[$first] as $prefix => $dirs) { - if (0 === strpos($class, $prefix)) { - foreach ($dirs as $dir) { - if (file_exists($file = $dir . DS . $logicalPathPsr0)) { - return $file; - } - } - } - } - } - // Remember that this class does not exist. - return self::$map[$class] = false; } /** * 导入所需的类库 同java的Import 本函数有缓存功能 - * @param string $class 类库命名空间字符串 + * @param string $class 类库命名空间字符串 * @param string $baseUrl 起始路径 - * @param string $ext 导入的文件扩展名 + * @param string $ext 导入的文件扩展名 * @return boolean */ public static function import($class, $baseUrl = '', $ext = EXT) { static $_file = []; - $class = str_replace(['.', '#'], [DS, '.'], $class); + $class = str_replace(['.', '#'], [DS, '.'], $class); if (isset($_file[$class . $baseUrl])) { return true; } if (empty($baseUrl)) { list($name, $class) = explode(DS, $class, 2); - if (isset(self::$namespace[$name])) { + if (isset(self::$prefixDirsPsr4[$name])) { // 注册的命名空间 - $baseUrl = self::$namespace[$name]; + $baseUrl = self::$prefixDirsPsr4[$name]; } elseif ('@' == $name) { //加载当前模块应用类库 $baseUrl = App::$modulePath; @@ -283,13 +276,23 @@ class Loader $baseUrl .= DS; } // 如果类存在 则导入类库文件 - $filename = $baseUrl . $class . $ext; - if (is_file($filename)) { + 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 && false === strpos(realpath($filename), $class . $ext)) { + if (IS_WIN && pathinfo($filename, PATHINFO_FILENAME) != pathinfo(realpath($filename), PATHINFO_FILENAME)) { return false; } - include $filename; + includeFile($filename); $_file[$class . $baseUrl] = true; return true; } @@ -298,10 +301,10 @@ class Loader /** * 实例化(分层)模型 - * @param string $name Model名称 - * @param string $layer 业务层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @param string $common 公共模块名 + * @param string $name Model名称 + * @param string $layer 业务层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @param string $common 公共模块名 * @return Object * @throws ClassNotFoundException */ @@ -332,10 +335,10 @@ class Loader /** * 实例化(分层)控制器 格式:[模块名/]控制器名 - * @param string $name 资源地址 - * @param string $layer 控制层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @param string $empty 空控制器名称 + * @param string $name 资源地址 + * @param string $layer 控制层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @param string $empty 空控制器名称 * @return Object|false * @throws ClassNotFoundException */ @@ -356,10 +359,10 @@ class Loader /** * 实例化验证类 格式:[模块名/]验证器名 - * @param string $name 资源地址 - * @param string $layer 验证层名称 - * @param bool $appendSuffix 是否添加类名后缀 - * @param string $common 公共模块名 + * @param string $name 资源地址 + * @param string $layer 验证层名称 + * @param bool $appendSuffix 是否添加类名后缀 + * @param string $common 公共模块名 * @return Object|false * @throws ClassNotFoundException */ @@ -405,10 +408,10 @@ class Loader /** * 远程调用模块的操作方法 参数格式 [模块/控制器/]操作 - * @param string $url 调用地址 - * @param string|array $vars 调用参数 支持字符串和数组 - * @param string $layer 要调用的控制层名称 - * @param bool $appendSuffix 是否添加类名后缀 + * @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) @@ -432,14 +435,16 @@ class Loader /** * 字符串命名风格转换 * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格 - * @param string $name 字符串 - * @param integer $type 转换类型 + * @param string $name 字符串 + * @param integer $type 转换类型 * @return string */ public static function parseName($name, $type = 0) { if ($type) { - return ucfirst(preg_replace_callback('/_([a-zA-Z])/', function ($match) {return strtoupper($match[1]);}, $name)); + return ucfirst(preg_replace_callback('/_([a-zA-Z])/', function ($match) { + return strtoupper($match[1]); + }, $name)); } else { return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); } @@ -448,8 +453,9 @@ class Loader /** * 解析应用类的类名 * @param string $module 模块名 - * @param string $layer 层名 controller model ... - * @param string $name 类名 + * @param string $layer 层名 controller model ... + * @param string $name 类名 + * @param bool $appendSuffix * @return string */ public static function parseClass($module, $layer, $name, $appendSuffix = false) @@ -470,3 +476,19 @@ class Loader self::$instance = []; } } + +/** + * 作用范围隔离 + * + * @param $file + * @return mixed + */ +function includeFile($file) +{ + return include $file; +} + +function requireFile($file) +{ + return require $file; +} \ No newline at end of file From 475add81a39cd9db336a0d2635c8e0b306f262b5 Mon Sep 17 00:00:00 2001 From: cjango Date: Wed, 29 Jun 2016 16:03:44 +0800 Subject: [PATCH 538/670] =?UTF-8?q?=E5=8A=A9=E6=89=8B=E5=87=BD=E6=95=B0=20?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E5=AE=9A=E4=B9=89=E5=88=A4=E6=96=AD=EF=BC=8C?= =?UTF-8?q?=E6=96=B9=E4=BE=BF=E7=94=A8=E6=88=B7=E9=87=8D=E5=86=99helper?= =?UTF-8?q?=E5=87=BD=E6=95=B0=20=E6=B3=A8=EF=BC=9A=E5=8F=AA=E6=94=AF?= =?UTF-8?q?=E6=8C=81applacation/common.php=E5=86=85=E9=87=8D=E5=86=99?= =?UTF-8?q?=EF=BC=8C=E6=A8=A1=E5=9D=97=E4=B8=8B=E7=9A=84=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E5=BA=93=E4=B8=8D=E5=8F=AF=E4=BB=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper.php | 374 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 215 insertions(+), 159 deletions(-) diff --git a/helper.php b/helper.php index adaa31c1..6f630a72 100644 --- a/helper.php +++ b/helper.php @@ -33,9 +33,11 @@ use think\View; * @param string $ext 类库后缀 * @return boolean */ -function load_trait($class, $ext = EXT) -{ - return Loader::import($class, TRAIT_PATH, $ext); +if (!function_exists('load_trait')) { + function load_trait($class, $ext = EXT) + { + return Loader::import($class, TRAIT_PATH, $ext); + } } /** @@ -47,10 +49,12 @@ function load_trait($class, $ext = EXT) * * @throws Exception */ -function exception($msg, $code = 0, $exception = '') -{ - $e = $exception ?: '\think\Exception'; - throw new $e($msg, $code); +if (!function_exists('exception')) { + function exception($msg, $code = 0, $exception = '') + { + $e = $exception ?: '\think\Exception'; + throw new $e($msg, $code); + } } /** @@ -60,12 +64,14 @@ function exception($msg, $code = 0, $exception = '') * @param integer|string $dec 小数位 如果是m 表示统计内存占用 * @return mixed */ -function debug($start, $end = '', $dec = 6) -{ - if ('' == $end) { - Debug::remark($start); - } else { - return 'm' == $dec ? Debug::getRangeMem($start, $end) : Debug::getRangeTime($start, $end, $dec); +if (!function_exists('debug')) { + function debug($start, $end = '', $dec = 6) + { + if ('' == $end) { + Debug::remark($start); + } else { + return 'm' == $dec ? Debug::getRangeMem($start, $end) : Debug::getRangeTime($start, $end, $dec); + } } } @@ -76,9 +82,11 @@ function debug($start, $end = '', $dec = 6) * @param string $lang 语言 * @return mixed */ -function lang($name, $vars = [], $lang = '') -{ - return Lang::get($name, $vars, $lang); +if (!function_exists('lang')) { + function lang($name, $vars = [], $lang = '') + { + return Lang::get($name, $vars, $lang); + } } /** @@ -88,12 +96,14 @@ function lang($name, $vars = [], $lang = '') * @param string $range 作用域 * @return mixed */ -function config($name = '', $value = null, $range = '') -{ - if (is_null($value) && is_string($name)) { - return Config::get($name, $range); - } else { - return Config::set($name, $value, $range); +if (!function_exists('config')) { + function config($name = '', $value = null, $range = '') + { + if (is_null($value) && is_string($name)) { + return Config::get($name, $range); + } else { + return Config::set($name, $value, $range); + } } } @@ -104,28 +114,30 @@ function config($name = '', $value = null, $range = '') * @param string $filter 过滤方法 * @return mixed */ -function input($key, $default = null, $filter = null) -{ - 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', 'delete', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) { - $key = substr($key, $pos + 1); +if (!function_exists('input')) { + function input($key, $default = null, $filter = null) + { + 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', 'delete', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) { + $key = substr($key, $pos + 1); + } else { + $method = 'param'; + } } else { + // 默认为自动判断 $method = 'param'; } - } else { - // 默认为自动判断 - $method = 'param'; - } - if (isset($has)) { - return request()->has($key, $method, $default); - } else { - return request()->$method($key, $default, $filter); + if (isset($has)) { + return request()->has($key, $method, $default); + } else { + return request()->$method($key, $default, $filter); + } } } @@ -135,9 +147,11 @@ function input($key, $default = null, $filter = null) * @param array $data 传人的参数 * @return mixed */ -function widget($name, $data = []) -{ - return Loader::action($name, $data, 'widget'); +if (!function_exists('widget')) { + function widget($name, $data = []) + { + return Loader::action($name, $data, 'widget'); + } } /** @@ -147,9 +161,11 @@ function widget($name, $data = []) * @param bool $appendSuffix 是否添加类名后缀 * @return \think\Model */ -function model($name = '', $layer = 'model', $appendSuffix = false) -{ - return Loader::model($name, $layer, $appendSuffix); +if (!function_exists('model')) { + function model($name = '', $layer = 'model', $appendSuffix = false) + { + return Loader::model($name, $layer, $appendSuffix); + } } /** @@ -159,9 +175,11 @@ function model($name = '', $layer = 'model', $appendSuffix = false) * @param bool $appendSuffix 是否添加类名后缀 * @return \think\Validate */ -function validate($name = '', $layer = 'validate', $appendSuffix = false) -{ - return Loader::validate($name, $layer, $appendSuffix); +if (!function_exists('validate')) { + function validate($name = '', $layer = 'validate', $appendSuffix = false) + { + return Loader::validate($name, $layer, $appendSuffix); + } } /** @@ -170,9 +188,11 @@ function validate($name = '', $layer = 'validate', $appendSuffix = false) * @param array|string $config 数据库配置参数 * @return \think\db\Query */ -function db($name = '', $config = []) -{ - return Db::connect($config)->name($name); +if (!function_exists('db')) { + function db($name = '', $config = []) + { + return Db::connect($config)->name($name); + } } /** @@ -182,9 +202,11 @@ function db($name = '', $config = []) * @param bool $appendSuffix 是否添加类名后缀 * @return \think\Controller */ -function controller($name, $layer = 'controller', $appendSuffix = false) -{ - return Loader::controller($name, $layer, $appendSuffix); +if (!function_exists('controller')) { + function controller($name, $layer = 'controller', $appendSuffix = false) + { + return Loader::controller($name, $layer, $appendSuffix); + } } /** @@ -195,9 +217,11 @@ function controller($name, $layer = 'controller', $appendSuffix = false) * @param bool $appendSuffix 是否添加类名后缀 * @return mixed */ -function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) -{ - return Loader::action($url, $vars, $layer, $appendSuffix); +if (!function_exists('action')) { + function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) + { + return Loader::action($url, $vars, $layer, $appendSuffix); + } } /** @@ -207,9 +231,11 @@ function action($url, $vars = [], $layer = 'controller', $appendSuffix = false) * @param string $ext 导入的文件扩展名 * @return boolean */ -function import($class, $baseUrl = '', $ext = EXT) -{ - return Loader::import($class, $baseUrl, $ext); +if (!function_exists('import')) { + function import($class, $baseUrl = '', $ext = EXT) + { + return Loader::import($class, $baseUrl, $ext); + } } /** @@ -218,9 +244,11 @@ function import($class, $baseUrl = '', $ext = EXT) * @param string $ext 类库后缀 * @return boolean */ -function vendor($class, $ext = EXT) -{ - return Loader::import($class, VENDOR_PATH, $ext); +if (!function_exists('vendor')) { + function vendor($class, $ext = EXT) + { + return Loader::import($class, VENDOR_PATH, $ext); + } } /** @@ -230,9 +258,11 @@ function vendor($class, $ext = EXT) * @param string $label 标签 默认为空 * @return void|string */ -function dump($var, $echo = true, $label = null) -{ - return Debug::dump($var, $echo, $label); +if (!function_exists('dump')) { + function dump($var, $echo = true, $label = null) + { + return Debug::dump($var, $echo, $label); + } } /** @@ -243,9 +273,11 @@ function dump($var, $echo = true, $label = null) * @param bool|string $domain 域名 * @return string */ -function url($url = '', $vars = '', $suffix = true, $domain = false) -{ - return Url::build($url, $vars, $suffix, $domain); +if (!function_exists('url')) { + function url($url = '', $vars = '', $suffix = true, $domain = false) + { + return Url::build($url, $vars, $suffix, $domain); + } } /** @@ -255,23 +287,25 @@ function url($url = '', $vars = '', $suffix = true, $domain = false) * @param string $prefix 前缀 * @return mixed */ -function session($name, $value = '', $prefix = null) -{ - if (is_array($name)) { - // 初始化 - Session::init($name); - } elseif (is_null($name)) { - // 清除 - Session::clear($value); - } elseif ('' === $value) { - // 判断或获取 - return 0 === strpos($name, '?') ? Session::has(substr($name, 1), $prefix) : Session::get($name, $prefix); - } elseif (is_null($value)) { - // 删除 - return Session::delete($name, $prefix); - } else { - // 设置 - return Session::set($name, $value, $prefix); +if (!function_exists('session')) { + function session($name, $value = '', $prefix = null) + { + if (is_array($name)) { + // 初始化 + Session::init($name); + } elseif (is_null($name)) { + // 清除 + Session::clear($value); + } elseif ('' === $value) { + // 判断或获取 + return 0 === strpos($name, '?') ? Session::has(substr($name, 1), $prefix) : Session::get($name, $prefix); + } elseif (is_null($value)) { + // 删除 + return Session::delete($name, $prefix); + } else { + // 设置 + return Session::set($name, $value, $prefix); + } } } @@ -282,23 +316,25 @@ function session($name, $value = '', $prefix = null) * @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 Cookie::get($name); - } elseif (is_null($value)) { - // 删除 - return Cookie::delete($name); - } else { - // 设置 - return Cookie::set($name, $value, $option); +if (!function_exists('cookie')) { + function cookie($name, $value = '', $option = null) + { + if (is_array($name)) { + // 初始化 + Cookie::init($name); + } elseif (is_null($name)) { + // 清除 + Cookie::clear($value); + } elseif ('' === $value) { + // 获取 + return Cookie::get($name); + } elseif (is_null($value)) { + // 删除 + return Cookie::delete($name); + } else { + // 设置 + return Cookie::set($name, $value, $option); + } } } @@ -309,29 +345,31 @@ function cookie($name, $value = '', $option = null) * @param mixed $options 缓存参数 * @return mixed */ -function cache($name, $value = '', $options = null) -{ - if (is_array($options)) { - // 缓存操作的同时初始化 - Cache::connect($options); - } elseif (is_array($name)) { - // 缓存初始化 - return Cache::connect($name); - } - if ('' === $value) { - // 获取缓存 - return Cache::get($name); - } elseif (is_null($value)) { - // 删除缓存 - return Cache::rm($name); - } else { - // 缓存数据 +if (!function_exists('cache')) { + function cache($name, $value = '', $options = null) + { if (is_array($options)) { - $expire = isset($options['expire']) ? $options['expire'] : null; //修复查询缓存无法设置过期时间 - } else { - $expire = is_numeric($options) ? $options : null; //默认快捷缓存设置过期时间 + // 缓存操作的同时初始化 + Cache::connect($options); + } elseif (is_array($name)) { + // 缓存初始化 + return Cache::connect($name); + } + if ('' === $value) { + // 获取缓存 + return 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; //默认快捷缓存设置过期时间 + } + return Cache::set($name, $value, $expire); } - return Cache::set($name, $value, $expire); } } @@ -341,12 +379,14 @@ function cache($name, $value = '', $options = null) * @param string $level 日志级别 * @return void|array */ -function trace($log = '[think]', $level = 'log') -{ - if ('[think]' === $log) { - return Log::getLog(); - } else { - Log::record($log, $level); +if (!function_exists('trace')) { + function trace($log = '[think]', $level = 'log') + { + if ('[think]' === $log) { + return Log::getLog(); + } else { + Log::record($log, $level); + } } } @@ -354,9 +394,11 @@ function trace($log = '[think]', $level = 'log') * 获取当前Request对象实例 * @return Request */ -function request() -{ - return Request::instance(); +if (!function_exists('request')) { + function request() + { + return Request::instance(); + } } /** @@ -367,9 +409,11 @@ function request() * @param string $type * @return Response */ -function response($data = [], $code = 200, $header = [], $type = 'html') -{ - return Response::create($data, $type, $code, $header); +if (!function_exists('response')) { + function response($data = [], $code = 200, $header = [], $type = 'html') + { + return Response::create($data, $type, $code, $header); + } } /** @@ -379,9 +423,11 @@ function response($data = [], $code = 200, $header = [], $type = 'html') * @param integer $code 状态码 * @return \think\response\View */ -function view($template = '', $vars = [], $code = 200) -{ - return Response::create($template, 'view', $code)->vars($vars); +if (!function_exists('view')) { + function view($template = '', $vars = [], $code = 200) + { + return Response::create($template, 'view', $code)->vars($vars); + } } /** @@ -392,9 +438,11 @@ function view($template = '', $vars = [], $code = 200) * @param array $options 参数 * @return \think\response\Json */ -function json($data = [], $code = 200, $header = [], $options = []) -{ - return Response::create($data, 'json', $code, $header, $options); +if (!function_exists('json')) { + function json($data = [], $code = 200, $header = [], $options = []) + { + return Response::create($data, 'json', $code, $header, $options); + } } /** @@ -405,9 +453,11 @@ function json($data = [], $code = 200, $header = [], $options = []) * @param array $options 参数 * @return \think\response\Jsonp */ -function jsonp($data = [], $code = 200, $header = [], $options = []) -{ - return Response::create($data, 'jsonp', $code, $header, $options); +if (!function_exists('jsonp')) { + function jsonp($data = [], $code = 200, $header = [], $options = []) + { + return Response::create($data, 'jsonp', $code, $header, $options); + } } /** @@ -418,9 +468,11 @@ function jsonp($data = [], $code = 200, $header = [], $options = []) * @param array $options 参数 * @return \think\response\Xml */ -function xml($data = [], $code = 200, $header = [], $options = []) -{ - return Response::create($data, 'xml', $code, $header, $options); +if (!function_exists('xml')) { + function xml($data = [], $code = 200, $header = [], $options = []) + { + return Response::create($data, 'xml', $code, $header, $options); + } } /** @@ -430,13 +482,15 @@ function xml($data = [], $code = 200, $header = [], $options = []) * @param integer $code 状态码 * @return \think\response\Redirect */ -function redirect($url = [], $params = [], $code = 302) -{ - if (is_integer($params)) { - $code = $params; - $params = []; +if (!function_exists('redirect')) { + function redirect($url = [], $params = [], $code = 302) + { + if (is_integer($params)) { + $code = $params; + $params = []; + } + return Response::create($url, 'redirect', $code)->params($params); } - return Response::create($url, 'redirect', $code)->params($params); } /** @@ -445,7 +499,9 @@ function redirect($url = [], $params = [], $code = 302) * @param string $message 错误信息 * @param array $header 参数 */ -function abort($code, $message = null, $header = []) -{ - throw new \think\exception\HttpException($code, $message, null, $header); +if (!function_exists('abort')) { + function abort($code, $message = null, $header = []) + { + throw new \think\exception\HttpException($code, $message, null, $header); + } } From 9e98ad237f8aa19f2df69786274b85b6ea44d5df Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 29 Jun 2016 17:25:37 +0800 Subject: [PATCH 539/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BQuery=E7=B1=BB?= =?UTF-8?q?=E7=9A=84view=E6=96=B9=E6=B3=95field=E5=8F=82=E6=95=B0=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E4=BD=BF=E7=94=A8sql=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index b6719410..95213988 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -776,8 +776,13 @@ class Query $fields[] = $alias . '.' . $val; $this->options['map'][$val] = $alias . '.' . $val; } else { - $fields[] = $alias . '.' . $key . ' AS ' . $val; - $this->options['map'][$val] = $alias . '.' . $key; + if (preg_match('/[,=\.\'\"\(\s]/', $key)) { + $name = $key; + } else { + $name = $alias . '.' . $key; + } + $fields[] = $name . ' AS ' . $val; + $this->options['map'][$val] = $name; } } } From 0aa1994ce334916bb889191b4026d0d157a085c5 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 29 Jun 2016 18:05:18 +0800 Subject: [PATCH 540/670] =?UTF-8?q?Query=E7=B1=BB=E6=94=B9=E8=BF=9B=20cach?= =?UTF-8?q?e=E6=96=B9=E6=B3=95=E6=94=AF=E6=8C=81=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E7=BC=93=E5=AD=98=E6=95=B0=E6=8D=AE=EF=BC=88?= =?UTF-8?q?=E4=BB=85=E9=92=88=E5=AF=B9=E4=B8=BB=E9=94=AE=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E3=80=81=E6=9B=B4=E6=96=B0=E5=92=8C=E5=88=A0=E9=99=A4=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 95213988..49604ac0 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1666,6 +1666,7 @@ class Query // 如果存在主键数据 则自动作为更新条件 if (is_string($pk) && isset($data[$pk])) { $where[$pk] = $data[$pk]; + $key = 'think:' . $options['table'] . '|' . $data[$pk]; unset($data[$pk]); } elseif (is_array($pk)) { // 增加复合主键支持 @@ -1692,6 +1693,11 @@ class Query // 获取实际执行的SQL语句 return $this->connection->getRealSql($sql, $this->bind); } else { + // 检测缓存 + if (isset($key) && Cache::get($key)) { + // 删除缓存 + Cache::rm($key); + } // 执行操作 return '' == $sql ? 0 : $this->execute($sql, $this->getBind()); } @@ -1813,8 +1819,12 @@ class Query $result = false; if (empty($options['fetch_sql']) && !empty($options['cache'])) { // 判断查询缓存 - $cache = $options['cache']; - $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options)); + $cache = $options['cache']; + if (true === $cache['key'] && !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) { @@ -1964,6 +1974,10 @@ class Query $options = $this->parseExpress(); if (!is_null($data) && true !== $data) { + if (!is_array($data)) { + // 缓存标识 + $key = 'think:' . $options['table'] . '|' . $data; + } // AR模式分析主键条件 $this->parsePkWhere($data, $options); } @@ -1974,10 +1988,17 @@ class Query } // 生成删除SQL语句 $sql = $this->builder()->delete($options); + if ($options['fetch_sql']) { // 获取实际执行的SQL语句 return $this->connection->getRealSql($sql, $this->bind); } + + // 检测缓存 + if (isset($key) && Cache::get($key)) { + // 删除缓存 + Cache::rm($key); + } // 执行操作 return $this->execute($sql, $this->getBind()); } From 73fdd134829c84680a5e0e37616d68bd2ffc171f Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 29 Jun 2016 15:10:43 +0800 Subject: [PATCH 541/670] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 6 ++++++ library/think/exception/Handle.php | 4 +++- tpl/think_exception.tpl | 25 ++++++++++++++++++++++++- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 99613ac6..9865d1d3 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -349,6 +349,12 @@ class App self::$debug = Config::get('app_debug'); if (!self::$debug) { ini_set('display_errors', 'Off'); + } else { + //重新申请一块比较大的buffer + if (ob_get_level() > 0) { + ob_end_clean(); + } + ob_start(); } // 应用命名空间 diff --git a/library/think/exception/Handle.php b/library/think/exception/Handle.php index 7efe241c..a598df8c 100644 --- a/library/think/exception/Handle.php +++ b/library/think/exception/Handle.php @@ -155,8 +155,10 @@ class Handle while (ob_get_level() > 1) { ob_end_clean(); } + + $data['echo'] = ob_get_clean(); + ob_start(); - ob_implicit_flush(0); extract($data); include Config::get('exception_tmpl'); // 获取并清空缓存 diff --git a/tpl/think_exception.tpl b/tpl/think_exception.tpl index 5fadd7cc..aabf82a8 100644 --- a/tpl/think_exception.tpl +++ b/tpl/think_exception.tpl @@ -123,6 +123,26 @@ .line-error{ background: #f8cbcb; } + + .echo table { + width: 100%; + } + + .echo pre { + padding: 16px; + overflow: auto; + font-size: 85%; + line-height: 1.45; + background-color: #f7f7f7; + border: 0; + border-radius: 3px; + font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; + } + + .echo pre > pre { + padding: 0; + margin: 0; + } /* Exception Info */ .exception .message{ @@ -130,7 +150,7 @@ border: 1px solid #ddd; border-bottom: 0 none; line-height: 18px; - font-size:16px; + font-size:16px; border-top-left-radius: 4px; border-top-right-radius: 4px; font-family: Consolas,"Liberation Mono",Courier,Verdana,"微软雅黑"; @@ -258,6 +278,9 @@ +
+ +
From d9a959904377cd7fe9f619efebb869c598e5693d Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Wed, 29 Jun 2016 15:35:32 +0800 Subject: [PATCH 542/670] =?UTF-8?q?=E7=8E=AF=E5=A2=83=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E4=B8=8D=E5=8C=BA=E5=88=86=E5=A4=A7=E5=B0=8F=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base.php | 4 +++- library/think/App.php | 5 ++++- library/think/Config.php | 8 ++++---- tpl/think_exception.tpl | 7 +++++-- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/base.php b/base.php index 052febe7..7ab5a9ab 100644 --- a/base.php +++ b/base.php @@ -44,9 +44,11 @@ require CORE_PATH . 'Loader.php'; if (is_file(ROOT_PATH . 'env' . EXT)) { $env = include ROOT_PATH . 'env' . EXT; foreach ($env as $key => $val) { - $name = ENV_PREFIX . $key; + $name = ENV_PREFIX . strtoupper($key); if (is_bool($val)) { $val = $val ? 1 : 0; + } elseif (!is_scalar($val)) { + continue; } putenv("$name=$val"); } diff --git a/library/think/App.php b/library/think/App.php index 9865d1d3..f03c31f8 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -352,9 +352,12 @@ class App } else { //重新申请一块比较大的buffer if (ob_get_level() > 0) { - ob_end_clean(); + $output = ob_get_clean(); } ob_start(); + if (!empty($output)) { + echo $output; + } } // 应用命名空间 diff --git a/library/think/Config.php b/library/think/Config.php index 330e57f1..105920b1 100644 --- a/library/think/Config.php +++ b/library/think/Config.php @@ -81,7 +81,7 @@ class Config if (!strpos($name, '.')) { // 判断环境变量 - $result = getenv(ENV_PREFIX . $name); + $result = getenv(ENV_PREFIX . strtoupper($name)); if (false !== $result) { return $result; } @@ -89,7 +89,7 @@ class Config } else { // 二维数组设置和获取支持 $name = explode('.', $name); - $result = getenv(ENV_PREFIX . $name[0] . '_' . $name[1]); + $result = getenv(ENV_PREFIX . strtoupper($name[0] . '_' . $name[1])); // 判断环境变量 if (false !== $result) { return $result; @@ -113,7 +113,7 @@ class Config } if (!strpos($name, '.')) { - $result = getenv(ENV_PREFIX . $name); + $result = getenv(ENV_PREFIX . strtoupper($name)); if (false !== $result) { return $result; } @@ -122,7 +122,7 @@ class Config } else { // 二维数组设置和获取支持 $name = explode('.', $name); - $result = getenv(ENV_PREFIX . $name[0] . '_' . $name[1]); + $result = getenv(ENV_PREFIX . strtoupper($name[0] . '_' . $name[1])); // 判断环境变量 if (false !== $result) { return $result; diff --git a/tpl/think_exception.tpl b/tpl/think_exception.tpl index aabf82a8..a978f1de 100644 --- a/tpl/think_exception.tpl +++ b/tpl/think_exception.tpl @@ -83,11 +83,11 @@

:)

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

[ V5.0 版本由 七牛云 独家赞助发布 ]
'; - $this->expectOutputString($expectOutputString); - $rc = new ReflectionClass('\think\Loader'); - $ns = $rc->getProperty('prefixDirsPsr4'); - $ns->setAccessible(true); - $namespace = $ns->getValue(); - $this->assertEquals([realpath(TEST_PATH)], $namespace['tests\\']); + $this->assertEquals($expectOutputString, $response->getContent()); + $this->assertEquals(200, $response->getCode()); $this->assertEquals(true, function_exists('lang')); $this->assertEquals(true, function_exists('config')); diff --git a/tests/thinkphp/library/think/paginateTest.php b/tests/thinkphp/library/think/paginateTest.php new file mode 100644 index 00000000..949b8c97 --- /dev/null +++ b/tests/thinkphp/library/think/paginateTest.php @@ -0,0 +1,44 @@ + +// +---------------------------------------------------------------------- + +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 From d127f13bd81876f970b4b9be382bcc579a2f481b Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Thu, 14 Jul 2016 10:46:50 +0800 Subject: [PATCH 662/670] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E6=97=A0=E7=94=A8=E7=9A=84=E7=8E=AF=E5=A2=83?= =?UTF-8?q?=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .travis.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 94de5bee..96a9dffc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,13 +37,13 @@ script: ## LINT - find . -path ./vendor -prune -o -type f -name \*.php -exec php -l {} \; ## PHP_CodeSniffer - - THINK_AUTOLOAD=0 vendor/bin/phpcs --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 --standard=PSR2 --ignore="vendor/*" ./ + - 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 - - THINK_AUTOLOAD=0 vendor/bin/phpcpd --verbose --exclude vendor ./ || true + - vendor/bin/phpcpd --verbose --exclude vendor ./ || true ## PHPLOC - - THINK_AUTOLOAD=0 vendor/bin/phploc --exclude vendor ./ + - vendor/bin/phploc --exclude vendor ./ ## PHPUNIT - - THINK_AUTOLOAD=0 vendor/bin/phpunit --coverage-clover=coverage.xml --configuration=phpunit.xml + - vendor/bin/phpunit --coverage-clover=coverage.xml --configuration=phpunit.xml after_success: - bash <(curl -s https://codecov.io/bash) From 8831298e8fbf414efbe9e7563f50f59eaf94ef3f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 14 Jul 2016 10:55:43 +0800 Subject: [PATCH 663/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BMerge=E7=B1=BBsave?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Merge.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/think/model/Merge.php b/library/think/model/Merge.php index 2239af73..1bf634f4 100644 --- a/library/think/model/Merge.php +++ b/library/think/model/Merge.php @@ -224,7 +224,7 @@ class Merge extends Model } // 处理模型数据 - $data = $this->parseData($this->name, $this->data); + $data = $this->parseData($this->name, $this->data, true); // 写入主表数据 $result = $db->name($this->name)->strict(false)->insert($data, $replace); if ($result) { From d38543ca1e4bad637d30ba8167bcf900ad8f3f0f Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 14 Jul 2016 13:49:34 +0800 Subject: [PATCH 664/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=20make:controller=20?= =?UTF-8?q?=20make:model=20=E6=8C=87=E4=BB=A4=E7=9A=84=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/console/command/make/Controller.php | 2 +- library/think/console/command/make/Model.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/think/console/command/make/Controller.php b/library/think/console/command/make/Controller.php index 08a792a2..df727048 100644 --- a/library/think/console/command/make/Controller.php +++ b/library/think/console/command/make/Controller.php @@ -28,7 +28,7 @@ class Controller extends Make ->setName('make:controller') ->setDescription('Create a new controller class') ->addArgument('namespace', Argument::REQUIRED) - ->addOption('module', 'm', Option::VALUE_OPTIONAL, 'Module Name', null) + ->addOption('module', 'm', Option::VALUE_OPTIONAL, 'Module Name', 'index') ->addOption('extend', 'e', Option::VALUE_OPTIONAL, 'Base on Controller class', null); } diff --git a/library/think/console/command/make/Model.php b/library/think/console/command/make/Model.php index 7c7831aa..af741382 100644 --- a/library/think/console/command/make/Model.php +++ b/library/think/console/command/make/Model.php @@ -28,7 +28,7 @@ class Model extends Make ->setName('make:model') ->setDescription('Create a new model class') ->addArgument('namespace', Argument::REQUIRED) - ->addOption('module', 'm', Option::VALUE_OPTIONAL, 'Module Name', null) + ->addOption('module', 'm', Option::VALUE_OPTIONAL, 'Module Name', 'index') ->addOption('extend', 'e', Option::VALUE_OPTIONAL, 'Base on Model class', null); } From 371ecbc57aaf43988508058959dce2d59b1a673c Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Thu, 14 Jul 2016 15:55:09 +0800 Subject: [PATCH 665/670] =?UTF-8?q?json=E8=BE=93=E5=87=BA=E6=97=B6?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E7=BC=96=E7=A0=81=E5=A4=B1=E8=B4=A5=E5=90=8E?= =?UTF-8?q?=E6=8A=9B=E5=87=BA=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/response/Json.php | 8 +++++++- library/think/response/Jsonp.php | 13 ++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/library/think/response/Json.php b/library/think/response/Json.php index f3cfc36f..a137f453 100644 --- a/library/think/response/Json.php +++ b/library/think/response/Json.php @@ -19,8 +19,9 @@ class Json extends Response protected $options = [ 'json_encode_param' => JSON_UNESCAPED_UNICODE, ]; - + protected $contentType = 'application/json'; + /** * 处理数据 * @access protected @@ -31,6 +32,11 @@ class Json extends Response { // 返回JSON数据格式到客户端 包含状态信息 $data = json_encode($data, $this->options['json_encode_param']); + + if ($data === false) { + throw new \InvalidArgumentException(json_last_error_msg()); + } + return $data; } diff --git a/library/think/response/Jsonp.php b/library/think/response/Jsonp.php index b6806575..fda1183a 100644 --- a/library/think/response/Jsonp.php +++ b/library/think/response/Jsonp.php @@ -22,7 +22,7 @@ class Jsonp extends Response 'default_jsonp_handler' => 'jsonpReturn', 'json_encode_param' => JSON_UNESCAPED_UNICODE, ]; - + protected $contentType = 'application/javascript'; /** @@ -35,8 +35,15 @@ class Jsonp extends Response { // 返回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']; - $data = $handler . '(' . json_encode($data, $this->options['json_encode_param']) . ');'; + $handler = !empty($var_jsonp_handler) ? $var_jsonp_handler : $this->options['default_jsonp_handler']; + + $data = json_encode($data, $this->options['json_encode_param']); + + if ($data === false) { + throw new \InvalidArgumentException(json_last_error_msg()); + } + + $data = $handler . '(' . $data . ');'; return $data; } From b4823a60f35f0011117197c6e785d51f11939142 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 14 Jul 2016 16:34:43 +0800 Subject: [PATCH 666/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BRelation=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E5=85=B3=E8=81=94=E5=AE=9A=E4=B9=89=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E5=AF=B9=E8=B1=A1=20=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E8=BF=94=E5=9B=9ERelation=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/model/Relation.php | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index d762afd5..515bf362 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -43,6 +43,8 @@ class Relation protected $alias; // 当前关联的JOIN类型 protected $joinType; + // 关联模型查询对象 + protected $query; /** * 架构函数 @@ -409,7 +411,7 @@ class Relation $this->localKey = $localKey; $this->alias = $alias; $this->joinType = $joinType; - + $this->query = (new $model)->db(); // 返回关联的模型对象 return $this; } @@ -433,7 +435,7 @@ class Relation $this->localKey = $otherKey; $this->alias = $alias; $this->joinType = $joinType; - + $this->query = (new $model)->db(); // 返回关联的模型对象 return $this; } @@ -455,7 +457,7 @@ class Relation $this->foreignKey = $foreignKey; $this->localKey = $localKey; $this->alias = $alias; - + $this->query = (new $model)->db(); // 返回关联的模型对象 return $this; } @@ -481,7 +483,7 @@ class Relation $this->throughKey = $throughKey; $this->localKey = $localKey; $this->alias = $alias; - + $this->query = (new $model)->db(); // 返回关联的模型对象 return $this; } @@ -505,7 +507,7 @@ class Relation $this->localKey = $localKey; $this->middle = $table; $this->alias = $alias; - + $this->query = (new $model)->db(); // 返回关联的模型对象 return $this; } @@ -653,14 +655,12 @@ class Relation public function __call($method, $args) { - if ($this->model) { - $model = new $this->model; - $db = $model->db(); + if ($this->query) { switch ($this->type) { case self::HAS_MANY: if (isset($this->parent->{$this->localKey})) { // 关联查询带入关联条件 - $db->where($this->foreignKey, $this->parent->{$this->localKey}); + $this->query->where($this->foreignKey, $this->parent->{$this->localKey}); } break; case self::HAS_MANY_THROUGH: @@ -671,13 +671,18 @@ class Relation $pk = (new $this->model)->getPk(); $throughKey = $this->throughKey; $modelTable = $this->parent->getTable(); - $result = $db->field($alias . '.*')->alias($alias) + $result = $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; } - return call_user_func_array([$db, $method], $args); + $result = call_user_func_array([$this->query, $method], $args); + if ($result instanceof \think\db\Query) { + return $this; + } else { + return $result; + } } else { throw new Exception('method not exists:' . __CLASS__ . '->' . $method); } From 9bdc1e0c64d0c0403473d9062e39bf1d727eccad Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 14 Jul 2016 16:56:15 +0800 Subject: [PATCH 667/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Route=E7=B1=BB?= =?UTF-8?q?=E4=B8=80=E5=A4=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Route.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/library/think/Route.php b/library/think/Route.php index de0bc30c..55fde12c 100644 --- a/library/think/Route.php +++ b/library/think/Route.php @@ -672,6 +672,8 @@ class Route if ($checkDomain) { self::checkDomain($request); } + // 获取当前请求类型的路由规则 + $rules = self::$rules[$request->method()]; // 检测URL绑定 $return = self::checkUrlBind($url, $rules, $depr); @@ -679,9 +681,6 @@ class Route return $return; } - // 获取当前请求类型的路由规则 - $rules = self::$rules[$request->method()]; - if (isset($rules[$url])) { // 静态路由规则检测 $rule = $rules[$url]; From 2b88407f7abc3c6db1aa011b146c4fcf95ca940b Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 14 Jul 2016 17:02:37 +0800 Subject: [PATCH 668/670] =?UTF-8?q?=E6=94=B9=E8=BF=9BSqlsrv=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/connector/Sqlsrv.php | 1 - 1 file changed, 1 deletion(-) diff --git a/library/think/db/connector/Sqlsrv.php b/library/think/db/connector/Sqlsrv.php index cfc80991..31cf9045 100644 --- a/library/think/db/connector/Sqlsrv.php +++ b/library/think/db/connector/Sqlsrv.php @@ -24,7 +24,6 @@ class Sqlsrv extends Connection PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_STRINGIFY_FETCHES => false, - PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8, ]; /** From d3c5c6f1662abe9f8a9cc22d5de9c5353c4612a2 Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Thu, 14 Jul 2016 18:05:30 +0800 Subject: [PATCH 669/670] =?UTF-8?q?=E6=94=B9=E8=BF=9Bmake=E5=91=BD?= =?UTF-8?q?=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Console.php | 1 - library/think/console/command/Make.php | 148 +++++++++++------- .../think/console/command/make/Controller.php | 42 ++--- library/think/console/command/make/File.php | 49 ------ library/think/console/command/make/Model.php | 30 ++-- .../command/make/stubs/controller.plain.stub | 10 ++ .../command/make/stubs/controller.stub | 84 ++++++++++ .../console/command/make/stubs/model.stub | 10 ++ tpl/make.tpl | 17 -- 9 files changed, 227 insertions(+), 164 deletions(-) delete mode 100644 library/think/console/command/make/File.php create mode 100644 library/think/console/command/make/stubs/controller.plain.stub create mode 100644 library/think/console/command/make/stubs/controller.stub create mode 100644 library/think/console/command/make/stubs/model.stub delete mode 100644 tpl/make.tpl diff --git a/library/think/Console.php b/library/think/Console.php index d0388864..991e3a7d 100644 --- a/library/think/Console.php +++ b/library/think/Console.php @@ -50,7 +50,6 @@ class Console "think\\console\\command\\Lists", "think\\console\\command\\Build", "think\\console\\command\\make\\Controller", - "think\\console\\command\\make\\File", "think\\console\\command\\make\\Model", "think\\console\\command\\optimize\\Autoload", ]; diff --git a/library/think/console/command/Make.php b/library/think/console/command/Make.php index b9ea6fdb..6dd754c7 100644 --- a/library/think/console/command/Make.php +++ b/library/think/console/command/Make.php @@ -11,82 +11,110 @@ namespace think\console\command; -use think\App; -use think\Exception; +use think\Config; +use think\console\Input; +use think\console\input\Argument; +use think\console\Output; -class Make extends Command +abstract class Make extends Command { + /** @var Input */ + protected $input; - // 创建文件 - protected static function buildFile($file, $content) + /** @var Output */ + protected $output; + + protected $type; + + abstract protected function getStub(); + + protected function configure() { - if (is_file($file)) { - throw new Exception('file already exists'); - } - - if (!is_dir(dirname($file))) { - mkdir(strtolower(dirname($file)), 0755, true); - } - - file_put_contents($file, $content); + $this->addArgument('name', Argument::REQUIRED, "The name of the class"); } - // 生成类库文件 - protected function build($namespace, $extend, $content = '') + public function run(Input $input, Output $output) { - $tpl = file_get_contents(THINK_PATH . 'tpl' . DS . 'make.tpl'); - - // comminute namespace - $namespace = explode('\\', $namespace); - $className = array_pop($namespace); - - if ($extend) { - $extend = 'extends \\' . ltrim($extend, '\\'); - } - // 处理内容 - $content = str_replace(['{%extend%}', '{%className%}', '{%namespace%}', '{%content%}'], - [$extend, $className, implode('\\', $namespace), $content], - $tpl); - - // 处理文件名 - array_shift($namespace); - $file = APP_PATH . implode(DS, $namespace) . DS . $className . '.php'; - // 生成类库文件 - self::buildFile($file, $content); - - return realpath($file); + $this->input = $input; + $this->output = $output; + return parent::run($input, $output); } - protected function getResult($layer, $namespace, $module, $extend, $content = '') + protected function execute(Input $input, Output $output) { - // 处理命名空间 - if (!empty($module)) { - $namespace = App::$namespace . "\\" . $module . "\\" . $layer . "\\" . $namespace; + $name = trim($input->getArgument('name')); + + $classname = $this->getClassName($name); + + $pathname = $this->getPathName($classname); + + if (is_file($pathname)) { + $output->writeln('' . $this->type . ' already exists!'); + return false; } - // 处理继承 - if (empty($extend)) { - switch ($layer) { - case 'model': - $extend = '\\think\\Model'; - break; - case 'validate': - $extend = '\\think\\Validate'; - break; - case 'controller': - default: - $extend = ''; - break; + if (!is_dir(dirname($pathname))) { + mkdir(strtolower(dirname($pathname)), 0755, true); + } + + file_put_contents($pathname, $this->buildClass($name)); + + $output->writeln('' . $this->type . ' created successfully.'); + + } + + protected function buildClass($name) + { + $stub = file_get_contents($this->getStub()); + + $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\'); + + $class = str_replace($namespace . '\\', '', $name); + + return str_replace(['{%className%}', '{%namespace%}', '{%app_namespace%}'], [ + $class, + $namespace, + Config::get('app_namespace') + ], $stub); + + } + + protected function getPathName($name) + { + $name = str_replace(Config::get('app_namespace') . '\\', '', $name); + + return APP_PATH . str_replace('\\', '/', $name) . '.php'; + } + + protected function getClassName($name) + { + $appNamespace = Config::get('app_namespace'); + + if (strpos($name, $appNamespace . '\\') === 0) { + return $name; + } + + if (Config::get('app_multi_module')) { + if (strpos($name, '/')) { + list($module, $name) = explode('/', $name, 2); + } else { + $module = 'common'; } } else { - if (!preg_match("/\\\/", $extend)) { - if (!empty($module)) { - $extend = "\\" . App::$namespace . "\\" . $module . "\\" . $layer . "\\" . $extend; - } - } + $module = null; } - return $this->build($namespace, $extend, $content); + if (strpos($name, '/') !== false) { + $name = str_replace('/', '\\', $name); + } + + return $this->getNamespace($appNamespace, $module) . '\\' . $name; } + + protected function getNamespace($appNamespace, $module) + { + return $module ? ($appNamespace . '\\' . $module) : $appNamespace; + } + } diff --git a/library/think/console/command/make/Controller.php b/library/think/console/command/make/Controller.php index df727048..afa7be90 100644 --- a/library/think/console/command/make/Controller.php +++ b/library/think/console/command/make/Controller.php @@ -11,34 +11,40 @@ namespace think\console\command\make; +use think\Config; use think\console\command\Make; -use think\console\Input; -use think\console\input\Argument; use think\console\input\Option; -use think\console\Output; class Controller extends Make { - /** - * {@inheritdoc} - */ + + protected $type = "Controller"; + protected function configure() { - $this - ->setName('make:controller') - ->setDescription('Create a new controller class') - ->addArgument('namespace', Argument::REQUIRED) - ->addOption('module', 'm', Option::VALUE_OPTIONAL, 'Module Name', 'index') - ->addOption('extend', 'e', Option::VALUE_OPTIONAL, 'Base on Controller class', null); + parent::configure(); + $this->setName('make:controller') + ->addOption('plain', null, Option::VALUE_NONE, 'Generate an empty controller class.') + ->setDescription('Create a new resource controller class'); } - protected function execute(Input $input, Output $output) + protected function getStub() { - $namespace = $input->getArgument('namespace'); - $module = $input->getOption('module'); - $extend = $input->getOption('extend'); - $result = $this->getResult('controller', $namespace, $module, $extend); - $output->writeln("output:" . $result); + if ($this->input->getOption('plain')) { + return __DIR__ . '/stubs/controller.plain.stub'; + } + + return __DIR__ . '/stubs/controller.stub'; + } + + protected function getClassName($name) + { + return parent::getClassName($name) . (Config::get('controller_suffix') ? ucfirst(Config::get('url_controller_layer')) : ''); + } + + protected function getNamespace($appNamespace, $module) + { + return parent::getNamespace($appNamespace, $module) . '\controller'; } } diff --git a/library/think/console/command/make/File.php b/library/think/console/command/make/File.php deleted file mode 100644 index 9b3b9b5f..00000000 --- a/library/think/console/command/make/File.php +++ /dev/null @@ -1,49 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace think\console\command\make; - -use think\console\command\Make; -use think\console\Input; -use think\console\input\Argument; -use think\console\input\Option; -use think\console\Output; - -class File extends Make -{ - /** - * {@inheritdoc} - */ - protected function configure() - { - $this - ->setName('make:file') - ->setDescription('Create a new applcation class') - ->addArgument('namespace', Argument::REQUIRED) - ->addOption('layer', 'l', Option::VALUE_OPTIONAL, 'Layer Name', null) - ->addOption('extend', 'e', Option::VALUE_OPTIONAL, 'Extend Base class', null); - } - - protected function execute(Input $input, Output $output) - { - $namespace = $input->getArgument('namespace'); - $extend = $input->getOption('extend'); - if (!$layer = $input->getOption('layer')) { - // 自动识别layer - $item = explode('\\', $namespace); - $layer = basename(dirname(implode(DS, $item))); - } - - $result = $this->getResult($layer, $namespace, '', $extend); - $output->writeln("output:" . $result); - } - -} diff --git a/library/think/console/command/make/Model.php b/library/think/console/command/make/Model.php index af741382..d4e9b5dd 100644 --- a/library/think/console/command/make/Model.php +++ b/library/think/console/command/make/Model.php @@ -12,33 +12,25 @@ namespace think\console\command\make; use think\console\command\Make; -use think\console\Input; -use think\console\input\Argument; -use think\console\input\Option; -use think\console\Output; class Model extends Make { - /** - * {@inheritdoc} - */ + protected $type = "Model"; + protected function configure() { - $this - ->setName('make:model') - ->setDescription('Create a new model class') - ->addArgument('namespace', Argument::REQUIRED) - ->addOption('module', 'm', Option::VALUE_OPTIONAL, 'Module Name', 'index') - ->addOption('extend', 'e', Option::VALUE_OPTIONAL, 'Base on Model class', null); + parent::configure(); + $this->setName('make:model') + ->setDescription('Create a new model class'); } - protected function execute(Input $input, Output $output) + protected function getStub() { - $namespace = $input->getArgument('namespace'); - $module = $input->getOption('module'); - $extend = $input->getOption('extend'); - $result = $this->getResult('model', $namespace, $module, $extend); - $output->writeln("output:" . $result); + return __DIR__ . '/stubs/model.stub'; } + protected function getNamespace($appNamespace, $module) + { + return parent::getNamespace($appNamespace, $module) . '\model'; + } } diff --git a/library/think/console/command/make/stubs/controller.plain.stub b/library/think/console/command/make/stubs/controller.plain.stub new file mode 100644 index 00000000..b7539dcf --- /dev/null +++ b/library/think/console/command/make/stubs/controller.plain.stub @@ -0,0 +1,10 @@ + -// +---------------------------------------------------------------------- - -namespace {%namespace%}; - -class {%className%} {%extend%} -{ -{%content%} -} From f5771d0eb154bcf4d0b6be06d190b248385eddeb Mon Sep 17 00:00:00 2001 From: yunwuxin <448901948@qq.com> Date: Thu, 14 Jul 2016 18:14:18 +0800 Subject: [PATCH 670/670] =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/console/command/Make.php | 2 +- library/think/console/command/make/stubs/controller.stub | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/library/think/console/command/Make.php b/library/think/console/command/Make.php index 6dd754c7..2829ee3c 100644 --- a/library/think/console/command/Make.php +++ b/library/think/console/command/Make.php @@ -58,7 +58,7 @@ abstract class Make extends Command mkdir(strtolower(dirname($pathname)), 0755, true); } - file_put_contents($pathname, $this->buildClass($name)); + file_put_contents($pathname, $this->buildClass($classname)); $output->writeln('' . $this->type . ' created successfully.'); diff --git a/library/think/console/command/make/stubs/controller.stub b/library/think/console/command/make/stubs/controller.stub index 70c30c34..870ce5cf 100644 --- a/library/think/console/command/make/stubs/controller.stub +++ b/library/think/console/command/make/stubs/controller.stub @@ -3,6 +3,7 @@ namespace {%namespace%}; use think\Controller; +use think\Request; class {%className%} extends Controller {